1
0
mirror of https://github.com/musix-org/musix-oss synced 2024-11-14 03:30:18 +00:00
musix-oss/node_modules/firebase/firebase-firestore.min.js.map
2020-03-03 22:30:50 +02:00

1 line
2.4 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"version":3,"file":"firebase-firestore.min.js","sources":["../../node_modules/tslib/tslib.es6.js","../logger/src/logger.ts","../util/src/environment.ts","../util/src/errors.ts","../component/src/component.ts","../../node_modules/closure-builder/third_party/closure-library/closure/goog/base.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/disposable/disposable.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/array/array.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/string/internal.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/useragent/util.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/object/object.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/reflect/reflect.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/useragent/useragent.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/useragent/browser.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/useragent/engine.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/browserfeature.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/event.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/browserevent.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/eventtype.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/listenable.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/listener.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/listenermap.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/events.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/eventtarget.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/json/json.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/freelist.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/workqueue.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/run.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/nexttick.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/timer/timer.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/throttle.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/eventhandler.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/requeststats.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/errorcode.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/eventtype.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/xmlhttpfactory.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/xmlhttp.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/environment.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/structs/structs.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/structs/map.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/string/string.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/uri/utils.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/uri/uri.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/basetestchannel.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/connectionstate.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/structs/set.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/wire.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/debug/formatter.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/json/nativejsonprocessor.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/wirev8.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/netutils.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/json/hybrid.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/xhrio.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/httpstatus.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/rpc/httpcors.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/string/path.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchanneltransport.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/functions/functions.js","../webchannel-wrapper/src/index.js","../firestore/src/util/log.ts","../firestore/src/core/version.ts","../firestore/src/util/assert.ts","../firestore/src/util/misc.ts","../firestore/src/core/database_info.ts","../firestore/src/core/types.ts","../firestore/src/api/credentials.ts","../firestore/src/auth/user.ts","../firestore/src/util/error.ts","../firestore/src/util/obj.ts","../firestore/src/util/input_validation.ts","../firestore/src/api/geo_point.ts","../firestore/src/api/timestamp.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/transform_operation.ts","../firestore/src/model/mutation.ts","../firestore/src/model/field_value.ts","../firestore/src/model/document.ts","../firestore/src/util/types.ts","../firestore/src/core/target.ts","../firestore/src/core/query.ts","../firestore/src/local/target_data.ts","../firestore/src/remote/existence_filter.ts","../firestore/src/remote/rpc_error.ts","../firestore/src/model/collections.ts","../firestore/src/model/document_set.ts","../firestore/src/core/view_snapshot.ts","../firestore/src/remote/watch_change.ts","../firestore/src/remote/remote_event.ts","../firestore/src/remote/serializer.ts","../firestore/src/platform/platform.ts","../firestore/src/util/api.ts","../firestore/src/api/blob.ts","../firestore/src/util/promise.ts","../firestore/src/util/obj_map.ts","../firestore/src/model/mutation_batch.ts","../firestore/src/local/reference_set.ts","../firestore/src/local/persistence_promise.ts","../firestore/src/local/remote_document_change_buffer.ts","../firestore/src/local/persistence.ts","../firestore/src/local/local_documents_view.ts","../firestore/src/local/local_view_changes.ts","../firestore/src/core/listen_sequence.ts","../firestore/src/util/async_queue.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/local/local_store.ts","../firestore/src/api/field_path.ts","../firestore/src/api/field_value.ts","../firestore/src/api/user_data_converter.ts","../firestore/src/remote/backoff.ts","../firestore/src/remote/persistent_stream.ts","../firestore/src/remote/datastore.ts","../firestore/src/core/transaction.ts","../firestore/src/remote/online_state_tracker.ts","../firestore/src/remote/remote_store.ts","../firestore/src/local/shared_client_state_schema.ts","../firestore/src/local/shared_client_state.ts","../firestore/src/core/target_id_generator.ts","../firestore/src/core/view.ts","../firestore/src/core/sync_engine.ts","../firestore/src/core/event_manager.ts","../firestore/src/core/transaction_runner.ts","../firestore/src/local/encoded_resource_path.ts","../firestore/src/local/simple_db.ts","../firestore/src/local/indexeddb_mutation_queue.ts","../firestore/src/local/indexeddb_target_cache.ts","../firestore/src/local/indexeddb_remote_document_cache.ts","../firestore/src/local/memory_index_manager.ts","../firestore/src/local/indexeddb_schema.ts","../firestore/src/local/indexeddb_index_manager.ts","../firestore/src/local/local_serializer.ts","../firestore/src/local/indexeddb_persistence.ts","../firestore/src/local/index_free_query_engine.ts","../firestore/src/local/memory_mutation_queue.ts","../firestore/src/core/firestore_client.ts","../firestore/src/local/memory_remote_document_cache.ts","../firestore/src/local/memory_target_cache.ts","../firestore/src/local/memory_persistence.ts","../firestore/src/util/async_observer.ts","../firestore/src/api/observer.ts","../firestore/src/api/database.ts","../firestore/src/platform/config.ts","../firestore/src/remote/connectivity_monitor_noop.ts","../firestore/src/platform_browser/browser_connectivity_monitor.ts","../firestore/src/remote/stream_bridge.ts","../firestore/src/platform_browser/webchannel_connection.ts","../firestore/src/platform_browser/browser_platform.ts","../firestore/src/platform_browser/browser_init.ts","../firestore/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * 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\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 * 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 switch (logType) {\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 */\n case LogLevel.DEBUG:\n console.log(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.VERBOSE:\n console.log(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.INFO:\n console.info(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.WARN:\n console.warn(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.ERROR:\n console.error(`[${now}] ${instance.name}:`, ...args);\n break;\n default:\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 get logLevel(): LogLevel {\n return this._logLevel;\n }\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n }\n\n /**\n * The log handler for the Logger instance.\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 functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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';\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.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\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 * @license\n * Copyright 2017 Google Inc.\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.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]: StringLike | undefined;\n}\n\nexport interface FirebaseError extends Error, ErrorData {\n // Unique code for error - format is service/error-code-string.\n readonly code: string;\n\n // Developer-friendly error message.\n readonly message: string;\n\n // Always 'FirebaseError'.\n readonly name: typeof ERROR_NAME;\n\n // Where available - stack backtrace in a string.\n readonly stack?: string;\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 readonly name = ERROR_NAME;\n\n constructor(readonly code: string, message: string) {\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);\n\n // Keys with an underscore at the end of their name are not included in\n // error.data for some reason.\n // TODO: Replace with Object.entries when lib is updated to es2017.\n for (const key of Object.keys(customData)) {\n if (key.slice(-1) !== '_') {\n if (key in error) {\n console.warn(\n `Overwriting FirebaseError base field \"${key}\" can cause unexpected behavior.`\n );\n }\n error[key] = customData[key];\n }\n }\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 ? value.toString() : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2019 Google Inc.\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} 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 /**\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","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Bootstrap for the Google JS Library (Closure).\r\n *\r\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\r\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\r\n * to include their own deps file(s) from different locations.\r\n *\r\n * Avoid including base.js more than once. This is strictly discouraged and not\r\n * supported. goog.require(...) won't work properly in that case.\r\n *\r\n * @provideGoog\r\n */\r\n\r\n\r\n/**\r\n * @define {boolean} Overridden to true by the compiler.\r\n */\r\nvar COMPILED = false;\r\n\r\n\r\n/**\r\n * Base namespace for the Closure library. Checks to see goog is already\r\n * defined in the current scope before assigning to prevent clobbering if\r\n * base.js is loaded more than once.\r\n *\r\n * @const\r\n */\r\nvar goog = goog || {};\r\n\r\n/**\r\n * Reference to the global context. In most cases this will be 'window'.\r\n * @const\r\n * @suppress {newCheckTypes}\r\n */\r\ngoog.global = this;\r\n\r\n\r\n/**\r\n * A hook for overriding the define values in uncompiled mode.\r\n *\r\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\r\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\r\n * `goog.define` will use the value instead of the default value. This\r\n * allows flags to be overwritten without compilation (this is normally\r\n * accomplished with the compiler's \"define\" flag).\r\n *\r\n * Example:\r\n * <pre>\r\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\r\n * </pre>\r\n *\r\n * @type {Object<string, (string|number|boolean)>|undefined}\r\n */\r\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\r\n\r\n\r\n/**\r\n * A hook for overriding the define values in uncompiled or compiled mode,\r\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\r\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\r\n *\r\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\r\n * string literals or the compiler will emit an error.\r\n *\r\n * While any @define value may be set, only those set with goog.define will be\r\n * effective for uncompiled code.\r\n *\r\n * Example:\r\n * <pre>\r\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\r\n * </pre>\r\n *\r\n * @type {Object<string, (string|number|boolean)>|undefined}\r\n */\r\ngoog.global.CLOSURE_DEFINES;\r\n\r\n\r\n/**\r\n * Returns true if the specified value is not undefined.\r\n *\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is defined.\r\n */\r\ngoog.isDef = function(val) {\r\n // void 0 always evaluates to undefined and hence we do not need to depend on\r\n // the definition of the global variable named 'undefined'.\r\n return val !== void 0;\r\n};\r\n\r\n/**\r\n * Returns true if the specified value is a string.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a string.\r\n */\r\ngoog.isString = function(val) {\r\n return typeof val == 'string';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is a boolean.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is boolean.\r\n */\r\ngoog.isBoolean = function(val) {\r\n return typeof val == 'boolean';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is a number.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a number.\r\n */\r\ngoog.isNumber = function(val) {\r\n return typeof val == 'number';\r\n};\r\n\r\n\r\n/**\r\n * Builds an object structure for the provided namespace path, ensuring that\r\n * names that already exist are not overwritten. For example:\r\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\r\n * Used by goog.provide and goog.exportSymbol.\r\n * @param {string} name name of the object that this file defines.\r\n * @param {*=} opt_object the object to expose at the end of the path.\r\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\r\n * is `goog.global`.\r\n * @private\r\n */\r\ngoog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {\r\n var parts = name.split('.');\r\n var cur = opt_objectToExportTo || goog.global;\r\n\r\n // Internet Explorer exhibits strange behavior when throwing errors from\r\n // methods externed in this manner. See the testExportSymbolExceptions in\r\n // base_test.html for an example.\r\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\r\n cur.execScript('var ' + parts[0]);\r\n }\r\n\r\n for (var part; parts.length && (part = parts.shift());) {\r\n if (!parts.length && goog.isDef(opt_object)) {\r\n // last part and we have an object; use it\r\n cur[part] = opt_object;\r\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\r\n cur = cur[part];\r\n } else {\r\n cur = cur[part] = {};\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Defines a named value. In uncompiled mode, the value is retrieved from\r\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\r\n * has the property specified, and otherwise used the defined defaultValue.\r\n * When compiled the default can be overridden using the compiler options or the\r\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\r\n * can be used safely in modules. Note that the value type MUST be either\r\n * boolean, number, or string.\r\n *\r\n * @param {string} name The distinguished name to provide.\r\n * @param {T} defaultValue\r\n * @return {T} The defined value.\r\n * @template T\r\n */\r\ngoog.define = function(name, defaultValue) {\r\n var value = defaultValue;\r\n if (!COMPILED) {\r\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\r\n var defines = goog.global.CLOSURE_DEFINES;\r\n if (uncompiledDefines &&\r\n // Anti DOM-clobbering runtime check (b/37736576).\r\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\r\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\r\n value = uncompiledDefines[name];\r\n } else if (\r\n defines &&\r\n // Anti DOM-clobbering runtime check (b/37736576).\r\n /** @type {?} */ (defines).nodeType === undefined &&\r\n Object.prototype.hasOwnProperty.call(defines, name)) {\r\n value = defines[name];\r\n }\r\n }\r\n goog.exportPath_(name, value);\r\n return value;\r\n};\r\n\r\n\r\n/**\r\n * @define {number} Integer year indicating the set of browser features that are\r\n * guaranteed to be present. This is defined to include exactly features that\r\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\r\n * specified year. For example,\r\n * ```js\r\n * if (goog.FEATURESET_YEAR >= 2019) {\r\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\r\n * } else {\r\n * // polyfill for older browsers\r\n * }\r\n * ```\r\n * This is intended to be the primary define for removing\r\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\r\n * and should inform the default value for most other defines:\r\n * ```js\r\n * const ASSUME_NATIVE_PROMISE =\r\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\r\n * ```\r\n *\r\n * The default assumption is that IE9 is the lowest supported browser, which was\r\n * first available Jan 1, 2012.\r\n *\r\n * TODO(user): Reference more thorough documentation when it's available.\r\n */\r\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\r\n\r\n\r\n/**\r\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\r\n * that should not be included in a production. It can be easily stripped\r\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\r\n * JSCompiler. For example, most toString() methods should be declared inside an\r\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\r\n * purposes and it is difficult for the JSCompiler to statically determine\r\n * whether they are used.\r\n */\r\ngoog.DEBUG = goog.define('goog.DEBUG', true);\r\n\r\n\r\n/**\r\n * @define {string} LOCALE defines the locale being used for compilation. It is\r\n * used to select locale specific data to be compiled in js binary. BUILD rule\r\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\r\n * option.\r\n *\r\n * Take into account that the locale code format is important. You should use\r\n * the canonical Unicode format with hyphen as a delimiter. Language must be\r\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\r\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\r\n *\r\n * See more info about locale codes here:\r\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\r\n *\r\n * For language codes you should use values defined by ISO 693-1. See it here\r\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\r\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\r\n * be used instead of the new code (he).\r\n *\r\n */\r\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\r\n\r\n\r\n/**\r\n * @define {boolean} Whether this code is running on trusted sites.\r\n *\r\n * On untrusted sites, several native functions can be defined or overridden by\r\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\r\n * to false forces closure to use its own implementations when possible.\r\n *\r\n * If your JavaScript can be loaded by a third party site and you are wary about\r\n * relying on non-standard implementations, specify\r\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\r\n */\r\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether a project is expected to be running in strict mode.\r\n *\r\n * This define can be used to trigger alternate implementations compatible with\r\n * running in EcmaScript Strict mode or warn about unavailable functionality.\r\n * @see https://goo.gl/PudQ4y\r\n *\r\n */\r\ngoog.STRICT_MODE_COMPATIBLE = goog.define('goog.STRICT_MODE_COMPATIBLE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\r\n * be disallowed in the compilation unit.\r\n */\r\ngoog.DISALLOW_TEST_ONLY_CODE =\r\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\r\n * loading scripts via goog.require. @see appendScriptSrcNode_.\r\n */\r\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\r\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\r\n\r\n\r\n/**\r\n * Defines a namespace in Closure.\r\n *\r\n * A namespace may only be defined once in a codebase. It may be defined using\r\n * goog.provide() or goog.module().\r\n *\r\n * The presence of one or more goog.provide() calls in a file indicates\r\n * that the file defines the given objects/namespaces.\r\n * Provided symbols must not be null or undefined.\r\n *\r\n * In addition, goog.provide() creates the object stubs for a namespace\r\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\r\n * goog.foo.bar if it does not already exist).\r\n *\r\n * Build tools also scan for provide/require/module statements\r\n * to discern dependencies, build dependency files (see deps.js), etc.\r\n *\r\n * @see goog.require\r\n * @see goog.module\r\n * @param {string} name Namespace provided by this file in the form\r\n * \"goog.package.part\".\r\n */\r\ngoog.provide = function(name) {\r\n if (goog.isInModuleLoader_()) {\r\n throw new Error('goog.provide cannot be used within a module.');\r\n }\r\n if (!COMPILED) {\r\n // Ensure that the same namespace isn't provided twice.\r\n // A goog.module/goog.provide maps a goog.require to a specific file\r\n if (goog.isProvided_(name)) {\r\n throw new Error('Namespace \"' + name + '\" already declared.');\r\n }\r\n }\r\n\r\n goog.constructNamespace_(name);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} name Namespace provided by this file in the form\r\n * \"goog.package.part\".\r\n * @param {Object=} opt_obj The object to embed in the namespace.\r\n * @private\r\n */\r\ngoog.constructNamespace_ = function(name, opt_obj) {\r\n if (!COMPILED) {\r\n delete goog.implicitNamespaces_[name];\r\n\r\n var namespace = name;\r\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\r\n if (goog.getObjectByName(namespace)) {\r\n break;\r\n }\r\n goog.implicitNamespaces_[namespace] = true;\r\n }\r\n }\r\n\r\n goog.exportPath_(name, opt_obj);\r\n};\r\n\r\n\r\n/**\r\n * Returns CSP nonce, if set for any script tag.\r\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\r\n * Defaults to global context.\r\n * @return {string} CSP nonce or empty string if no nonce is present.\r\n */\r\ngoog.getScriptNonce = function(opt_window) {\r\n if (opt_window && opt_window != goog.global) {\r\n return goog.getScriptNonce_(opt_window.document);\r\n }\r\n if (goog.cspNonce_ === null) {\r\n goog.cspNonce_ = goog.getScriptNonce_(goog.global.document);\r\n }\r\n return goog.cspNonce_;\r\n};\r\n\r\n\r\n/**\r\n * According to the CSP3 spec a nonce must be a valid base64 string.\r\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\r\n * @private @const\r\n */\r\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\r\n\r\n\r\n/**\r\n * @private {?string}\r\n */\r\ngoog.cspNonce_ = null;\r\n\r\n\r\n/**\r\n * Returns CSP nonce, if set for any script tag.\r\n * @param {!Document} doc\r\n * @return {string} CSP nonce or empty string if no nonce is present.\r\n * @private\r\n */\r\ngoog.getScriptNonce_ = function(doc) {\r\n var script = doc.querySelector && doc.querySelector('script[nonce]');\r\n if (script) {\r\n // Try to get the nonce from the IDL property first, because browsers that\r\n // implement additional nonce protection features (currently only Chrome) to\r\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\r\n // See https://github.com/whatwg/html/issues/2369\r\n var nonce = script['nonce'] || script.getAttribute('nonce');\r\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\r\n return nonce;\r\n }\r\n }\r\n return '';\r\n};\r\n\r\n\r\n/**\r\n * Module identifier validation regexp.\r\n * Note: This is a conservative check, it is very possible to be more lenient,\r\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\r\n * restrictions are intended to leave the door open for using goog.require\r\n * with relative file paths rather than module identifiers.\r\n * @private\r\n */\r\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\r\n\r\n\r\n/**\r\n * Defines a module in Closure.\r\n *\r\n * Marks that this file must be loaded as a module and claims the namespace.\r\n *\r\n * A namespace may only be defined once in a codebase. It may be defined using\r\n * goog.provide() or goog.module().\r\n *\r\n * goog.module() has three requirements:\r\n * - goog.module may not be used in the same file as goog.provide.\r\n * - goog.module must be the first statement in the file.\r\n * - only one goog.module is allowed per file.\r\n *\r\n * When a goog.module annotated file is loaded, it is enclosed in\r\n * a strict function closure. This means that:\r\n * - any variables declared in a goog.module file are private to the file\r\n * (not global), though the compiler is expected to inline the module.\r\n * - The code must obey all the rules of \"strict\" JavaScript.\r\n * - the file will be marked as \"use strict\"\r\n *\r\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\r\n * itself. If declared symbols are desired, use\r\n * goog.module.declareLegacyNamespace().\r\n *\r\n *\r\n * See the public goog.module proposal: http://goo.gl/Va1hin\r\n *\r\n * @param {string} name Namespace provided by this file in the form\r\n * \"goog.package.part\", is expected but not required.\r\n * @return {void}\r\n */\r\ngoog.module = function(name) {\r\n if (!goog.isString(name) || !name ||\r\n name.search(goog.VALID_MODULE_RE_) == -1) {\r\n throw new Error('Invalid module identifier');\r\n }\r\n if (!goog.isInGoogModuleLoader_()) {\r\n throw new Error(\r\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\r\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\r\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\r\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\r\n 'module. For more info see: ' +\r\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\r\n }\r\n if (goog.moduleLoaderState_.moduleName) {\r\n throw new Error('goog.module may only be called once per module.');\r\n }\r\n\r\n // Store the module name for the loader.\r\n goog.moduleLoaderState_.moduleName = name;\r\n if (!COMPILED) {\r\n // Ensure that the same namespace isn't provided twice.\r\n // A goog.module/goog.provide maps a goog.require to a specific file\r\n if (goog.isProvided_(name)) {\r\n throw new Error('Namespace \"' + name + '\" already declared.');\r\n }\r\n delete goog.implicitNamespaces_[name];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {string} name The module identifier.\r\n * @return {?} The module exports for an already loaded module or null.\r\n *\r\n * Note: This is not an alternative to goog.require, it does not\r\n * indicate a hard dependency, instead it is used to indicate\r\n * an optional dependency or to access the exports of a module\r\n * that has already been loaded.\r\n * @suppress {missingProvide}\r\n */\r\ngoog.module.get = function(name) {\r\n\r\n return goog.module.getInternal_(name);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} name The module identifier.\r\n * @return {?} The module exports for an already loaded module or null.\r\n * @private\r\n */\r\ngoog.module.getInternal_ = function(name) {\r\n if (!COMPILED) {\r\n if (name in goog.loadedModules_) {\r\n return goog.loadedModules_[name].exports;\r\n } else if (!goog.implicitNamespaces_[name]) {\r\n var ns = goog.getObjectByName(name);\r\n return ns != null ? ns : null;\r\n }\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Types of modules the debug loader can load.\r\n * @enum {string}\r\n */\r\ngoog.ModuleType = {\r\n ES6: 'es6',\r\n GOOG: 'goog'\r\n};\r\n\r\n\r\n/**\r\n * @private {?{\r\n * moduleName: (string|undefined),\r\n * declareLegacyNamespace:boolean,\r\n * type: ?goog.ModuleType\r\n * }}\r\n */\r\ngoog.moduleLoaderState_ = null;\r\n\r\n\r\n/**\r\n * @private\r\n * @return {boolean} Whether a goog.module or an es6 module is currently being\r\n * initialized.\r\n */\r\ngoog.isInModuleLoader_ = function() {\r\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\r\n};\r\n\r\n\r\n/**\r\n * @private\r\n * @return {boolean} Whether a goog.module is currently being initialized.\r\n */\r\ngoog.isInGoogModuleLoader_ = function() {\r\n return !!goog.moduleLoaderState_ &&\r\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\r\n};\r\n\r\n\r\n/**\r\n * @private\r\n * @return {boolean} Whether an es6 module is currently being initialized.\r\n */\r\ngoog.isInEs6ModuleLoader_ = function() {\r\n var inLoader = !!goog.moduleLoaderState_ &&\r\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\r\n\r\n if (inLoader) {\r\n return true;\r\n }\r\n\r\n var jscomp = goog.global['$jscomp'];\r\n\r\n if (jscomp) {\r\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\r\n // that has some of the runtime, but not all of it. This can happen if\r\n // optimizations are turned on so the unused runtime is removed but renaming\r\n // and Closure pass are off (so $jscomp is still named $jscomp and the\r\n // goog.provide/require calls still exist).\r\n if (typeof jscomp.getCurrentModulePath != 'function') {\r\n return false;\r\n }\r\n\r\n // Bundled ES6 module.\r\n return !!jscomp.getCurrentModulePath();\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Provide the module's exports as a globally accessible object under the\r\n * module's declared name. This is intended to ease migration to goog.module\r\n * for files that have existing usages.\r\n * @suppress {missingProvide}\r\n */\r\ngoog.module.declareLegacyNamespace = function() {\r\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\r\n throw new Error(\r\n 'goog.module.declareLegacyNamespace must be called from ' +\r\n 'within a goog.module');\r\n }\r\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\r\n throw new Error(\r\n 'goog.module must be called prior to ' +\r\n 'goog.module.declareLegacyNamespace.');\r\n }\r\n goog.moduleLoaderState_.declareLegacyNamespace = true;\r\n};\r\n\r\n\r\n/**\r\n * Associates an ES6 module with a Closure module ID so that is available via\r\n * goog.require. The associated ID acts like a goog.module ID - it does not\r\n * create any global names, it is merely available via goog.require /\r\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\r\n * goog.module.get will return the entire module as if it was import *'d. This\r\n * allows Closure files to reference ES6 modules for the sake of migration.\r\n *\r\n * @param {string} namespace\r\n * @suppress {missingProvide}\r\n */\r\ngoog.declareModuleId = function(namespace) {\r\n if (!COMPILED) {\r\n if (!goog.isInEs6ModuleLoader_()) {\r\n throw new Error(\r\n 'goog.declareModuleId may only be called from ' +\r\n 'within an ES6 module');\r\n }\r\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\r\n throw new Error(\r\n 'goog.declareModuleId may only be called once per module.');\r\n }\r\n if (namespace in goog.loadedModules_) {\r\n throw new Error(\r\n 'Module with namespace \"' + namespace + '\" already exists.');\r\n }\r\n }\r\n if (goog.moduleLoaderState_) {\r\n // Not bundled - debug loading.\r\n goog.moduleLoaderState_.moduleName = namespace;\r\n } else {\r\n // Bundled - not debug loading, no module loader state.\r\n var jscomp = goog.global['$jscomp'];\r\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\r\n throw new Error(\r\n 'Module with namespace \"' + namespace +\r\n '\" has been loaded incorrectly.');\r\n }\r\n var exports = jscomp.require(jscomp.getCurrentModulePath());\r\n goog.loadedModules_[namespace] = {\r\n exports: exports,\r\n type: goog.ModuleType.ES6,\r\n moduleId: namespace\r\n };\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Marks that the current file should only be used for testing, and never for\r\n * live code in production.\r\n *\r\n * In the case of unit tests, the message may optionally be an exact namespace\r\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\r\n * provide (if not explicitly defined in the code).\r\n *\r\n * @param {string=} opt_message Optional message to add to the error that's\r\n * raised when used in production code.\r\n */\r\ngoog.setTestOnly = function(opt_message) {\r\n if (goog.DISALLOW_TEST_ONLY_CODE) {\r\n opt_message = opt_message || '';\r\n throw new Error(\r\n 'Importing test-only code into non-debug environment' +\r\n (opt_message ? ': ' + opt_message : '.'));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Forward declares a symbol. This is an indication to the compiler that the\r\n * symbol may be used in the source yet is not required and may not be provided\r\n * in compilation.\r\n *\r\n * The most common usage of forward declaration is code that takes a type as a\r\n * function parameter but does not need to require it. By forward declaring\r\n * instead of requiring, no hard dependency is made, and (if not required\r\n * elsewhere) the namespace may never be required and thus, not be pulled\r\n * into the JavaScript binary. If it is required elsewhere, it will be type\r\n * checked as normal.\r\n *\r\n * Before using goog.forwardDeclare, please read the documentation at\r\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\r\n * understand the options and tradeoffs when working with forward declarations.\r\n *\r\n * @param {string} name The namespace to forward declare in the form of\r\n * \"goog.package.part\".\r\n */\r\ngoog.forwardDeclare = function(name) {};\r\n\r\n\r\n/**\r\n * Forward declare type information. Used to assign types to goog.global\r\n * referenced object that would otherwise result in unknown type references\r\n * and thus block property disambiguation.\r\n */\r\ngoog.forwardDeclare('Document');\r\ngoog.forwardDeclare('HTMLScriptElement');\r\ngoog.forwardDeclare('XMLHttpRequest');\r\n\r\n\r\nif (!COMPILED) {\r\n /**\r\n * Check if the given name has been goog.provided. This will return false for\r\n * names that are available only as implicit namespaces.\r\n * @param {string} name name of the object to look for.\r\n * @return {boolean} Whether the name has been provided.\r\n * @private\r\n */\r\n goog.isProvided_ = function(name) {\r\n return (name in goog.loadedModules_) ||\r\n (!goog.implicitNamespaces_[name] &&\r\n goog.isDefAndNotNull(goog.getObjectByName(name)));\r\n };\r\n\r\n /**\r\n * Namespaces implicitly defined by goog.provide. For example,\r\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\r\n * 'goog.events' must be namespaces.\r\n *\r\n * @type {!Object<string, (boolean|undefined)>}\r\n * @private\r\n */\r\n goog.implicitNamespaces_ = {'goog.module': true};\r\n\r\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\r\n // here and because the existing module package has not been moved yet out of\r\n // the goog.module namespace. This satisifies both the debug loader and\r\n // ahead-of-time dependency management.\r\n}\r\n\r\n\r\n/**\r\n * Returns an object based on its fully qualified external name. The object\r\n * is not found if null or undefined. If you are using a compilation pass that\r\n * renames property names beware that using this function will not find renamed\r\n * properties.\r\n *\r\n * @param {string} name The fully qualified name.\r\n * @param {Object=} opt_obj The object within which to look; default is\r\n * |goog.global|.\r\n * @return {?} The value (object or primitive) or, if not found, null.\r\n */\r\ngoog.getObjectByName = function(name, opt_obj) {\r\n var parts = name.split('.');\r\n var cur = opt_obj || goog.global;\r\n for (var i = 0; i < parts.length; i++) {\r\n cur = cur[parts[i]];\r\n if (!goog.isDefAndNotNull(cur)) {\r\n return null;\r\n }\r\n }\r\n return cur;\r\n};\r\n\r\n\r\n/**\r\n * Globalizes a whole namespace, such as goog or goog.lang.\r\n *\r\n * @param {!Object} obj The namespace to globalize.\r\n * @param {Object=} opt_global The object to add the properties to.\r\n * @deprecated Properties may be explicitly exported to the global scope, but\r\n * this should no longer be done in bulk.\r\n */\r\ngoog.globalize = function(obj, opt_global) {\r\n var global = opt_global || goog.global;\r\n for (var x in obj) {\r\n global[x] = obj[x];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds a dependency from a file to the files it requires.\r\n * @param {string} relPath The path to the js file.\r\n * @param {!Array<string>} provides An array of strings with\r\n * the names of the objects this file provides.\r\n * @param {!Array<string>} requires An array of strings with\r\n * the names of the objects this file requires.\r\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\r\n * how the file must be loaded. The boolean 'true' is equivalent\r\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\r\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\r\n */\r\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\r\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\r\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\r\n }\r\n};\r\n\r\n\r\n\r\n\r\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\r\n// to do \"debug-mode\" development. The dependency system can sometimes be\r\n// confusing, as can the debug DOM loader's asynchronous nature.\r\n//\r\n// With the DOM loader, a call to goog.require() is not blocking -- the script\r\n// will not load until some point after the current script. If a namespace is\r\n// needed at runtime, it needs to be defined in a previous script, or loaded via\r\n// require() with its registered dependencies.\r\n//\r\n// User-defined namespaces may need their own deps file. For a reference on\r\n// creating a deps file, see:\r\n// Externally: https://developers.google.com/closure/library/docs/depswriter\r\n//\r\n// Because of legacy clients, the DOM loader can't be easily removed from\r\n// base.js. Work was done to make it disableable or replaceable for\r\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\r\n// for example). See bootstrap/ for more information.\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to enable the debug loader.\r\n *\r\n * If enabled, a call to goog.require() will attempt to load the namespace by\r\n * appending a script tag to the DOM (if the namespace has been registered).\r\n *\r\n * If disabled, goog.require() will simply assert that the namespace has been\r\n * provided (and depend on the fact that some outside tool correctly ordered\r\n * the script).\r\n */\r\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', true);\r\n\r\n\r\n/**\r\n * @param {string} msg\r\n * @private\r\n */\r\ngoog.logToConsole_ = function(msg) {\r\n if (goog.global.console) {\r\n goog.global.console['error'](msg);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Implements a system for the dynamic resolution of dependencies that works in\r\n * parallel with the BUILD system.\r\n *\r\n * Note that all calls to goog.require will be stripped by the compiler.\r\n *\r\n * @see goog.provide\r\n * @param {string} namespace Namespace (as was given in goog.provide,\r\n * goog.module, or goog.declareModuleId) in the form\r\n * \"goog.package.part\".\r\n * @return {?} If called within a goog.module or ES6 module file, the associated\r\n * namespace or module otherwise null.\r\n */\r\ngoog.require = function(namespace) {\r\n if (!COMPILED) {\r\n // Might need to lazy load on old IE.\r\n if (goog.ENABLE_DEBUG_LOADER) {\r\n goog.debugLoader_.requested(namespace);\r\n }\r\n\r\n // If the object already exists we do not need to do anything.\r\n if (goog.isProvided_(namespace)) {\r\n if (goog.isInModuleLoader_()) {\r\n return goog.module.getInternal_(namespace);\r\n }\r\n } else if (goog.ENABLE_DEBUG_LOADER) {\r\n var moduleLoaderState = goog.moduleLoaderState_;\r\n goog.moduleLoaderState_ = null;\r\n try {\r\n goog.debugLoader_.load_(namespace);\r\n } finally {\r\n goog.moduleLoaderState_ = moduleLoaderState;\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Requires a symbol for its type information. This is an indication to the\r\n * compiler that the symbol may appear in type annotations, yet it is not\r\n * referenced at runtime.\r\n *\r\n * When called within a goog.module or ES6 module file, the return value may be\r\n * assigned to or destructured into a variable, but it may not be otherwise used\r\n * in code outside of a type annotation.\r\n *\r\n * Note that all calls to goog.requireType will be stripped by the compiler.\r\n *\r\n * @param {string} namespace Namespace (as was given in goog.provide,\r\n * goog.module, or goog.declareModuleId) in the form\r\n * \"goog.package.part\".\r\n * @return {?}\r\n */\r\ngoog.requireType = function(namespace) {\r\n // Return an empty object so that single-level destructuring of the return\r\n // value doesn't crash at runtime when using the debug loader. Multi-level\r\n // destructuring isn't supported.\r\n return {};\r\n};\r\n\r\n\r\n/**\r\n * Path for included scripts.\r\n * @type {string}\r\n */\r\ngoog.basePath = '';\r\n\r\n\r\n/**\r\n * A hook for overriding the base path.\r\n * @type {string|undefined}\r\n */\r\ngoog.global.CLOSURE_BASE_PATH;\r\n\r\n\r\n/**\r\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\r\n * deps files will attempt to be loaded.\r\n * @type {boolean|undefined}\r\n */\r\ngoog.global.CLOSURE_NO_DEPS;\r\n\r\n\r\n/**\r\n * A function to import a single script. This is meant to be overridden when\r\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\r\n * in the global scope so that it can be set before base.js is loaded, which\r\n * allows deps.js to be imported properly.\r\n *\r\n * The first parameter the script source, which is a relative URI. The second,\r\n * optional parameter is the script contents, in the event the script needed\r\n * transformation. It should return true if the script was imported, false\r\n * otherwise.\r\n * @type {(function(string, string=): boolean)|undefined}\r\n */\r\ngoog.global.CLOSURE_IMPORT_SCRIPT;\r\n\r\n\r\n/**\r\n * Null function used for default values of callbacks, etc.\r\n * @return {void} Nothing.\r\n */\r\ngoog.nullFunction = function() {};\r\n\r\n\r\n/**\r\n * When defining a class Foo with an abstract method bar(), you can do:\r\n * Foo.prototype.bar = goog.abstractMethod\r\n *\r\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\r\n * when bar() is invoked.\r\n *\r\n * @type {!Function}\r\n * @throws {Error} when invoked to indicate the method should be overridden.\r\n */\r\ngoog.abstractMethod = function() {\r\n throw new Error('unimplemented abstract method');\r\n};\r\n\r\n\r\n/**\r\n * Adds a `getInstance` static method that always returns the same\r\n * instance object.\r\n * @param {!Function} ctor The constructor for the class to add the static\r\n * method to.\r\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\r\n * but we don't have a better type to use here.\r\n */\r\ngoog.addSingletonGetter = function(ctor) {\r\n // instance_ is immediately set to prevent issues with sealed constructors\r\n // such as are encountered when a constructor is returned as the export object\r\n // of a goog.module in unoptimized code.\r\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\r\n /** @type {undefined|!Object} @suppress {underscore} */\r\n ctor.instance_ = undefined;\r\n ctor.getInstance = function() {\r\n if (ctor.instance_) {\r\n return ctor.instance_;\r\n }\r\n if (goog.DEBUG) {\r\n // NOTE: JSCompiler can't optimize away Array#push.\r\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\r\n }\r\n // Cast to avoid conformance violations that ctor.instance_ is unknown\r\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * All singleton classes that have been instantiated, for testing. Don't read\r\n * it directly, use the `goog.testing.singleton` module. The compiler\r\n * removes this variable if unused.\r\n * @type {!Array<!Function>}\r\n * @private\r\n */\r\ngoog.instantiatedSingletons_ = [];\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to load goog.modules using `eval` when using\r\n * the debug loader. This provides a better debugging experience as the\r\n * source is unmodified and can be edited using Chrome Workspaces or similar.\r\n * However in some environments the use of `eval` is banned\r\n * so we provide an alternative.\r\n */\r\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the exports of goog.modules should be sealed when\r\n * possible.\r\n */\r\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\r\n\r\n\r\n/**\r\n * The registry of initialized modules:\r\n * The module identifier or path to module exports map.\r\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\r\n */\r\ngoog.loadedModules_ = {};\r\n\r\n\r\n/**\r\n * True if the debug loader enabled and used.\r\n * @const {boolean}\r\n */\r\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\r\n\r\n\r\n/**\r\n * @define {string} How to decide whether to transpile. Valid values\r\n * are 'always', 'never', and 'detect'. The default ('detect') is to\r\n * use feature detection to determine which language levels need\r\n * transpilation.\r\n */\r\n// NOTE(sdh): we could expand this to accept a language level to bypass\r\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\r\n// would leave ES3 and ES5 files alone.\r\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\r\n\r\n/**\r\n * @define {boolean} If true assume that ES modules have already been\r\n * transpiled by the jscompiler (in the same way that transpile.js would\r\n * transpile them - to jscomp modules). Useful only for servers that wish to use\r\n * the debug loader and transpile server side. Thus this is only respected if\r\n * goog.TRANSPILE is \"never\".\r\n */\r\ngoog.ASSUME_ES_MODULES_TRANSPILED =\r\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\r\n\r\n\r\n/**\r\n * @define {string} If a file needs to be transpiled what the output language\r\n * should be. By default this is the highest language level this file detects\r\n * the current environment supports. Generally this flag should not be set, but\r\n * it could be useful to override. Example: If the current environment supports\r\n * ES6 then by default ES7+ files will be transpiled to ES6, unless this is\r\n * overridden.\r\n *\r\n * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized\r\n * is treated as es3.\r\n *\r\n * Note that setting this value does not force transpilation. Just if\r\n * transpilation occurs this will be the output. So this is most useful when\r\n * goog.TRANSPILE is set to 'always' and then forcing the language level to be\r\n * something lower than what the environment detects.\r\n */\r\ngoog.TRANSPILE_TO_LANGUAGE = goog.define('goog.TRANSPILE_TO_LANGUAGE', '');\r\n\r\n\r\n/**\r\n * @define {string} Path to the transpiler. Executing the script at this\r\n * path (relative to base.js) should define a function $jscomp.transpile.\r\n */\r\ngoog.TRANSPILER = goog.define('goog.TRANSPILER', 'transpile.js');\r\n\r\n\r\n/**\r\n * @package {?boolean}\r\n * Visible for testing.\r\n */\r\ngoog.hasBadLetScoping = null;\r\n\r\n\r\n/**\r\n * @return {boolean}\r\n * @package Visible for testing.\r\n */\r\ngoog.useSafari10Workaround = function() {\r\n if (goog.hasBadLetScoping == null) {\r\n var hasBadLetScoping;\r\n try {\r\n hasBadLetScoping = !eval(\r\n '\"use strict\";' +\r\n 'let x = 1; function f() { return typeof x; };' +\r\n 'f() == \"number\";');\r\n } catch (e) {\r\n // Assume that ES6 syntax isn't supported.\r\n hasBadLetScoping = false;\r\n }\r\n goog.hasBadLetScoping = hasBadLetScoping;\r\n }\r\n return goog.hasBadLetScoping;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} moduleDef\r\n * @return {string}\r\n * @package Visible for testing.\r\n */\r\ngoog.workaroundSafari10EvalBug = function(moduleDef) {\r\n return '(function(){' + moduleDef +\r\n '\\n' + // Terminate any trailing single line comment.\r\n ';' + // Terminate any trailing expression.\r\n '})();\\n';\r\n};\r\n\r\n\r\n/**\r\n * @param {function(?):?|string} moduleDef The module definition.\r\n */\r\ngoog.loadModule = function(moduleDef) {\r\n // NOTE: we allow function definitions to be either in the from\r\n // of a string to eval (which keeps the original source intact) or\r\n // in a eval forbidden environment (CSP) we allow a function definition\r\n // which in its body must call `goog.module`, and return the exports\r\n // of the module.\r\n var previousState = goog.moduleLoaderState_;\r\n try {\r\n goog.moduleLoaderState_ = {\r\n moduleName: '',\r\n declareLegacyNamespace: false,\r\n type: goog.ModuleType.GOOG\r\n };\r\n var exports;\r\n if (goog.isFunction(moduleDef)) {\r\n exports = moduleDef.call(undefined, {});\r\n } else if (goog.isString(moduleDef)) {\r\n if (goog.useSafari10Workaround()) {\r\n moduleDef = goog.workaroundSafari10EvalBug(moduleDef);\r\n }\r\n\r\n exports = goog.loadModuleFromSource_.call(undefined, moduleDef);\r\n } else {\r\n throw new Error('Invalid module definition');\r\n }\r\n\r\n var moduleName = goog.moduleLoaderState_.moduleName;\r\n if (goog.isString(moduleName) && moduleName) {\r\n // Don't seal legacy namespaces as they may be used as a parent of\r\n // another namespace\r\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\r\n goog.constructNamespace_(moduleName, exports);\r\n } else if (\r\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\r\n typeof exports == 'object' && exports != null) {\r\n Object.seal(exports);\r\n }\r\n\r\n var data = {\r\n exports: exports,\r\n type: goog.ModuleType.GOOG,\r\n moduleId: goog.moduleLoaderState_.moduleName\r\n };\r\n goog.loadedModules_[moduleName] = data;\r\n } else {\r\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\r\n }\r\n } finally {\r\n goog.moduleLoaderState_ = previousState;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @private @const\r\n */\r\ngoog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() {\r\n // NOTE: we avoid declaring parameters or local variables here to avoid\r\n // masking globals or leaking values into the module definition.\r\n 'use strict';\r\n var exports = {};\r\n eval(arguments[0]);\r\n return exports;\r\n});\r\n\r\n\r\n/**\r\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\r\n * path components.\r\n * @param {string} path\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.normalizePath_ = function(path) {\r\n var components = path.split('/');\r\n var i = 0;\r\n while (i < components.length) {\r\n if (components[i] == '.') {\r\n components.splice(i, 1);\r\n } else if (\r\n i && components[i] == '..' && components[i - 1] &&\r\n components[i - 1] != '..') {\r\n components.splice(--i, 2);\r\n } else {\r\n i++;\r\n }\r\n }\r\n return components.join('/');\r\n};\r\n\r\n\r\n/**\r\n * Provides a hook for loading a file when using Closure's goog.require() API\r\n * with goog.modules. In particular this hook is provided to support Node.js.\r\n *\r\n * @type {(function(string):string)|undefined}\r\n */\r\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\r\n\r\n\r\n/**\r\n * Loads file by synchronous XHR. Should not be used in production environments.\r\n * @param {string} src Source URL.\r\n * @return {?string} File contents, or null if load failed.\r\n * @private\r\n */\r\ngoog.loadFileSync_ = function(src) {\r\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\r\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\r\n } else {\r\n try {\r\n /** @type {XMLHttpRequest} */\r\n var xhr = new goog.global['XMLHttpRequest']();\r\n xhr.open('get', src, false);\r\n xhr.send();\r\n // NOTE: Successful http: requests have a status of 200, but successful\r\n // file: requests may have a status of zero. Any other status, or a\r\n // thrown exception (particularly in case of file: requests) indicates\r\n // some sort of error, which we treat as a missing or unavailable file.\r\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\r\n } catch (err) {\r\n // No need to rethrow or log, since errors should show up on their own.\r\n return null;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Lazily retrieves the transpiler and applies it to the source.\r\n * @param {string} code JS code.\r\n * @param {string} path Path to the code.\r\n * @param {string} target Language level output.\r\n * @return {string} The transpiled code.\r\n * @private\r\n */\r\ngoog.transpile_ = function(code, path, target) {\r\n var jscomp = goog.global['$jscomp'];\r\n if (!jscomp) {\r\n goog.global['$jscomp'] = jscomp = {};\r\n }\r\n var transpile = jscomp.transpile;\r\n if (!transpile) {\r\n var transpilerPath = goog.basePath + goog.TRANSPILER;\r\n var transpilerCode = goog.loadFileSync_(transpilerPath);\r\n if (transpilerCode) {\r\n // This must be executed synchronously, since by the time we know we\r\n // need it, we're about to load and write the ES6 code synchronously,\r\n // so a normal script-tag load will be too slow. Wrapped in a function\r\n // so that code is eval'd in the global scope.\r\n (function() {\r\n eval(transpilerCode + '\\n//# sourceURL=' + transpilerPath);\r\n }).call(goog.global);\r\n // Even though the transpiler is optional, if $gwtExport is found, it's\r\n // a sign the transpiler was loaded and the $jscomp.transpile *should*\r\n // be there.\r\n if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&\r\n !goog.global['$gwtExport']['$jscomp']['transpile']) {\r\n throw new Error(\r\n 'The transpiler did not properly export the \"transpile\" ' +\r\n 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));\r\n }\r\n // transpile.js only exports a single $jscomp function, transpile. We\r\n // grab just that and add it to the existing definition of $jscomp which\r\n // contains the polyfills.\r\n goog.global['$jscomp'].transpile =\r\n goog.global['$gwtExport']['$jscomp']['transpile'];\r\n jscomp = goog.global['$jscomp'];\r\n transpile = jscomp.transpile;\r\n }\r\n }\r\n if (!transpile) {\r\n // The transpiler is an optional component. If it's not available then\r\n // replace it with a pass-through function that simply logs.\r\n var suffix = ' requires transpilation but no transpiler was found.';\r\n transpile = jscomp.transpile = function(code, path) {\r\n // TODO(sdh): figure out some way to get this error to show up\r\n // in test results, noting that the failure may occur in many\r\n // different ways, including in loadModule() before the test\r\n // runner even comes up.\r\n goog.logToConsole_(path + suffix);\r\n return code;\r\n };\r\n }\r\n // Note: any transpilation errors/warnings will be logged to the console.\r\n return transpile(code, path, target);\r\n};\r\n\r\n//==============================================================================\r\n// Language Enhancements\r\n//==============================================================================\r\n\r\n\r\n/**\r\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\r\n * operator in such a way that null returns 'null' and arrays return 'array'.\r\n * @param {?} value The value to get the type of.\r\n * @return {string} The name of the type.\r\n */\r\ngoog.typeOf = function(value) {\r\n var s = typeof value;\r\n if (s == 'object') {\r\n if (value) {\r\n // Check these first, so we can avoid calling Object.prototype.toString if\r\n // possible.\r\n //\r\n // IE improperly marshals typeof across execution contexts, but a\r\n // cross-context object will still return false for \"instanceof Object\".\r\n if (value instanceof Array) {\r\n return 'array';\r\n } else if (value instanceof Object) {\r\n return s;\r\n }\r\n\r\n // HACK: In order to use an Object prototype method on the arbitrary\r\n // value, the compiler requires the value be cast to type Object,\r\n // even though the ECMA spec explicitly allows it.\r\n var className = Object.prototype.toString.call(\r\n /** @type {!Object} */ (value));\r\n // In Firefox 3.6, attempting to access iframe window objects' length\r\n // property throws an NS_ERROR_FAILURE, so we need to special-case it\r\n // here.\r\n if (className == '[object Window]') {\r\n return 'object';\r\n }\r\n\r\n // We cannot always use constructor == Array or instanceof Array because\r\n // different frames have different Array objects. In IE6, if the iframe\r\n // where the array was created is destroyed, the array loses its\r\n // prototype. Then dereferencing val.splice here throws an exception, so\r\n // we can't use goog.isFunction. Calling typeof directly returns 'unknown'\r\n // so that will work. In this case, this function will return false and\r\n // most array functions will still work because the array is still\r\n // array-like (supports length and []) even though it has lost its\r\n // prototype.\r\n // Mark Miller noticed that Object.prototype.toString\r\n // allows access to the unforgeable [[Class]] property.\r\n // 15.2.4.2 Object.prototype.toString ( )\r\n // When the toString method is called, the following steps are taken:\r\n // 1. Get the [[Class]] property of this object.\r\n // 2. Compute a string value by concatenating the three strings\r\n // \"[object \", Result(1), and \"]\".\r\n // 3. Return Result(2).\r\n // and this behavior survives the destruction of the execution context.\r\n if ((className == '[object Array]' ||\r\n // In IE all non value types are wrapped as objects across window\r\n // boundaries (not iframe though) so we have to do object detection\r\n // for this edge case.\r\n typeof value.length == 'number' &&\r\n typeof value.splice != 'undefined' &&\r\n typeof value.propertyIsEnumerable != 'undefined' &&\r\n !value.propertyIsEnumerable('splice')\r\n\r\n )) {\r\n return 'array';\r\n }\r\n // HACK: There is still an array case that fails.\r\n // function ArrayImpostor() {}\r\n // ArrayImpostor.prototype = [];\r\n // var impostor = new ArrayImpostor;\r\n // this can be fixed by getting rid of the fast path\r\n // (value instanceof Array) and solely relying on\r\n // (value && Object.prototype.toString.vall(value) === '[object Array]')\r\n // but that would require many more function calls and is not warranted\r\n // unless closure code is receiving objects from untrusted sources.\r\n\r\n // IE in cross-window calls does not correctly marshal the function type\r\n // (it appears just as an object) so we cannot use just typeof val ==\r\n // 'function'. However, if the object has a call property, it is a\r\n // function.\r\n if ((className == '[object Function]' ||\r\n typeof value.call != 'undefined' &&\r\n typeof value.propertyIsEnumerable != 'undefined' &&\r\n !value.propertyIsEnumerable('call'))) {\r\n return 'function';\r\n }\r\n\r\n } else {\r\n return 'null';\r\n }\r\n\r\n } else if (s == 'function' && typeof value.call == 'undefined') {\r\n // In Safari typeof nodeList returns 'function', and on Firefox typeof\r\n // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We\r\n // would like to return object for those and we can detect an invalid\r\n // function by making sure that the function object has a call method.\r\n return 'object';\r\n }\r\n return s;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is null.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is null.\r\n */\r\ngoog.isNull = function(val) {\r\n return val === null;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is defined and not null.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is defined and not null.\r\n */\r\ngoog.isDefAndNotNull = function(val) {\r\n // Note that undefined == null.\r\n return val != null;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is an array.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is an array.\r\n */\r\ngoog.isArray = function(val) {\r\n return goog.typeOf(val) == 'array';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the object looks like an array. To qualify as array like\r\n * the value needs to be either a NodeList or an object with a Number length\r\n * property. Note that for this function neither strings nor functions are\r\n * considered \"array-like\".\r\n *\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is an array.\r\n */\r\ngoog.isArrayLike = function(val) {\r\n var type = goog.typeOf(val);\r\n // We do not use goog.isObject here in order to exclude function values.\r\n return type == 'array' || type == 'object' && typeof val.length == 'number';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the object looks like a Date. To qualify as Date-like the\r\n * value needs to be an object and have a getFullYear() function.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a like a Date.\r\n */\r\ngoog.isDateLike = function(val) {\r\n return goog.isObject(val) && typeof val.getFullYear == 'function';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is a function.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a function.\r\n */\r\ngoog.isFunction = function(val) {\r\n return goog.typeOf(val) == 'function';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is an object. This includes arrays and\r\n * functions.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is an object.\r\n */\r\ngoog.isObject = function(val) {\r\n var type = typeof val;\r\n return type == 'object' && val != null || type == 'function';\r\n // return Object(val) === val also works, but is slower, especially if val is\r\n // not an object.\r\n};\r\n\r\n\r\n/**\r\n * Gets a unique ID for an object. This mutates the object so that further calls\r\n * with the same object as a parameter returns the same value. The unique ID is\r\n * guaranteed to be unique across the current session amongst objects that are\r\n * passed into `getUid`. There is no guarantee that the ID is unique or\r\n * consistent across sessions. It is unsafe to generate unique ID for function\r\n * prototypes.\r\n *\r\n * @param {Object} obj The object to get the unique ID for.\r\n * @return {number} The unique ID for the object.\r\n */\r\ngoog.getUid = function(obj) {\r\n // TODO(arv): Make the type stricter, do not accept null.\r\n\r\n // In Opera window.hasOwnProperty exists but always returns false so we avoid\r\n // using it. As a consequence the unique ID generated for BaseClass.prototype\r\n // and SubClass.prototype will be the same.\r\n return obj[goog.UID_PROPERTY_] ||\r\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\r\n};\r\n\r\n\r\n/**\r\n * Whether the given object is already assigned a unique ID.\r\n *\r\n * This does not modify the object.\r\n *\r\n * @param {!Object} obj The object to check.\r\n * @return {boolean} Whether there is an assigned unique id for the object.\r\n */\r\ngoog.hasUid = function(obj) {\r\n return !!obj[goog.UID_PROPERTY_];\r\n};\r\n\r\n\r\n/**\r\n * Removes the unique ID from an object. This is useful if the object was\r\n * previously mutated using `goog.getUid` in which case the mutation is\r\n * undone.\r\n * @param {Object} obj The object to remove the unique ID field from.\r\n */\r\ngoog.removeUid = function(obj) {\r\n // TODO(arv): Make the type stricter, do not accept null.\r\n\r\n // In IE, DOM nodes are not instances of Object and throw an exception if we\r\n // try to delete. Instead we try to use removeAttribute.\r\n if (obj !== null && 'removeAttribute' in obj) {\r\n obj.removeAttribute(goog.UID_PROPERTY_);\r\n }\r\n\r\n try {\r\n delete obj[goog.UID_PROPERTY_];\r\n } catch (ex) {\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Name for unique ID property. Initialized in a way to help avoid collisions\r\n * with other closure JavaScript on the same page.\r\n * @type {string}\r\n * @private\r\n */\r\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\r\n\r\n\r\n/**\r\n * Counter for UID.\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.uidCounter_ = 0;\r\n\r\n\r\n/**\r\n * Adds a hash code field to an object. The hash code is unique for the\r\n * given object.\r\n * @param {Object} obj The object to get the hash code for.\r\n * @return {number} The hash code for the object.\r\n * @deprecated Use goog.getUid instead.\r\n */\r\ngoog.getHashCode = goog.getUid;\r\n\r\n\r\n/**\r\n * Removes the hash code field from an object.\r\n * @param {Object} obj The object to remove the field from.\r\n * @deprecated Use goog.removeUid instead.\r\n */\r\ngoog.removeHashCode = goog.removeUid;\r\n\r\n\r\n/**\r\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\r\n * arrays will be cloned recursively.\r\n *\r\n * WARNINGS:\r\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\r\n * refer to themselves will cause infinite recursion.\r\n *\r\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\r\n * UIDs created by <code>getUid</code> into cloned results.\r\n *\r\n * @param {*} obj The value to clone.\r\n * @return {*} A clone of the input value.\r\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\r\n */\r\ngoog.cloneObject = function(obj) {\r\n var type = goog.typeOf(obj);\r\n if (type == 'object' || type == 'array') {\r\n if (typeof obj.clone === 'function') {\r\n return obj.clone();\r\n }\r\n var clone = type == 'array' ? [] : {};\r\n for (var key in obj) {\r\n clone[key] = goog.cloneObject(obj[key]);\r\n }\r\n return clone;\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * A native implementation of goog.bind.\r\n * @param {?function(this:T, ...)} fn A function to partially apply.\r\n * @param {T} selfObj Specifies the object which this should point to when the\r\n * function is run.\r\n * @param {...*} var_args Additional arguments that are partially applied to the\r\n * function.\r\n * @return {!Function} A partially-applied form of the function goog.bind() was\r\n * invoked as a method of.\r\n * @template T\r\n * @private\r\n */\r\ngoog.bindNative_ = function(fn, selfObj, var_args) {\r\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\r\n};\r\n\r\n\r\n/**\r\n * A pure-JS implementation of goog.bind.\r\n * @param {?function(this:T, ...)} fn A function to partially apply.\r\n * @param {T} selfObj Specifies the object which this should point to when the\r\n * function is run.\r\n * @param {...*} var_args Additional arguments that are partially applied to the\r\n * function.\r\n * @return {!Function} A partially-applied form of the function goog.bind() was\r\n * invoked as a method of.\r\n * @template T\r\n * @private\r\n */\r\ngoog.bindJs_ = function(fn, selfObj, var_args) {\r\n if (!fn) {\r\n throw new Error();\r\n }\r\n\r\n if (arguments.length > 2) {\r\n var boundArgs = Array.prototype.slice.call(arguments, 2);\r\n return function() {\r\n // Prepend the bound arguments to the current arguments.\r\n var newArgs = Array.prototype.slice.call(arguments);\r\n Array.prototype.unshift.apply(newArgs, boundArgs);\r\n return fn.apply(selfObj, newArgs);\r\n };\r\n\r\n } else {\r\n return function() {\r\n return fn.apply(selfObj, arguments);\r\n };\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Partially applies this function to a particular 'this object' and zero or\r\n * more arguments. The result is a new function with some arguments of the first\r\n * function pre-filled and the value of this 'pre-specified'.\r\n *\r\n * Remaining arguments specified at call-time are appended to the pre-specified\r\n * ones.\r\n *\r\n * Also see: {@link #partial}.\r\n *\r\n * Usage:\r\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\r\n * barMethBound('arg3', 'arg4');</pre>\r\n *\r\n * @param {?function(this:T, ...)} fn A function to partially apply.\r\n * @param {T} selfObj Specifies the object which this should point to when the\r\n * function is run.\r\n * @param {...*} var_args Additional arguments that are partially applied to the\r\n * function.\r\n * @return {!Function} A partially-applied form of the function goog.bind() was\r\n * invoked as a method of.\r\n * @template T\r\n * @suppress {deprecated} See above.\r\n */\r\ngoog.bind = function(fn, selfObj, var_args) {\r\n // TODO(nicksantos): narrow the type signature.\r\n if (Function.prototype.bind &&\r\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\r\n // extension environment. This means that for Chrome extensions, they get\r\n // the implementation of Function.prototype.bind that calls goog.bind\r\n // instead of the native one. Even worse, we don't want to introduce a\r\n // circular dependency between goog.bind and Function.prototype.bind, so\r\n // we have to hack this to make sure it works correctly.\r\n Function.prototype.bind.toString().indexOf('native code') != -1) {\r\n goog.bind = goog.bindNative_;\r\n } else {\r\n goog.bind = goog.bindJs_;\r\n }\r\n return goog.bind.apply(null, arguments);\r\n};\r\n\r\n\r\n/**\r\n * Like goog.bind(), except that a 'this object' is not required. Useful when\r\n * the target function is already bound.\r\n *\r\n * Usage:\r\n * var g = goog.partial(f, arg1, arg2);\r\n * g(arg3, arg4);\r\n *\r\n * @param {Function} fn A function to partially apply.\r\n * @param {...*} var_args Additional arguments that are partially applied to fn.\r\n * @return {!Function} A partially-applied form of the function goog.partial()\r\n * was invoked as a method of.\r\n */\r\ngoog.partial = function(fn, var_args) {\r\n var args = Array.prototype.slice.call(arguments, 1);\r\n return function() {\r\n // Clone the array (with slice()) and append additional arguments\r\n // to the existing arguments.\r\n var newArgs = args.slice();\r\n newArgs.push.apply(newArgs, arguments);\r\n return fn.apply(/** @type {?} */ (this), newArgs);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Copies all the members of a source object to a target object. This method\r\n * does not work on all browsers for all objects that contain keys such as\r\n * toString or hasOwnProperty. Use goog.object.extend for this purpose.\r\n * @param {Object} target Target.\r\n * @param {Object} source Source.\r\n */\r\ngoog.mixin = function(target, source) {\r\n for (var x in source) {\r\n target[x] = source[x];\r\n }\r\n\r\n // For IE7 or lower, the for-in-loop does not contain any properties that are\r\n // not enumerable on the prototype object (for example, isPrototypeOf from\r\n // Object.prototype) but also it will not include 'replace' on objects that\r\n // extend String and change 'replace' (not that it is common for anyone to\r\n // extend anything except Object).\r\n};\r\n\r\n\r\n/**\r\n * @return {number} An integer value representing the number of milliseconds\r\n * between midnight, January 1, 1970 and the current time.\r\n */\r\ngoog.now = (goog.TRUSTED_SITE && Date.now) || (function() {\r\n // Unary plus operator converts its operand to a number which in\r\n // the case of\r\n // a date is done by calling getTime().\r\n return +new Date();\r\n });\r\n\r\n\r\n/**\r\n * Evals JavaScript in the global scope. In IE this uses execScript, other\r\n * browsers use goog.global.eval. If goog.global.eval does not evaluate in the\r\n * global scope (for example, in Safari), appends a script tag instead.\r\n * Throws an exception if neither execScript or eval is defined.\r\n * @param {string} script JavaScript string.\r\n */\r\ngoog.globalEval = function(script) {\r\n if (goog.global.execScript) {\r\n goog.global.execScript(script, 'JavaScript');\r\n } else if (goog.global.eval) {\r\n // Test to see if eval works\r\n if (goog.evalWorksForGlobals_ == null) {\r\n try {\r\n goog.global.eval('var _evalTest_ = 1;');\r\n } catch (ignore) {\r\n }\r\n if (typeof goog.global['_evalTest_'] != 'undefined') {\r\n try {\r\n delete goog.global['_evalTest_'];\r\n } catch (ignore) {\r\n // Microsoft edge fails the deletion above in strict mode.\r\n }\r\n goog.evalWorksForGlobals_ = true;\r\n } else {\r\n goog.evalWorksForGlobals_ = false;\r\n }\r\n }\r\n\r\n if (goog.evalWorksForGlobals_) {\r\n goog.global.eval(script);\r\n } else {\r\n /** @type {!Document} */\r\n var doc = goog.global.document;\r\n var scriptElt =\r\n /** @type {!HTMLScriptElement} */ (doc.createElement('SCRIPT'));\r\n scriptElt.type = 'text/javascript';\r\n scriptElt.defer = false;\r\n // Note(user): can't use .innerHTML since \"t('<test>')\" will fail and\r\n // .text doesn't work in Safari 2. Therefore we append a text node.\r\n scriptElt.appendChild(doc.createTextNode(script));\r\n doc.head.appendChild(scriptElt);\r\n doc.head.removeChild(scriptElt);\r\n }\r\n } else {\r\n throw new Error('goog.globalEval not available');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Indicates whether or not we can call 'eval' directly to eval code in the\r\n * global scope. Set to a Boolean by the first call to goog.globalEval (which\r\n * empirically tests whether eval works for globals). @see goog.globalEval\r\n * @type {?boolean}\r\n * @private\r\n */\r\ngoog.evalWorksForGlobals_ = null;\r\n\r\n\r\n/**\r\n * Optional map of CSS class names to obfuscated names used with\r\n * goog.getCssName().\r\n * @private {!Object<string, string>|undefined}\r\n * @see goog.setCssNameMapping\r\n */\r\ngoog.cssNameMapping_;\r\n\r\n\r\n/**\r\n * Optional obfuscation style for CSS class names. Should be set to either\r\n * 'BY_WHOLE' or 'BY_PART' if defined.\r\n * @type {string|undefined}\r\n * @private\r\n * @see goog.setCssNameMapping\r\n */\r\ngoog.cssNameMappingStyle_;\r\n\r\n\r\n\r\n/**\r\n * A hook for modifying the default behavior goog.getCssName. The function\r\n * if present, will receive the standard output of the goog.getCssName as\r\n * its input.\r\n *\r\n * @type {(function(string):string)|undefined}\r\n */\r\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\r\n\r\n\r\n/**\r\n * Handles strings that are intended to be used as CSS class names.\r\n *\r\n * This function works in tandem with @see goog.setCssNameMapping.\r\n *\r\n * Without any mapping set, the arguments are simple joined with a hyphen and\r\n * passed through unaltered.\r\n *\r\n * When there is a mapping, there are two possible styles in which these\r\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\r\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\r\n * style, the full css name is looked up in the map directly. If a rewrite is\r\n * not specified by the map, the compiler will output a warning.\r\n *\r\n * When the mapping is passed to the compiler, it will replace calls to\r\n * goog.getCssName with the strings from the mapping, e.g.\r\n * var x = goog.getCssName('foo');\r\n * var y = goog.getCssName(this.baseClass, 'active');\r\n * becomes:\r\n * var x = 'foo';\r\n * var y = this.baseClass + '-active';\r\n *\r\n * If one argument is passed it will be processed, if two are passed only the\r\n * modifier will be processed, as it is assumed the first argument was generated\r\n * as a result of calling goog.getCssName.\r\n *\r\n * @param {string} className The class name.\r\n * @param {string=} opt_modifier A modifier to be appended to the class name.\r\n * @return {string} The class name or the concatenation of the class name and\r\n * the modifier.\r\n */\r\ngoog.getCssName = function(className, opt_modifier) {\r\n // String() is used for compatibility with compiled soy where the passed\r\n // className can be non-string objects.\r\n if (String(className).charAt(0) == '.') {\r\n throw new Error(\r\n 'className passed in goog.getCssName must not start with \".\".' +\r\n ' You passed: ' + className);\r\n }\r\n\r\n var getMapping = function(cssName) {\r\n return goog.cssNameMapping_[cssName] || cssName;\r\n };\r\n\r\n var renameByParts = function(cssName) {\r\n // Remap all the parts individually.\r\n var parts = cssName.split('-');\r\n var mapped = [];\r\n for (var i = 0; i < parts.length; i++) {\r\n mapped.push(getMapping(parts[i]));\r\n }\r\n return mapped.join('-');\r\n };\r\n\r\n var rename;\r\n if (goog.cssNameMapping_) {\r\n rename =\r\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\r\n } else {\r\n rename = function(a) {\r\n return a;\r\n };\r\n }\r\n\r\n var result =\r\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\r\n\r\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\r\n // processing of the class name.\r\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\r\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\r\n }\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Sets the map to check when returning a value from goog.getCssName(). Example:\r\n * <pre>\r\n * goog.setCssNameMapping({\r\n * \"goog\": \"a\",\r\n * \"disabled\": \"b\",\r\n * });\r\n *\r\n * var x = goog.getCssName('goog');\r\n * // The following evaluates to: \"a a-b\".\r\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\r\n * </pre>\r\n * When declared as a map of string literals to string literals, the JSCompiler\r\n * will replace all calls to goog.getCssName() using the supplied map if the\r\n * --process_closure_primitives flag is set.\r\n *\r\n * @param {!Object} mapping A map of strings to strings where keys are possible\r\n * arguments to goog.getCssName() and values are the corresponding values\r\n * that should be returned.\r\n * @param {string=} opt_style The style of css name mapping. There are two valid\r\n * options: 'BY_PART', and 'BY_WHOLE'.\r\n * @see goog.getCssName for a description.\r\n */\r\ngoog.setCssNameMapping = function(mapping, opt_style) {\r\n goog.cssNameMapping_ = mapping;\r\n goog.cssNameMappingStyle_ = opt_style;\r\n};\r\n\r\n\r\n/**\r\n * To use CSS renaming in compiled mode, one of the input files should have a\r\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\r\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\r\n * mode, JavaScript code should be loaded before this base.js file that declares\r\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\r\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\r\n * are made in uncompiled mode.\r\n *\r\n * A hook for overriding the CSS name mapping.\r\n * @type {!Object<string, string>|undefined}\r\n */\r\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\r\n\r\n\r\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\r\n // This does not call goog.setCssNameMapping() because the JSCompiler\r\n // requires that goog.setCssNameMapping() be called with an object literal.\r\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\r\n}\r\n\r\n\r\n/**\r\n * Gets a localized message.\r\n *\r\n * This function is a compiler primitive. If you give the compiler a localized\r\n * message bundle, it will replace the string at compile-time with a localized\r\n * version, and expand goog.getMsg call to a concatenated string.\r\n *\r\n * Messages must be initialized in the form:\r\n * <code>\r\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\r\n * </code>\r\n *\r\n * This function produces a string which should be treated as plain text. Use\r\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\r\n * produce SafeHtml.\r\n *\r\n * @param {string} str Translatable string, places holders in the form {$foo}.\r\n * @param {Object<string, string>=} opt_values Maps place holder name to value.\r\n * @return {string} message with placeholders filled.\r\n */\r\ngoog.getMsg = function(str, opt_values) {\r\n if (opt_values) {\r\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\r\n return (opt_values != null && key in opt_values) ? opt_values[key] :\r\n match;\r\n });\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Gets a localized message. If the message does not have a translation, gives a\r\n * fallback message.\r\n *\r\n * This is useful when introducing a new message that has not yet been\r\n * translated into all languages.\r\n *\r\n * This function is a compiler primitive. Must be used in the form:\r\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\r\n * where MSG_A and MSG_B were initialized with goog.getMsg.\r\n *\r\n * @param {string} a The preferred message.\r\n * @param {string} b The fallback message.\r\n * @return {string} The best translated message.\r\n */\r\ngoog.getMsgWithFallback = function(a, b) {\r\n return a;\r\n};\r\n\r\n\r\n/**\r\n * Exposes an unobfuscated global namespace path for the given object.\r\n * Note that fields of the exported object *will* be obfuscated, unless they are\r\n * exported in turn via this function or goog.exportProperty.\r\n *\r\n * Also handy for making public items that are defined in anonymous closures.\r\n *\r\n * ex. goog.exportSymbol('public.path.Foo', Foo);\r\n *\r\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\r\n * public.path.Foo.staticFunction();\r\n *\r\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\r\n * Foo.prototype.myMethod);\r\n * new public.path.Foo().myMethod();\r\n *\r\n * @param {string} publicPath Unobfuscated name to export.\r\n * @param {*} object Object the name should point to.\r\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\r\n * is goog.global.\r\n */\r\ngoog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {\r\n goog.exportPath_(publicPath, object, opt_objectToExportTo);\r\n};\r\n\r\n\r\n/**\r\n * Exports a property unobfuscated into the object's namespace.\r\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\r\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\r\n * @param {Object} object Object whose static property is being exported.\r\n * @param {string} publicName Unobfuscated name to export.\r\n * @param {*} symbol Object the name should point to.\r\n */\r\ngoog.exportProperty = function(object, publicName, symbol) {\r\n object[publicName] = symbol;\r\n};\r\n\r\n\r\n/**\r\n * Inherit the prototype methods from one constructor into another.\r\n *\r\n * Usage:\r\n * <pre>\r\n * function ParentClass(a, b) { }\r\n * ParentClass.prototype.foo = function(a) { };\r\n *\r\n * function ChildClass(a, b, c) {\r\n * ChildClass.base(this, 'constructor', a, b);\r\n * }\r\n * goog.inherits(ChildClass, ParentClass);\r\n *\r\n * var child = new ChildClass('a', 'b', 'see');\r\n * child.foo(); // This works.\r\n * </pre>\r\n *\r\n * @param {!Function} childCtor Child class.\r\n * @param {!Function} parentCtor Parent class.\r\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\r\n * Function.\r\n */\r\ngoog.inherits = function(childCtor, parentCtor) {\r\n /** @constructor */\r\n function tempCtor() {}\r\n tempCtor.prototype = parentCtor.prototype;\r\n childCtor.superClass_ = parentCtor.prototype;\r\n childCtor.prototype = new tempCtor();\r\n /** @override */\r\n childCtor.prototype.constructor = childCtor;\r\n\r\n /**\r\n * Calls superclass constructor/method.\r\n *\r\n * This function is only available if you use goog.inherits to\r\n * express inheritance relationships between classes.\r\n *\r\n * NOTE: This is a replacement for goog.base and for superClass_\r\n * property defined in childCtor.\r\n *\r\n * @param {!Object} me Should always be \"this\".\r\n * @param {string} methodName The method name to call. Calling\r\n * superclass constructor can be done with the special string\r\n * 'constructor'.\r\n * @param {...*} var_args The arguments to pass to superclass\r\n * method/constructor.\r\n * @return {*} The return value of the superclass method/constructor.\r\n */\r\n childCtor.base = function(me, methodName, var_args) {\r\n // Copying using loop to avoid deop due to passing arguments object to\r\n // function. This is faster in many JS engines as of late 2014.\r\n var args = new Array(arguments.length - 2);\r\n for (var i = 2; i < arguments.length; i++) {\r\n args[i - 2] = arguments[i];\r\n }\r\n return parentCtor.prototype[methodName].apply(me, args);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Call up to the superclass.\r\n *\r\n * If this is called from a constructor, then this calls the superclass\r\n * constructor with arguments 1-N.\r\n *\r\n * If this is called from a prototype method, then you must pass the name of the\r\n * method as the second argument to this function. If you do not, you will get a\r\n * runtime error. This calls the superclass' method with arguments 2-N.\r\n *\r\n * This function only works if you use goog.inherits to express inheritance\r\n * relationships between your classes.\r\n *\r\n * This function is a compiler primitive. At compile-time, the compiler will do\r\n * macro expansion to remove a lot of the extra overhead that this function\r\n * introduces. The compiler will also enforce a lot of the assumptions that this\r\n * function makes, and treat it as a compiler error if you break them.\r\n *\r\n * @param {!Object} me Should always be \"this\".\r\n * @param {*=} opt_methodName The method name if calling a super method.\r\n * @param {...*} var_args The rest of the arguments.\r\n * @return {*} The return value of the superclass method.\r\n * @suppress {es5Strict} This method can not be used in strict mode, but\r\n * all Closure Library consumers must depend on this file.\r\n * @deprecated goog.base is not strict mode compatible. Prefer the static\r\n * \"base\" method added to the constructor by goog.inherits\r\n * or ES6 classes and the \"super\" keyword.\r\n */\r\ngoog.base = function(me, opt_methodName, var_args) {\r\n var caller = arguments.callee.caller;\r\n\r\n if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {\r\n throw new Error(\r\n 'arguments.caller not defined. goog.base() cannot be used ' +\r\n 'with strict mode code. See ' +\r\n 'http://www.ecma-international.org/ecma-262/5.1/#sec-C');\r\n }\r\n\r\n if (typeof caller.superClass_ !== 'undefined') {\r\n // Copying using loop to avoid deop due to passing arguments object to\r\n // function. This is faster in many JS engines as of late 2014.\r\n var ctorArgs = new Array(arguments.length - 1);\r\n for (var i = 1; i < arguments.length; i++) {\r\n ctorArgs[i - 1] = arguments[i];\r\n }\r\n // This is a constructor. Call the superclass constructor.\r\n return /** @type {!Function} */ (caller.superClass_)\r\n .constructor.apply(me, ctorArgs);\r\n }\r\n\r\n if (typeof opt_methodName != 'string' && typeof opt_methodName != 'symbol') {\r\n throw new Error(\r\n 'method names provided to goog.base must be a string or a symbol');\r\n }\r\n\r\n // Copying using loop to avoid deop due to passing arguments object to\r\n // function. This is faster in many JS engines as of late 2014.\r\n var args = new Array(arguments.length - 2);\r\n for (var i = 2; i < arguments.length; i++) {\r\n args[i - 2] = arguments[i];\r\n }\r\n var foundCaller = false;\r\n for (var ctor = me.constructor; ctor;\r\n ctor = ctor.superClass_ && ctor.superClass_.constructor) {\r\n if (ctor.prototype[opt_methodName] === caller) {\r\n foundCaller = true;\r\n } else if (foundCaller) {\r\n return ctor.prototype[opt_methodName].apply(me, args);\r\n }\r\n }\r\n\r\n // If we did not find the caller in the prototype chain, then one of two\r\n // things happened:\r\n // 1) The caller is an instance method.\r\n // 2) This method was not called by the right caller.\r\n if (me[opt_methodName] === caller) {\r\n return me.constructor.prototype[opt_methodName].apply(me, args);\r\n } else {\r\n throw new Error(\r\n 'goog.base called from a method of one name ' +\r\n 'to a method of a different name');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Allow for aliasing within scope functions. This function exists for\r\n * uncompiled code - in compiled code the calls will be inlined and the aliases\r\n * applied. In uncompiled code the function is simply run since the aliases as\r\n * written are valid JavaScript.\r\n *\r\n *\r\n * @param {function()} fn Function to call. This function can contain aliases\r\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\r\n * (e.g. \"var Timer = goog.Timer\").\r\n */\r\ngoog.scope = function(fn) {\r\n if (goog.isInModuleLoader_()) {\r\n throw new Error('goog.scope is not supported within a module.');\r\n }\r\n fn.call(goog.global);\r\n};\r\n\r\n\r\n/*\r\n * To support uncompiled, strict mode bundles that use eval to divide source\r\n * like so:\r\n * eval('someSource;//# sourceUrl sourcefile.js');\r\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\r\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\r\n * be defined externally.\r\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\r\n * extern generation when that compiler option is enabled.\r\n */\r\nif (!COMPILED) {\r\n goog.global['COMPILED'] = COMPILED;\r\n}\r\n\r\n\r\n//==============================================================================\r\n// goog.defineClass implementation\r\n//==============================================================================\r\n\r\n\r\n/**\r\n * Creates a restricted form of a Closure \"class\":\r\n * - from the compiler's perspective, the instance returned from the\r\n * constructor is sealed (no new properties may be added). This enables\r\n * better checks.\r\n * - the compiler will rewrite this definition to a form that is optimal\r\n * for type checking and optimization (initially this will be a more\r\n * traditional form).\r\n *\r\n * @param {Function} superClass The superclass, Object or null.\r\n * @param {goog.defineClass.ClassDescriptor} def\r\n * An object literal describing\r\n * the class. It may have the following properties:\r\n * \"constructor\": the constructor function\r\n * \"statics\": an object literal containing methods to add to the constructor\r\n * as \"static\" methods or a function that will receive the constructor\r\n * function as its only parameter to which static properties can\r\n * be added.\r\n * all other properties are added to the prototype.\r\n * @return {!Function} The class constructor.\r\n */\r\ngoog.defineClass = function(superClass, def) {\r\n // TODO(johnlenz): consider making the superClass an optional parameter.\r\n var constructor = def.constructor;\r\n var statics = def.statics;\r\n // Wrap the constructor prior to setting up the prototype and static methods.\r\n if (!constructor || constructor == Object.prototype.constructor) {\r\n constructor = function() {\r\n throw new Error(\r\n 'cannot instantiate an interface (no constructor defined).');\r\n };\r\n }\r\n\r\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\r\n if (superClass) {\r\n goog.inherits(cls, superClass);\r\n }\r\n\r\n // Remove all the properties that should not be copied to the prototype.\r\n delete def.constructor;\r\n delete def.statics;\r\n\r\n goog.defineClass.applyProperties_(cls.prototype, def);\r\n if (statics != null) {\r\n if (statics instanceof Function) {\r\n statics(cls);\r\n } else {\r\n goog.defineClass.applyProperties_(cls, statics);\r\n }\r\n }\r\n\r\n return cls;\r\n};\r\n\r\n\r\n/**\r\n * @typedef {{\r\n * constructor: (!Function|undefined),\r\n * statics: (Object|undefined|function(Function):void)\r\n * }}\r\n */\r\ngoog.defineClass.ClassDescriptor;\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the instances returned by goog.defineClass should\r\n * be sealed when possible.\r\n *\r\n * When sealing is disabled the constructor function will not be wrapped by\r\n * goog.defineClass, making it incompatible with ES6 class methods.\r\n */\r\ngoog.defineClass.SEAL_CLASS_INSTANCES =\r\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\r\n\r\n\r\n/**\r\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\r\n * defined, this function will wrap the constructor in a function that seals the\r\n * results of the provided constructor function.\r\n *\r\n * @param {!Function} ctr The constructor whose results maybe be sealed.\r\n * @param {Function} superClass The superclass constructor.\r\n * @return {!Function} The replacement constructor.\r\n * @private\r\n */\r\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\r\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\r\n // Do now wrap the constructor when sealing is disabled. Angular code\r\n // depends on this for injection to work properly.\r\n return ctr;\r\n }\r\n\r\n // Compute whether the constructor is sealable at definition time, rather\r\n // than when the instance is being constructed.\r\n var superclassSealable = !goog.defineClass.isUnsealable_(superClass);\r\n\r\n /**\r\n * @this {Object}\r\n * @return {?}\r\n */\r\n var wrappedCtr = function() {\r\n // Don't seal an instance of a subclass when it calls the constructor of\r\n // its super class as there is most likely still setup to do.\r\n var instance = ctr.apply(this, arguments) || this;\r\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\r\n\r\n if (this.constructor === wrappedCtr && superclassSealable &&\r\n Object.seal instanceof Function) {\r\n Object.seal(instance);\r\n }\r\n return instance;\r\n };\r\n\r\n return wrappedCtr;\r\n};\r\n\r\n\r\n/**\r\n * @param {Function} ctr The constructor to test.\r\n * @return {boolean} Whether the constructor has been tagged as unsealable\r\n * using goog.tagUnsealableClass.\r\n * @private\r\n */\r\ngoog.defineClass.isUnsealable_ = function(ctr) {\r\n return ctr && ctr.prototype &&\r\n ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_];\r\n};\r\n\r\n\r\n// TODO(johnlenz): share these values with the goog.object\r\n/**\r\n * The names of the fields that are defined on Object.prototype.\r\n * @type {!Array<string>}\r\n * @private\r\n * @const\r\n */\r\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\r\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\r\n 'toLocaleString', 'toString', 'valueOf'\r\n];\r\n\r\n\r\n// TODO(johnlenz): share this function with the goog.object\r\n/**\r\n * @param {!Object} target The object to add properties to.\r\n * @param {!Object} source The object to copy properties from.\r\n * @private\r\n */\r\ngoog.defineClass.applyProperties_ = function(target, source) {\r\n // TODO(johnlenz): update this to support ES5 getters/setters\r\n\r\n var key;\r\n for (key in source) {\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n target[key] = source[key];\r\n }\r\n }\r\n\r\n // For IE the for-in-loop does not contain any properties that are not\r\n // enumerable on the prototype object (for example isPrototypeOf from\r\n // Object.prototype) and it will also not include 'replace' on objects that\r\n // extend String and change 'replace' (not that it is common for anyone to\r\n // extend anything except Object).\r\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\r\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n target[key] = source[key];\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sealing classes breaks the older idiom of assigning properties on the\r\n * prototype rather than in the constructor. As such, goog.defineClass\r\n * must not seal subclasses of these old-style classes until they are fixed.\r\n * Until then, this marks a class as \"broken\", instructing defineClass\r\n * not to seal subclasses.\r\n * @param {!Function} ctr The legacy constructor to tag as unsealable.\r\n */\r\ngoog.tagUnsealableClass = function(ctr) {\r\n if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {\r\n ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Name for unsealable tag property.\r\n * @const @private {string}\r\n */\r\ngoog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';\r\n\r\n\r\n// There's a bug in the compiler where without collapse properties the\r\n// Closure namespace defines do not guard code correctly. To help reduce code\r\n// size also check for !COMPILED even though it redundant until this is fixed.\r\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\r\n\r\n /**\r\n * Tries to detect whether is in the context of an HTML document.\r\n * @return {boolean} True if it looks like HTML document.\r\n * @private\r\n */\r\n goog.inHtmlDocument_ = function() {\r\n /** @type {!Document} */\r\n var doc = goog.global.document;\r\n return doc != null && 'write' in doc; // XULDocument misses write.\r\n };\r\n\r\n\r\n /**\r\n * We'd like to check for if the document readyState is 'loading'; however\r\n * there are bugs on IE 10 and below where the readyState being anything other\r\n * than 'complete' is not reliable.\r\n * @return {boolean}\r\n * @private\r\n */\r\n goog.isDocumentLoading_ = function() {\r\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\r\n // detect those browsers.\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n return doc.attachEvent ? doc.readyState != 'complete' :\r\n doc.readyState == 'loading';\r\n };\r\n\r\n\r\n /**\r\n * Tries to detect the base path of base.js script that bootstraps Closure.\r\n * @private\r\n */\r\n goog.findBasePath_ = function() {\r\n if (goog.isDef(goog.global.CLOSURE_BASE_PATH) &&\r\n // Anti DOM-clobbering runtime check (b/37736576).\r\n goog.isString(goog.global.CLOSURE_BASE_PATH)) {\r\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\r\n return;\r\n } else if (!goog.inHtmlDocument_()) {\r\n return;\r\n }\r\n /** @type {!Document} */\r\n var doc = goog.global.document;\r\n // If we have a currentScript available, use it exclusively.\r\n var currentScript = doc.currentScript;\r\n if (currentScript) {\r\n var scripts = [currentScript];\r\n } else {\r\n var scripts = doc.getElementsByTagName('SCRIPT');\r\n }\r\n // Search backwards since the current script is in almost all cases the one\r\n // that has base.js.\r\n for (var i = scripts.length - 1; i >= 0; --i) {\r\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\r\n var src = script.src;\r\n var qmark = src.lastIndexOf('?');\r\n var l = qmark == -1 ? src.length : qmark;\r\n if (src.substr(l - 7, 7) == 'base.js') {\r\n goog.basePath = src.substr(0, l - 7);\r\n return;\r\n }\r\n }\r\n };\r\n\r\n goog.findBasePath_();\r\n\r\n /** @struct @constructor @final */\r\n goog.Transpiler = function() {\r\n /** @private {?Object<string, boolean>} */\r\n this.requiresTranspilation_ = null;\r\n /** @private {string} */\r\n this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;\r\n };\r\n\r\n\r\n /**\r\n * Returns a newly created map from language mode string to a boolean\r\n * indicating whether transpilation should be done for that mode as well as\r\n * the highest level language that this environment supports.\r\n *\r\n * Guaranteed invariant:\r\n * For any two modes, l1 and l2 where l2 is a newer mode than l1,\r\n * `map[l1] == true` implies that `map[l2] == true`.\r\n *\r\n * Note this method is extracted and used elsewhere, so it cannot rely on\r\n * anything external (it should easily be able to be transformed into a\r\n * standalone, top level function).\r\n *\r\n * @private\r\n * @return {{\r\n * target: string,\r\n * map: !Object<string, boolean>\r\n * }}\r\n */\r\n goog.Transpiler.prototype.createRequiresTranspilation_ = function() {\r\n var transpilationTarget = 'es3';\r\n var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};\r\n var transpilationRequiredForAllLaterModes = false;\r\n\r\n /**\r\n * Adds an entry to requiresTranspliation for the given language mode.\r\n *\r\n * IMPORTANT: Calls must be made in order from oldest to newest language\r\n * mode.\r\n * @param {string} modeName\r\n * @param {function(): boolean} isSupported Returns true if the JS engine\r\n * supports the given mode.\r\n */\r\n function addNewerLanguageTranspilationCheck(modeName, isSupported) {\r\n if (transpilationRequiredForAllLaterModes) {\r\n requiresTranspilation[modeName] = true;\r\n } else if (isSupported()) {\r\n transpilationTarget = modeName;\r\n requiresTranspilation[modeName] = false;\r\n } else {\r\n requiresTranspilation[modeName] = true;\r\n transpilationRequiredForAllLaterModes = true;\r\n }\r\n }\r\n\r\n /**\r\n * Does the given code evaluate without syntax errors and return a truthy\r\n * result?\r\n */\r\n function /** boolean */ evalCheck(/** string */ code) {\r\n try {\r\n return !!eval(code);\r\n } catch (ignored) {\r\n return false;\r\n }\r\n }\r\n\r\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\r\n goog.global.navigator.userAgent :\r\n '';\r\n\r\n // Identify ES3-only browsers by their incorrect treatment of commas.\r\n addNewerLanguageTranspilationCheck('es5', function() {\r\n return evalCheck('[1,].length==1');\r\n });\r\n addNewerLanguageTranspilationCheck('es6', function() {\r\n // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:\r\n // https://github.com/Microsoft/ChakraCore/issues/1496.\r\n var re = /Edge\\/(\\d+)(\\.\\d)*/i;\r\n var edgeUserAgent = userAgent.match(re);\r\n if (edgeUserAgent) {\r\n // The Reflect.construct test below is flaky on Edge. It can sometimes\r\n // pass or fail on 40 15.15063, so just exit early for Edge and treat\r\n // it as ES5. Until we're on a more up to date version just always use\r\n // ES5. See https://github.com/Microsoft/ChakraCore/issues/3217.\r\n return false;\r\n }\r\n // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]\r\n // (a) default params (specifically shadowing locals),\r\n // (b) destructuring, (c) block-scoped functions,\r\n // (d) for-of (const), (e) new.target/Reflect.construct\r\n var es6fullTest =\r\n 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +\r\n 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +\r\n 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +\r\n 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +\r\n '==3}';\r\n\r\n return evalCheck('(()=>{\"use strict\";' + es6fullTest + '})()');\r\n });\r\n // ** and **= are the only new features in 'es7'\r\n addNewerLanguageTranspilationCheck('es7', function() {\r\n return evalCheck('2 ** 2 == 4');\r\n });\r\n // async functions are the only new features in 'es8'\r\n addNewerLanguageTranspilationCheck('es8', function() {\r\n return evalCheck('async () => 1, true');\r\n });\r\n addNewerLanguageTranspilationCheck('es9', function() {\r\n return evalCheck('({...rest} = {}), true');\r\n });\r\n addNewerLanguageTranspilationCheck('es_next', function() {\r\n return false; // assume it always need to transpile\r\n });\r\n return {target: transpilationTarget, map: requiresTranspilation};\r\n };\r\n\r\n\r\n /**\r\n * Determines whether the given language needs to be transpiled.\r\n * @param {string} lang\r\n * @param {string|undefined} module\r\n * @return {boolean}\r\n */\r\n goog.Transpiler.prototype.needsTranspile = function(lang, module) {\r\n if (goog.TRANSPILE == 'always') {\r\n return true;\r\n } else if (goog.TRANSPILE == 'never') {\r\n return false;\r\n } else if (!this.requiresTranspilation_) {\r\n var obj = this.createRequiresTranspilation_();\r\n this.requiresTranspilation_ = obj.map;\r\n this.transpilationTarget_ = this.transpilationTarget_ || obj.target;\r\n }\r\n if (lang in this.requiresTranspilation_) {\r\n if (this.requiresTranspilation_[lang]) {\r\n return true;\r\n } else if (\r\n goog.inHtmlDocument_() && module == 'es6' &&\r\n !('noModule' in goog.global.document.createElement('script'))) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n throw new Error('Unknown language mode: ' + lang);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Lazily retrieves the transpiler and applies it to the source.\r\n * @param {string} code JS code.\r\n * @param {string} path Path to the code.\r\n * @return {string} The transpiled code.\r\n */\r\n goog.Transpiler.prototype.transpile = function(code, path) {\r\n // TODO(johnplaisted): We should delete goog.transpile_ and just have this\r\n // function. But there's some compile error atm where goog.global is being\r\n // stripped incorrectly without this.\r\n return goog.transpile_(code, path, this.transpilationTarget_);\r\n };\r\n\r\n\r\n /** @private @final {!goog.Transpiler} */\r\n goog.transpiler_ = new goog.Transpiler();\r\n\r\n /**\r\n * Rewrites closing script tags in input to avoid ending an enclosing script\r\n * tag.\r\n *\r\n * @param {string} str\r\n * @return {string}\r\n * @private\r\n */\r\n goog.protectScriptTag_ = function(str) {\r\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\r\n };\r\n\r\n\r\n /**\r\n * A debug loader is responsible for downloading and executing javascript\r\n * files in an unbundled, uncompiled environment.\r\n *\r\n * This can be custimized via the setDependencyFactory method, or by\r\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\r\n *\r\n * @struct @constructor @final @private\r\n */\r\n goog.DebugLoader_ = function() {\r\n /** @private @const {!Object<string, !goog.Dependency>} */\r\n this.dependencies_ = {};\r\n /** @private @const {!Object<string, string>} */\r\n this.idToPath_ = {};\r\n /** @private @const {!Object<string, boolean>} */\r\n this.written_ = {};\r\n /** @private @const {!Array<!goog.Dependency>} */\r\n this.loadingDeps_ = [];\r\n /** @private {!Array<!goog.Dependency>} */\r\n this.depsToLoad_ = [];\r\n /** @private {boolean} */\r\n this.paused_ = false;\r\n /** @private {!goog.DependencyFactory} */\r\n this.factory_ = new goog.DependencyFactory(goog.transpiler_);\r\n /** @private @const {!Object<string, !Function>} */\r\n this.deferredCallbacks_ = {};\r\n /** @private @const {!Array<string>} */\r\n this.deferredQueue_ = [];\r\n };\r\n\r\n /**\r\n * @param {!Array<string>} namespaces\r\n * @param {function(): undefined} callback Function to call once all the\r\n * namespaces have loaded.\r\n */\r\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\r\n var cb = callback;\r\n function resolve() {\r\n if (cb) {\r\n goog.global.setTimeout(cb, 0);\r\n cb = null;\r\n }\r\n }\r\n\r\n if (!namespaces.length) {\r\n resolve();\r\n return;\r\n }\r\n\r\n var deps = [];\r\n for (var i = 0; i < namespaces.length; i++) {\r\n var path = this.getPathFromDeps_(namespaces[i]);\r\n if (!path) {\r\n throw new Error('Unregonized namespace: ' + namespaces[i]);\r\n }\r\n deps.push(this.dependencies_[path]);\r\n }\r\n\r\n var require = goog.require;\r\n var loaded = 0;\r\n for (var i = 0; i < namespaces.length; i++) {\r\n require(namespaces[i]);\r\n deps[i].onLoad(function() {\r\n if (++loaded == namespaces.length) {\r\n resolve();\r\n }\r\n });\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Loads the Closure Dependency file.\r\n *\r\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\r\n * loaded, setDependencyFactory called, and then this called. i.e. allows\r\n * custom loading of the deps file.\r\n */\r\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\r\n // Circumvent addDependency, which would try to transpile deps.js if\r\n // transpile is set to always.\r\n var relPath = 'deps.js';\r\n this.depsToLoad_.push(this.factory_.createDependency(\r\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},\r\n false));\r\n this.loadDeps_();\r\n };\r\n\r\n\r\n /**\r\n * Notifies the debug loader when a dependency has been requested.\r\n *\r\n * @param {string} absPathOrId Path of the dependency or goog id.\r\n * @param {boolean=} opt_force\r\n */\r\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\r\n var path = this.getPathFromDeps_(absPathOrId);\r\n if (path &&\r\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\r\n var callback = this.deferredCallbacks_[path];\r\n if (callback) {\r\n delete this.deferredCallbacks_[path];\r\n callback();\r\n }\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Sets the dependency factory, which can be used to create custom\r\n * goog.Dependency implementations to control how dependencies are loaded.\r\n *\r\n * @param {!goog.DependencyFactory} factory\r\n */\r\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\r\n this.factory_ = factory;\r\n };\r\n\r\n\r\n /**\r\n * Travserses the dependency graph and queues the given dependency, and all of\r\n * its transitive dependencies, for loading and then starts loading if not\r\n * paused.\r\n *\r\n * @param {string} namespace\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.load_ = function(namespace) {\r\n if (!this.getPathFromDeps_(namespace)) {\r\n var errorMessage = 'goog.require could not find: ' + namespace;\r\n\r\n goog.logToConsole_(errorMessage);\r\n throw Error(errorMessage);\r\n } else {\r\n var loader = this;\r\n\r\n var deps = [];\r\n\r\n /** @param {string} namespace */\r\n var visit = function(namespace) {\r\n var path = loader.getPathFromDeps_(namespace);\r\n\r\n if (!path) {\r\n throw new Error('Bad dependency path or symbol: ' + namespace);\r\n }\r\n\r\n if (loader.written_[path]) {\r\n return;\r\n }\r\n\r\n loader.written_[path] = true;\r\n\r\n var dep = loader.dependencies_[path];\r\n for (var i = 0; i < dep.requires.length; i++) {\r\n if (!goog.isProvided_(dep.requires[i])) {\r\n visit(dep.requires[i]);\r\n }\r\n }\r\n\r\n deps.push(dep);\r\n };\r\n\r\n visit(namespace);\r\n\r\n var wasLoading = !!this.depsToLoad_.length;\r\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\r\n\r\n if (!this.paused_ && !wasLoading) {\r\n this.loadDeps_();\r\n }\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Loads any queued dependencies until they are all loaded or paused.\r\n *\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.loadDeps_ = function() {\r\n var loader = this;\r\n var paused = this.paused_;\r\n\r\n while (this.depsToLoad_.length && !paused) {\r\n (function() {\r\n var loadCallDone = false;\r\n var dep = loader.depsToLoad_.shift();\r\n\r\n var loaded = false;\r\n loader.loading_(dep);\r\n\r\n var controller = {\r\n pause: function() {\r\n if (loadCallDone) {\r\n throw new Error('Cannot call pause after the call to load.');\r\n } else {\r\n paused = true;\r\n }\r\n },\r\n resume: function() {\r\n if (loadCallDone) {\r\n loader.resume_();\r\n } else {\r\n // Some dep called pause and then resume in the same load call.\r\n // Just keep running this same loop.\r\n paused = false;\r\n }\r\n },\r\n loaded: function() {\r\n if (loaded) {\r\n throw new Error('Double call to loaded.');\r\n }\r\n\r\n loaded = true;\r\n loader.loaded_(dep);\r\n },\r\n pending: function() {\r\n // Defensive copy.\r\n var pending = [];\r\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\r\n pending.push(loader.loadingDeps_[i]);\r\n }\r\n return pending;\r\n },\r\n /**\r\n * @param {goog.ModuleType} type\r\n */\r\n setModuleState: function(type) {\r\n goog.moduleLoaderState_ = {\r\n type: type,\r\n moduleName: '',\r\n declareLegacyNamespace: false\r\n };\r\n },\r\n /** @type {function(string, string, string=)} */\r\n registerEs6ModuleExports: function(\r\n path, exports, opt_closureNamespace) {\r\n if (opt_closureNamespace) {\r\n goog.loadedModules_[opt_closureNamespace] = {\r\n exports: exports,\r\n type: goog.ModuleType.ES6,\r\n moduleId: opt_closureNamespace || ''\r\n };\r\n }\r\n },\r\n /** @type {function(string, ?)} */\r\n registerGoogModuleExports: function(moduleId, exports) {\r\n goog.loadedModules_[moduleId] = {\r\n exports: exports,\r\n type: goog.ModuleType.GOOG,\r\n moduleId: moduleId\r\n };\r\n },\r\n clearModuleState: function() {\r\n goog.moduleLoaderState_ = null;\r\n },\r\n defer: function(callback) {\r\n if (loadCallDone) {\r\n throw new Error(\r\n 'Cannot register with defer after the call to load.');\r\n }\r\n loader.defer_(dep, callback);\r\n },\r\n areDepsLoaded: function() {\r\n return loader.areDepsLoaded_(dep.requires);\r\n }\r\n };\r\n\r\n try {\r\n dep.load(controller);\r\n } finally {\r\n loadCallDone = true;\r\n }\r\n })();\r\n }\r\n\r\n if (paused) {\r\n this.pause_();\r\n }\r\n };\r\n\r\n\r\n /** @private */\r\n goog.DebugLoader_.prototype.pause_ = function() {\r\n this.paused_ = true;\r\n };\r\n\r\n\r\n /** @private */\r\n goog.DebugLoader_.prototype.resume_ = function() {\r\n if (this.paused_) {\r\n this.paused_ = false;\r\n this.loadDeps_();\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Marks the given dependency as loading (load has been called but it has not\r\n * yet marked itself as finished). Useful for dependencies that want to know\r\n * what else is loading. Example: goog.modules cannot eval if there are\r\n * loading dependencies.\r\n *\r\n * @param {!goog.Dependency} dep\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.loading_ = function(dep) {\r\n this.loadingDeps_.push(dep);\r\n };\r\n\r\n\r\n /**\r\n * Marks the given dependency as having finished loading and being available\r\n * for require.\r\n *\r\n * @param {!goog.Dependency} dep\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\r\n for (var i = 0; i < this.loadingDeps_.length; i++) {\r\n if (this.loadingDeps_[i] == dep) {\r\n this.loadingDeps_.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n for (var i = 0; i < this.deferredQueue_.length; i++) {\r\n if (this.deferredQueue_[i] == dep.path) {\r\n this.deferredQueue_.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\r\n !this.depsToLoad_.length) {\r\n // Something has asked to load these, but they may not be directly\r\n // required again later, so load them now that we know we're done loading\r\n // everything else. e.g. a goog module entry point.\r\n while (this.deferredQueue_.length) {\r\n this.requested(this.deferredQueue_.shift(), true);\r\n }\r\n }\r\n\r\n dep.loaded();\r\n };\r\n\r\n\r\n /**\r\n * @param {!Array<string>} pathsOrIds\r\n * @return {boolean}\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\r\n for (var i = 0; i < pathsOrIds.length; i++) {\r\n var path = this.getPathFromDeps_(pathsOrIds[i]);\r\n if (!path ||\r\n (!(path in this.deferredCallbacks_) &&\r\n !goog.isProvided_(pathsOrIds[i]))) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n };\r\n\r\n\r\n /**\r\n * @param {string} absPathOrId\r\n * @return {?string}\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\r\n if (absPathOrId in this.idToPath_) {\r\n return this.idToPath_[absPathOrId];\r\n } else if (absPathOrId in this.dependencies_) {\r\n return absPathOrId;\r\n } else {\r\n return null;\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @param {!goog.Dependency} dependency\r\n * @param {!Function} callback\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\r\n this.deferredCallbacks_[dependency.path] = callback;\r\n this.deferredQueue_.push(dependency.path);\r\n };\r\n\r\n\r\n /**\r\n * Interface for goog.Dependency implementations to have some control over\r\n * loading of dependencies.\r\n *\r\n * @record\r\n */\r\n goog.LoadController = function() {};\r\n\r\n\r\n /**\r\n * Tells the controller to halt loading of more dependencies.\r\n */\r\n goog.LoadController.prototype.pause = function() {};\r\n\r\n\r\n /**\r\n * Tells the controller to resume loading of more dependencies if paused.\r\n */\r\n goog.LoadController.prototype.resume = function() {};\r\n\r\n\r\n /**\r\n * Tells the controller that this dependency has finished loading.\r\n *\r\n * This causes this to be removed from pending() and any load callbacks to\r\n * fire.\r\n */\r\n goog.LoadController.prototype.loaded = function() {};\r\n\r\n\r\n /**\r\n * List of dependencies on which load has been called but which have not\r\n * called loaded on their controller. This includes the current dependency.\r\n *\r\n * @return {!Array<!goog.Dependency>}\r\n */\r\n goog.LoadController.prototype.pending = function() {};\r\n\r\n\r\n /**\r\n * Registers an object as an ES6 module's exports so that goog.modules may\r\n * require it by path.\r\n *\r\n * @param {string} path Full path of the module.\r\n * @param {?} exports\r\n * @param {string=} opt_closureNamespace Closure namespace to associate with\r\n * this module.\r\n */\r\n goog.LoadController.prototype.registerEs6ModuleExports = function(\r\n path, exports, opt_closureNamespace) {};\r\n\r\n\r\n /**\r\n * Sets the current module state.\r\n *\r\n * @param {goog.ModuleType} type Type of module.\r\n */\r\n goog.LoadController.prototype.setModuleState = function(type) {};\r\n\r\n\r\n /**\r\n * Clears the current module state.\r\n */\r\n goog.LoadController.prototype.clearModuleState = function() {};\r\n\r\n\r\n /**\r\n * Registers a callback to call once the dependency is actually requested\r\n * via goog.require + all of the immediate dependencies have been loaded or\r\n * all other files have been loaded. Allows for lazy loading until\r\n * require'd without pausing dependency loading, which is needed on old IE.\r\n *\r\n * @param {!Function} callback\r\n */\r\n goog.LoadController.prototype.defer = function(callback) {};\r\n\r\n\r\n /**\r\n * @return {boolean}\r\n */\r\n goog.LoadController.prototype.areDepsLoaded = function() {};\r\n\r\n\r\n /**\r\n * Basic super class for all dependencies Closure Library can load.\r\n *\r\n * This default implementation is designed to load untranspiled, non-module\r\n * scripts in a web broswer.\r\n *\r\n * For transpiled non-goog.module files {@see goog.TranspiledDependency}.\r\n * For goog.modules see {@see goog.GoogModuleDependency}.\r\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor\r\n */\r\n goog.Dependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n /** @const */\r\n this.path = path;\r\n /** @const */\r\n this.relativePath = relativePath;\r\n /** @const */\r\n this.provides = provides;\r\n /** @const */\r\n this.requires = requires;\r\n /** @const */\r\n this.loadFlags = loadFlags;\r\n /** @private {boolean} */\r\n this.loaded_ = false;\r\n /** @private {!Array<function()>} */\r\n this.loadCallbacks_ = [];\r\n };\r\n\r\n\r\n /**\r\n * @return {string} The pathname part of this dependency's path if it is a\r\n * URI.\r\n */\r\n goog.Dependency.prototype.getPathName = function() {\r\n var pathName = this.path;\r\n var protocolIndex = pathName.indexOf('://');\r\n if (protocolIndex >= 0) {\r\n pathName = pathName.substring(protocolIndex + 3);\r\n var slashIndex = pathName.indexOf('/');\r\n if (slashIndex >= 0) {\r\n pathName = pathName.substring(slashIndex + 1);\r\n }\r\n }\r\n return pathName;\r\n };\r\n\r\n\r\n /**\r\n * @param {function()} callback Callback to fire as soon as this has loaded.\r\n * @final\r\n */\r\n goog.Dependency.prototype.onLoad = function(callback) {\r\n if (this.loaded_) {\r\n callback();\r\n } else {\r\n this.loadCallbacks_.push(callback);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Marks this dependency as loaded and fires any callbacks registered with\r\n * onLoad.\r\n * @final\r\n */\r\n goog.Dependency.prototype.loaded = function() {\r\n this.loaded_ = true;\r\n var callbacks = this.loadCallbacks_;\r\n this.loadCallbacks_ = [];\r\n for (var i = 0; i < callbacks.length; i++) {\r\n callbacks[i]();\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Whether or not document.written / appended script tags should be deferred.\r\n *\r\n * @private {boolean}\r\n */\r\n goog.Dependency.defer_ = false;\r\n\r\n\r\n /**\r\n * Map of script ready / state change callbacks. Old IE cannot handle putting\r\n * these properties on goog.global.\r\n *\r\n * @private @const {!Object<string, function(?):undefined>}\r\n */\r\n goog.Dependency.callbackMap_ = {};\r\n\r\n\r\n /**\r\n * @param {function(...?):?} callback\r\n * @return {string}\r\n * @private\r\n */\r\n goog.Dependency.registerCallback_ = function(callback) {\r\n var key = Math.random().toString(32);\r\n goog.Dependency.callbackMap_[key] = callback;\r\n return key;\r\n };\r\n\r\n\r\n /**\r\n * @param {string} key\r\n * @private\r\n */\r\n goog.Dependency.unregisterCallback_ = function(key) {\r\n delete goog.Dependency.callbackMap_[key];\r\n };\r\n\r\n\r\n /**\r\n * @param {string} key\r\n * @param {...?} var_args\r\n * @private\r\n * @suppress {unusedPrivateMembers}\r\n */\r\n goog.Dependency.callback_ = function(key, var_args) {\r\n if (key in goog.Dependency.callbackMap_) {\r\n var callback = goog.Dependency.callbackMap_[key];\r\n var args = [];\r\n for (var i = 1; i < arguments.length; i++) {\r\n args.push(arguments[i]);\r\n }\r\n callback.apply(undefined, args);\r\n } else {\r\n var errorMessage = 'Callback key ' + key +\r\n ' does not exist (was base.js loaded more than once?).';\r\n throw Error(errorMessage);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Starts loading this dependency. This dependency can pause loading if it\r\n * needs to and resume it later via the controller interface.\r\n *\r\n * When this is loaded it should call controller.loaded(). Note that this will\r\n * end up calling the loaded method of this dependency; there is no need to\r\n * call it explicitly.\r\n *\r\n * @param {!goog.LoadController} controller\r\n */\r\n goog.Dependency.prototype.load = function(controller) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n if (!goog.inHtmlDocument_()) {\r\n goog.logToConsole_(\r\n 'Cannot use default debug loader outside of HTML documents.');\r\n if (this.relativePath == 'deps.js') {\r\n // Some old code is relying on base.js auto loading deps.js failing with\r\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\r\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\r\n // CLOSURE_NO_DEPS set to true.\r\n goog.logToConsole_(\r\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\r\n 'or setting CLOSURE_NO_DEPS to true.');\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n\r\n // If the user tries to require a new symbol after document load,\r\n // something has gone terribly wrong. Doing a document.write would\r\n // wipe out the page. This does not apply to the CSP-compliant method\r\n // of writing script tags.\r\n if (doc.readyState == 'complete' &&\r\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\r\n // Certain test frameworks load base.js multiple times, which tries\r\n // to write deps.js each time. If that happens, just fail silently.\r\n // These frameworks wipe the page between each load of base.js, so this\r\n // is OK.\r\n var isDeps = /\\bdeps.js$/.test(this.path);\r\n if (isDeps) {\r\n controller.loaded();\r\n return;\r\n } else {\r\n throw Error('Cannot write \"' + this.path + '\" after document load');\r\n }\r\n }\r\n\r\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\r\n goog.isDocumentLoading_()) {\r\n var key = goog.Dependency.registerCallback_(function(script) {\r\n if (!goog.DebugLoader_.IS_OLD_IE_ || script.readyState == 'complete') {\r\n goog.Dependency.unregisterCallback_(key);\r\n controller.loaded();\r\n }\r\n });\r\n var nonceAttr = !goog.DebugLoader_.IS_OLD_IE_ && goog.getScriptNonce() ?\r\n ' nonce=\"' + goog.getScriptNonce() + '\"' :\r\n '';\r\n var event =\r\n goog.DebugLoader_.IS_OLD_IE_ ? 'onreadystatechange' : 'onload';\r\n var defer = goog.Dependency.defer_ ? 'defer' : '';\r\n var script = '<script src=\"' + this.path + '\" ' + event +\r\n '=\"goog.Dependency.callback_(\\'' + key +\r\n '\\', this)\" type=\"text/javascript\" ' + defer + nonceAttr + '><' +\r\n '/script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n } else {\r\n var scriptEl =\r\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\r\n scriptEl.defer = goog.Dependency.defer_;\r\n scriptEl.async = false;\r\n scriptEl.type = 'text/javascript';\r\n\r\n // If CSP nonces are used, propagate them to dynamically created scripts.\r\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\r\n var nonce = goog.getScriptNonce();\r\n if (nonce) {\r\n scriptEl.setAttribute('nonce', nonce);\r\n }\r\n\r\n if (goog.DebugLoader_.IS_OLD_IE_) {\r\n // Execution order is not guaranteed on old IE, halt loading and write\r\n // these scripts one at a time, after each loads.\r\n controller.pause();\r\n scriptEl.onreadystatechange = function() {\r\n if (scriptEl.readyState == 'loaded' ||\r\n scriptEl.readyState == 'complete') {\r\n controller.loaded();\r\n controller.resume();\r\n }\r\n };\r\n } else {\r\n scriptEl.onload = function() {\r\n scriptEl.onload = null;\r\n controller.loaded();\r\n };\r\n }\r\n\r\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\r\n this.path;\r\n doc.head.appendChild(scriptEl);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides Should be an empty array.\r\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\r\n * modules for interop purposes.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor\r\n * @extends {goog.Dependency}\r\n */\r\n goog.Es6ModuleDependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n goog.Es6ModuleDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n };\r\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\r\n\r\n\r\n /** @override */\r\n goog.Es6ModuleDependency.prototype.load = function(controller) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n if (!goog.inHtmlDocument_()) {\r\n goog.logToConsole_(\r\n 'Cannot use default debug loader outside of HTML documents.');\r\n controller.pause();\r\n return;\r\n }\r\n\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n\r\n var dep = this;\r\n\r\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\r\n // difference between this and just waiting for interactive mode and then\r\n // appending?\r\n function write(src, contents) {\r\n if (contents) {\r\n var script = '<script type=\"module\" crossorigin>' + contents + '</' +\r\n 'script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n } else {\r\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"></' +\r\n 'script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n }\r\n }\r\n\r\n function append(src, contents) {\r\n var scriptEl =\r\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\r\n scriptEl.defer = true;\r\n scriptEl.async = false;\r\n scriptEl.type = 'module';\r\n scriptEl.setAttribute('crossorigin', true);\r\n\r\n // If CSP nonces are used, propagate them to dynamically created scripts.\r\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\r\n var nonce = goog.getScriptNonce();\r\n if (nonce) {\r\n scriptEl.setAttribute('nonce', nonce);\r\n }\r\n\r\n if (contents) {\r\n scriptEl.textContent = goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\r\n contents;\r\n } else {\r\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\r\n src;\r\n }\r\n\r\n doc.head.appendChild(scriptEl);\r\n }\r\n\r\n var create;\r\n\r\n if (goog.isDocumentLoading_()) {\r\n create = write;\r\n // We can ONLY call document.write if we are guaranteed that any\r\n // non-module script tags document.written after this are deferred.\r\n // Small optimization, in theory document.writing is faster.\r\n goog.Dependency.defer_ = true;\r\n } else {\r\n create = append;\r\n }\r\n\r\n // Write 4 separate tags here:\r\n // 1) Sets the module state at the correct time (just before execution).\r\n // 2) A src node for this, which just hopefully lets the browser load it a\r\n // little early (no need to parse #3).\r\n // 3) Import the module and register it.\r\n // 4) Clear the module state at the correct time. Guaranteed to run even\r\n // if there is an error in the module (#3 will not run if there is an\r\n // error in the module).\r\n var beforeKey = goog.Dependency.registerCallback_(function() {\r\n goog.Dependency.unregisterCallback_(beforeKey);\r\n controller.setModuleState(goog.ModuleType.ES6);\r\n });\r\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\r\n\r\n // TODO(johnplaisted): Does this really speed up anything?\r\n create(this.path, undefined);\r\n\r\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\r\n goog.Dependency.unregisterCallback_(registerKey);\r\n controller.registerEs6ModuleExports(\r\n dep.path, exports, goog.moduleLoaderState_.moduleName);\r\n });\r\n create(\r\n undefined,\r\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\r\n registerKey + '\", m)');\r\n\r\n var afterKey = goog.Dependency.registerCallback_(function() {\r\n goog.Dependency.unregisterCallback_(afterKey);\r\n controller.clearModuleState();\r\n controller.loaded();\r\n });\r\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\r\n };\r\n\r\n\r\n /**\r\n * Superclass of any dependency that needs to be loaded into memory,\r\n * transformed, and then eval'd (goog.modules and transpiled files).\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor @abstract\r\n * @extends {goog.Dependency}\r\n */\r\n goog.TransformedDependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n goog.TransformedDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n /** @private {?string} */\r\n this.contents_ = null;\r\n\r\n /**\r\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\r\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\r\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\r\n * it does then no other ES6 modules will load after).\r\n *\r\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\r\n * bugs on newer ones.\r\n *\r\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\r\n *\r\n * @private @const {boolean}\r\n */\r\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\r\n !('noModule' in goog.global.document.createElement('script'));\r\n };\r\n goog.inherits(goog.TransformedDependency, goog.Dependency);\r\n\r\n\r\n /** @override */\r\n goog.TransformedDependency.prototype.load = function(controller) {\r\n var dep = this;\r\n\r\n function fetch() {\r\n dep.contents_ = goog.loadFileSync_(dep.path);\r\n\r\n if (dep.contents_) {\r\n dep.contents_ = dep.transform(dep.contents_);\r\n if (dep.contents_) {\r\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\r\n }\r\n }\r\n }\r\n\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\r\n fetch();\r\n if (this.contents_ &&\r\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\r\n this.contents_ = null;\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n\r\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\r\n\r\n if (!this.lazyFetch_) {\r\n fetch();\r\n }\r\n\r\n function load() {\r\n if (dep.lazyFetch_) {\r\n fetch();\r\n }\r\n\r\n if (!dep.contents_) {\r\n // loadFileSync_ or transform are responsible. Assume they logged an\r\n // error.\r\n return;\r\n }\r\n\r\n if (isEs6) {\r\n controller.setModuleState(goog.ModuleType.ES6);\r\n }\r\n\r\n var namespace;\r\n\r\n try {\r\n var contents = dep.contents_;\r\n dep.contents_ = null;\r\n goog.globalEval(contents);\r\n if (isEs6) {\r\n namespace = goog.moduleLoaderState_.moduleName;\r\n }\r\n } finally {\r\n if (isEs6) {\r\n controller.clearModuleState();\r\n }\r\n }\r\n\r\n if (isEs6) {\r\n // Due to circular dependencies this may not be available for require\r\n // right now.\r\n goog.global['$jscomp']['require']['ensure'](\r\n [dep.getPathName()], function() {\r\n controller.registerEs6ModuleExports(\r\n dep.path,\r\n goog.global['$jscomp']['require'](dep.getPathName()),\r\n namespace);\r\n });\r\n }\r\n\r\n controller.loaded();\r\n }\r\n\r\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\r\n // events. If we fetched now and then document.write'd the contents the\r\n // document.write would be an eval and would execute too soon! Instead write\r\n // a script tag to fetch and eval synchronously at the correct time.\r\n function fetchInOwnScriptThenLoad() {\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n\r\n var key = goog.Dependency.registerCallback_(function() {\r\n goog.Dependency.unregisterCallback_(key);\r\n load();\r\n });\r\n\r\n var script = '<script type=\"text/javascript\">' +\r\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\r\n '</' +\r\n 'script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n }\r\n\r\n // If one thing is pending it is this.\r\n var anythingElsePending = controller.pending().length > 1;\r\n\r\n // If anything else is loading we need to lazy load due to bugs in old IE.\r\n // Specifically script tags with src and script tags with contents could\r\n // execute out of order if document.write is used, so we cannot use\r\n // document.write. Do not pause here; it breaks old IE as well.\r\n var useOldIeWorkAround =\r\n anythingElsePending && goog.DebugLoader_.IS_OLD_IE_;\r\n\r\n // Additionally if we are meant to defer scripts but the page is still\r\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\r\n // meant to defer and anything else is pending then defer (those may be\r\n // scripts that did not need transformation and are just script tags with\r\n // defer set to true, and we need to evaluate after that deferred script).\r\n var needsAsyncLoading = goog.Dependency.defer_ &&\r\n (anythingElsePending || goog.isDocumentLoading_());\r\n\r\n if (useOldIeWorkAround || needsAsyncLoading) {\r\n // Note that we only defer when we have to rather than 100% of the time.\r\n // Always defering would work, but then in theory the order of\r\n // goog.require calls would then matter. We want to enforce that most of\r\n // the time the order of the require calls does not matter.\r\n controller.defer(function() {\r\n load();\r\n });\r\n return;\r\n }\r\n // TODO(johnplaisted): Externs are missing onreadystatechange for\r\n // HTMLDocument.\r\n /** @type {?} */\r\n var doc = goog.global.document;\r\n\r\n var isInternetExplorer =\r\n goog.inHtmlDocument_() && 'ActiveXObject' in goog.global;\r\n\r\n // Don't delay in any version of IE. There's bug around this that will\r\n // cause out of order script execution. This means that on older IE ES6\r\n // modules will load too early (while the document is still loading + the\r\n // dom is not available). The other option is to load too late (when the\r\n // document is complete and the onload even will never fire). This seems\r\n // to be the lesser of two evils as scripts already act like the former.\r\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\r\n !isInternetExplorer) {\r\n goog.Dependency.defer_ = true;\r\n // Transpiled ES6 modules still need to load like regular ES6 modules,\r\n // aka only after the document is interactive.\r\n controller.pause();\r\n var oldCallback = doc.onreadystatechange;\r\n doc.onreadystatechange = function() {\r\n if (doc.readyState == 'interactive') {\r\n doc.onreadystatechange = oldCallback;\r\n load();\r\n controller.resume();\r\n }\r\n if (goog.isFunction(oldCallback)) {\r\n oldCallback.apply(undefined, arguments);\r\n }\r\n };\r\n } else {\r\n // Always eval on old IE.\r\n if (goog.DebugLoader_.IS_OLD_IE_ || !goog.inHtmlDocument_() ||\r\n !goog.isDocumentLoading_()) {\r\n load();\r\n } else {\r\n fetchInOwnScriptThenLoad();\r\n }\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @param {string} contents\r\n * @return {string}\r\n * @abstract\r\n */\r\n goog.TransformedDependency.prototype.transform = function(contents) {};\r\n\r\n\r\n /**\r\n * Any non-goog.module dependency which needs to be transpiled before eval.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @param {!goog.Transpiler} transpiler\r\n * @struct @constructor\r\n * @extends {goog.TransformedDependency}\r\n */\r\n goog.TranspiledDependency = function(\r\n path, relativePath, provides, requires, loadFlags, transpiler) {\r\n goog.TranspiledDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n /** @protected @const*/\r\n this.transpiler = transpiler;\r\n };\r\n goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);\r\n\r\n\r\n /** @override */\r\n goog.TranspiledDependency.prototype.transform = function(contents) {\r\n // Transpile with the pathname so that ES6 modules are domain agnostic.\r\n return this.transpiler.transpile(contents, this.getPathName());\r\n };\r\n\r\n\r\n /**\r\n * An ES6 module dependency that was transpiled to a jscomp module outside\r\n * of the debug loader, e.g. server side.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor\r\n * @extends {goog.TransformedDependency}\r\n */\r\n goog.PreTranspiledEs6ModuleDependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n goog.PreTranspiledEs6ModuleDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n };\r\n goog.inherits(\r\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\r\n\r\n\r\n /** @override */\r\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\r\n contents) {\r\n return contents;\r\n };\r\n\r\n\r\n /**\r\n * A goog.module, transpiled or not. Will always perform some minimal\r\n * transformation even when not transpiled to wrap in a goog.loadModule\r\n * statement.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @param {boolean} needsTranspile\r\n * @param {!goog.Transpiler} transpiler\r\n * @struct @constructor\r\n * @extends {goog.TransformedDependency}\r\n */\r\n goog.GoogModuleDependency = function(\r\n path, relativePath, provides, requires, loadFlags, needsTranspile,\r\n transpiler) {\r\n goog.GoogModuleDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n /** @private @const */\r\n this.needsTranspile_ = needsTranspile;\r\n /** @private @const */\r\n this.transpiler_ = transpiler;\r\n };\r\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\r\n\r\n\r\n /** @override */\r\n goog.GoogModuleDependency.prototype.transform = function(contents) {\r\n if (this.needsTranspile_) {\r\n contents = this.transpiler_.transpile(contents, this.getPathName());\r\n }\r\n\r\n if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {\r\n return '' +\r\n 'goog.loadModule(function(exports) {' +\r\n '\"use strict\";' + contents +\r\n '\\n' + // terminate any trailing single line comment.\r\n ';return exports' +\r\n '});' +\r\n '\\n//# sourceURL=' + this.path + '\\n';\r\n } else {\r\n return '' +\r\n 'goog.loadModule(' +\r\n goog.global.JSON.stringify(\r\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\r\n ');';\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Whether the browser is IE9 or earlier, which needs special handling\r\n * for deferred modules.\r\n * @const @private {boolean}\r\n */\r\n goog.DebugLoader_.IS_OLD_IE_ = !!(\r\n !goog.global.atob && goog.global.document && goog.global.document['all']);\r\n\r\n\r\n /**\r\n * @param {string} relPath\r\n * @param {!Array<string>|undefined} provides\r\n * @param {!Array<string>} requires\r\n * @param {boolean|!Object<string>=} opt_loadFlags\r\n * @see goog.addDependency\r\n */\r\n goog.DebugLoader_.prototype.addDependency = function(\r\n relPath, provides, requires, opt_loadFlags) {\r\n provides = provides || [];\r\n relPath = relPath.replace(/\\\\/g, '/');\r\n var path = goog.normalizePath_(goog.basePath + relPath);\r\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\r\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\r\n }\r\n var dep = this.factory_.createDependency(\r\n path, relPath, provides, requires, opt_loadFlags,\r\n goog.transpiler_.needsTranspile(\r\n opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));\r\n this.dependencies_[path] = dep;\r\n for (var i = 0; i < provides.length; i++) {\r\n this.idToPath_[provides[i]] = path;\r\n }\r\n this.idToPath_[relPath] = path;\r\n };\r\n\r\n\r\n /**\r\n * Creates goog.Dependency instances for the debug loader to load.\r\n *\r\n * Should be overridden to have the debug loader use custom subclasses of\r\n * goog.Dependency.\r\n *\r\n * @param {!goog.Transpiler} transpiler\r\n * @struct @constructor\r\n */\r\n goog.DependencyFactory = function(transpiler) {\r\n /** @protected @const */\r\n this.transpiler = transpiler;\r\n };\r\n\r\n\r\n /**\r\n * @param {string} path Absolute path of the file.\r\n * @param {string} relativePath Path relative to closures base.js.\r\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\r\n * @param {!Array<string>} requires Array of required goog.provide/module /\r\n * relative ES6 module paths.\r\n * @param {!Object<string, string>} loadFlags\r\n * @param {boolean} needsTranspile True if the file needs to be transpiled\r\n * per the goog.Transpiler.\r\n * @return {!goog.Dependency}\r\n */\r\n goog.DependencyFactory.prototype.createDependency = function(\r\n path, relativePath, provides, requires, loadFlags, needsTranspile) {\r\n\r\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\r\n return new goog.GoogModuleDependency(\r\n path, relativePath, provides, requires, loadFlags, needsTranspile,\r\n this.transpiler);\r\n } else if (needsTranspile) {\r\n return new goog.TranspiledDependency(\r\n path, relativePath, provides, requires, loadFlags, this.transpiler);\r\n } else {\r\n if (loadFlags['module'] == goog.ModuleType.ES6) {\r\n if (goog.TRANSPILE == 'never' && goog.ASSUME_ES_MODULES_TRANSPILED) {\r\n return new goog.PreTranspiledEs6ModuleDependency(\r\n path, relativePath, provides, requires, loadFlags);\r\n } else {\r\n return new goog.Es6ModuleDependency(\r\n path, relativePath, provides, requires, loadFlags);\r\n }\r\n } else {\r\n return new goog.Dependency(\r\n path, relativePath, provides, requires, loadFlags);\r\n }\r\n }\r\n };\r\n\r\n\r\n /** @private @const */\r\n goog.debugLoader_ = new goog.DebugLoader_();\r\n\r\n\r\n /**\r\n * Loads the Closure Dependency file.\r\n *\r\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\r\n * loaded, setDependencyFactory called, and then this called. i.e. allows\r\n * custom loading of the deps file.\r\n */\r\n goog.loadClosureDeps = function() {\r\n goog.debugLoader_.loadClosureDeps();\r\n };\r\n\r\n\r\n /**\r\n * Sets the dependency factory, which can be used to create custom\r\n * goog.Dependency implementations to control how dependencies are loaded.\r\n *\r\n * Note: if you wish to call this function and provide your own implemnetation\r\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\r\n * file and all of its goog.addDependency calls will use the default factory.\r\n * You can call goog.loadClosureDeps to load the Closure dependency file\r\n * later, after your factory is injected.\r\n *\r\n * @param {!goog.DependencyFactory} factory\r\n */\r\n goog.setDependencyFactory = function(factory) {\r\n goog.debugLoader_.setDependencyFactory(factory);\r\n };\r\n\r\n\r\n if (!goog.global.CLOSURE_NO_DEPS) {\r\n goog.debugLoader_.loadClosureDeps();\r\n }\r\n\r\n\r\n /**\r\n * Bootstraps the given namespaces and calls the callback once they are\r\n * available either via goog.require. This is a replacement for using\r\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\r\n * in an HTML file would guarantee that the require'd namespace was available\r\n * in the next immediate script tag. With ES6 modules this no longer a\r\n * guarantee.\r\n *\r\n * @param {!Array<string>} namespaces\r\n * @param {function(): ?} callback Function to call once all the namespaces\r\n * have loaded. Always called asynchronously.\r\n */\r\n goog.bootstrap = function(namespaces, callback) {\r\n goog.debugLoader_.bootstrap(namespaces, callback);\r\n };\r\n}\r\n\r\n\r\n/**\r\n * @define {string} Trusted Types policy name. If non-empty then Closure will\r\n * use Trusted Types.\r\n */\r\ngoog.TRUSTED_TYPES_POLICY_NAME =\r\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', '');\r\n\r\n\r\n/**\r\n * Returns the parameter.\r\n * @param {string} s\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.identity_ = function(s) {\r\n return s;\r\n};\r\n\r\n\r\n/**\r\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\r\n * The policy just blesses any string as a Trusted Type. It is not visibility\r\n * restricted because anyone can also call TrustedTypes.createPolicy directly.\r\n * However, the allowed names should be restricted by a HTTP header and the\r\n * reference to the created policy should be visibility restricted.\r\n * @param {string} name\r\n * @return {?TrustedTypePolicy}\r\n * @throws {!TypeError} If called with a name which is already registered.\r\n */\r\ngoog.createTrustedTypesPolicy = function(name) {\r\n if (typeof TrustedTypes === 'undefined' || !TrustedTypes.createPolicy) {\r\n return null;\r\n }\r\n return TrustedTypes.createPolicy(name, {\r\n createHTML: goog.identity_,\r\n createScript: goog.identity_,\r\n createScriptURL: goog.identity_,\r\n createURL: goog.identity_\r\n });\r\n};\r\n\r\n\r\n/** @private @const {?TrustedTypePolicy} */\r\ngoog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\r\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\r\n null;\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Implements the disposable interface. The dispose method is used\r\n * to clean up references and resources.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.Disposable');\r\ngoog.provide('goog.dispose');\r\ngoog.provide('goog.disposeAll');\r\n\r\ngoog.require('goog.disposable.IDisposable');\r\n\r\n\r\n\r\n/**\r\n * Class that provides the basic implementation for disposable objects. If your\r\n * class holds one or more references to COM objects, DOM nodes, or other\r\n * disposable objects, it should extend this class or implement the disposable\r\n * interface (defined in goog.disposable.IDisposable).\r\n * @constructor\r\n * @implements {goog.disposable.IDisposable}\r\n */\r\ngoog.Disposable = function() {\r\n /**\r\n * If monitoring the goog.Disposable instances is enabled, stores the creation\r\n * stack trace of the Disposable instance.\r\n * @type {string|undefined}\r\n */\r\n this.creationStack;\r\n\r\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\r\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\r\n this.creationStack = new Error().stack;\r\n }\r\n goog.Disposable.instances_[goog.getUid(this)] = this;\r\n }\r\n // Support sealing\r\n this.disposed_ = this.disposed_;\r\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\r\n};\r\n\r\n\r\n/**\r\n * @enum {number} Different monitoring modes for Disposable.\r\n */\r\ngoog.Disposable.MonitoringMode = {\r\n /**\r\n * No monitoring.\r\n */\r\n OFF: 0,\r\n /**\r\n * Creating and disposing the goog.Disposable instances is monitored. All\r\n * disposable objects need to call the `goog.Disposable` base\r\n * constructor. The PERMANENT mode must be switched on before creating any\r\n * goog.Disposable instances.\r\n */\r\n PERMANENT: 1,\r\n /**\r\n * INTERACTIVE mode can be switched on and off on the fly without producing\r\n * errors. It also doesn't warn if the disposable objects don't call the\r\n * `goog.Disposable` base constructor.\r\n */\r\n INTERACTIVE: 2\r\n};\r\n\r\n\r\n/**\r\n * @define {number} The monitoring mode of the goog.Disposable\r\n * instances. Default is OFF. Switching on the monitoring is only\r\n * recommended for debugging because it has a significant impact on\r\n * performance and memory usage. If switched off, the monitoring code\r\n * compiles down to 0 bytes.\r\n */\r\ngoog.Disposable.MONITORING_MODE =\r\n goog.define('goog.Disposable.MONITORING_MODE', 0);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to attach creation stack to each created disposable\r\n * instance; This is only relevant for when MonitoringMode != OFF.\r\n */\r\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\r\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\r\n\r\n\r\n/**\r\n * Maps the unique ID of every undisposed `goog.Disposable` object to\r\n * the object itself.\r\n * @type {!Object<number, !goog.Disposable>}\r\n * @private\r\n */\r\ngoog.Disposable.instances_ = {};\r\n\r\n\r\n/**\r\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\r\n * haven't been disposed of.\r\n */\r\ngoog.Disposable.getUndisposedObjects = function() {\r\n var ret = [];\r\n for (var id in goog.Disposable.instances_) {\r\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\r\n ret.push(goog.Disposable.instances_[Number(id)]);\r\n }\r\n }\r\n return ret;\r\n};\r\n\r\n\r\n/**\r\n * Clears the registry of undisposed objects but doesn't dispose of them.\r\n */\r\ngoog.Disposable.clearUndisposedObjects = function() {\r\n goog.Disposable.instances_ = {};\r\n};\r\n\r\n\r\n/**\r\n * Whether the object has been disposed of.\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.Disposable.prototype.disposed_ = false;\r\n\r\n\r\n/**\r\n * Callbacks to invoke when this object is disposed.\r\n * @type {Array<!Function>}\r\n * @private\r\n */\r\ngoog.Disposable.prototype.onDisposeCallbacks_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the object has been disposed of.\r\n * @override\r\n */\r\ngoog.Disposable.prototype.isDisposed = function() {\r\n return this.disposed_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the object has been disposed of.\r\n * @deprecated Use {@link #isDisposed} instead.\r\n */\r\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\r\n\r\n\r\n/**\r\n * Disposes of the object. If the object hasn't already been disposed of, calls\r\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\r\n * override {@link #disposeInternal} in order to delete references to COM\r\n * objects, DOM nodes, and other disposable objects. Reentrant.\r\n *\r\n * @return {void} Nothing.\r\n * @override\r\n */\r\ngoog.Disposable.prototype.dispose = function() {\r\n if (!this.disposed_) {\r\n // Set disposed_ to true first, in case during the chain of disposal this\r\n // gets disposed recursively.\r\n this.disposed_ = true;\r\n this.disposeInternal();\r\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\r\n var uid = goog.getUid(this);\r\n if (goog.Disposable.MONITORING_MODE ==\r\n goog.Disposable.MonitoringMode.PERMANENT &&\r\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\r\n throw new Error(\r\n this + ' did not call the goog.Disposable base ' +\r\n 'constructor or was disposed of after a clearUndisposedObjects ' +\r\n 'call');\r\n }\r\n if (goog.Disposable.MONITORING_MODE !=\r\n goog.Disposable.MonitoringMode.OFF &&\r\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\r\n throw new Error(\r\n this + ' did not empty its onDisposeCallbacks queue. This ' +\r\n 'probably means it overrode dispose() or disposeInternal() ' +\r\n 'without calling the superclass\\' method.');\r\n }\r\n delete goog.Disposable.instances_[uid];\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Associates a disposable object with this object so that they will be disposed\r\n * together.\r\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\r\n * this object is disposed.\r\n */\r\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\r\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\r\n};\r\n\r\n\r\n/**\r\n * Invokes a callback function when this object is disposed. Callbacks are\r\n * invoked in the order in which they were added. If a callback is added to\r\n * an already disposed Disposable, it will be called immediately.\r\n * @param {function(this:T):?} callback The callback function.\r\n * @param {T=} opt_scope An optional scope to call the callback in.\r\n * @template T\r\n */\r\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\r\n if (this.disposed_) {\r\n goog.isDef(opt_scope) ? callback.call(opt_scope) : callback();\r\n return;\r\n }\r\n if (!this.onDisposeCallbacks_) {\r\n this.onDisposeCallbacks_ = [];\r\n }\r\n\r\n this.onDisposeCallbacks_.push(\r\n goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback);\r\n};\r\n\r\n\r\n/**\r\n * Deletes or nulls out any references to COM objects, DOM nodes, or other\r\n * disposable objects. Classes that extend `goog.Disposable` should\r\n * override this method.\r\n * Not reentrant. To avoid calling it twice, it must only be called from the\r\n * subclass' `disposeInternal` method. Everywhere else the public\r\n * `dispose` method must be used.\r\n * For example:\r\n * <pre>\r\n * mypackage.MyClass = function() {\r\n * mypackage.MyClass.base(this, 'constructor');\r\n * // Constructor logic specific to MyClass.\r\n * ...\r\n * };\r\n * goog.inherits(mypackage.MyClass, goog.Disposable);\r\n *\r\n * mypackage.MyClass.prototype.disposeInternal = function() {\r\n * // Dispose logic specific to MyClass.\r\n * ...\r\n * // Call superclass's disposeInternal at the end of the subclass's, like\r\n * // in C++, to avoid hard-to-catch issues.\r\n * mypackage.MyClass.base(this, 'disposeInternal');\r\n * };\r\n * </pre>\r\n * @protected\r\n */\r\ngoog.Disposable.prototype.disposeInternal = function() {\r\n if (this.onDisposeCallbacks_) {\r\n while (this.onDisposeCallbacks_.length) {\r\n this.onDisposeCallbacks_.shift()();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns True if we can verify the object is disposed.\r\n * Calls `isDisposed` on the argument if it supports it. If obj\r\n * is not an object with an isDisposed() method, return false.\r\n * @param {*} obj The object to investigate.\r\n * @return {boolean} True if we can verify the object is disposed.\r\n */\r\ngoog.Disposable.isDisposed = function(obj) {\r\n if (obj && typeof obj.isDisposed == 'function') {\r\n return obj.isDisposed();\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Calls `dispose` on the argument if it supports it. If obj is not an\r\n * object with a dispose() method, this is a no-op.\r\n * @param {*} obj The object to dispose of.\r\n */\r\ngoog.dispose = function(obj) {\r\n if (obj && typeof obj.dispose == 'function') {\r\n obj.dispose();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls `dispose` on each member of the list that supports it. (If the\r\n * member is an ArrayLike, then `goog.disposeAll()` will be called\r\n * recursively on each of its members.) If the member is not an object with a\r\n * `dispose()` method, then it is ignored.\r\n * @param {...*} var_args The list.\r\n */\r\ngoog.disposeAll = function(var_args) {\r\n for (var i = 0, len = arguments.length; i < len; ++i) {\r\n var disposable = arguments[i];\r\n if (goog.isArrayLike(disposable)) {\r\n goog.disposeAll.apply(null, disposable);\r\n } else {\r\n goog.dispose(disposable);\r\n }\r\n }\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for manipulating arrays.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.array');\r\n\r\ngoog.require('goog.asserts');\r\n\r\n\r\n/**\r\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\r\n * rely on Array.prototype functions, if available.\r\n *\r\n * The Array.prototype functions can be defined by external libraries like\r\n * Prototype and setting this flag to false forces closure to use its own\r\n * goog.array implementation.\r\n *\r\n * If your javascript can be loaded by a third party site and you are wary about\r\n * relying on the prototype functions, specify\r\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\r\n *\r\n * Setting goog.TRUSTED_SITE to false will automatically set\r\n * NATIVE_ARRAY_PROTOTYPES to false.\r\n */\r\ngoog.NATIVE_ARRAY_PROTOTYPES =\r\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\r\n\r\n\r\n/**\r\n * @define {boolean} If true, JSCompiler will use the native implementation of\r\n * array functions where appropriate (e.g., `Array#filter`) and remove the\r\n * unused pure JS implementation.\r\n */\r\ngoog.array.ASSUME_NATIVE_FUNCTIONS =\r\n goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);\r\n\r\n\r\n/**\r\n * Returns the last element in an array without removing it.\r\n * Same as goog.array.last.\r\n * @param {IArrayLike<T>|string} array The array.\r\n * @return {T} Last item in array.\r\n * @template T\r\n */\r\ngoog.array.peek = function(array) {\r\n return array[array.length - 1];\r\n};\r\n\r\n\r\n/**\r\n * Returns the last element in an array without removing it.\r\n * Same as goog.array.peek.\r\n * @param {IArrayLike<T>|string} array The array.\r\n * @return {T} Last item in array.\r\n * @template T\r\n */\r\ngoog.array.last = goog.array.peek;\r\n\r\n// NOTE(arv): Since most of the array functions are generic it allows you to\r\n// pass an array-like object. Strings have a length and are considered array-\r\n// like. However, the 'in' operator does not work on strings so we cannot just\r\n// use the array path even if the browser supports indexing into strings. We\r\n// therefore end up splitting the string.\r\n\r\n\r\n/**\r\n * Returns the index of the first element of an array with a specified value, or\r\n * -1 if the element is not present in the array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\r\n *\r\n * @param {IArrayLike<T>|string} arr The array to be searched.\r\n * @param {T} obj The object for which we are searching.\r\n * @param {number=} opt_fromIndex The index at which to start the search. If\r\n * omitted the search starts at index 0.\r\n * @return {number} The index of the first matching array element.\r\n * @template T\r\n */\r\ngoog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\r\n function(arr, obj, opt_fromIndex) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\r\n } :\r\n function(arr, obj, opt_fromIndex) {\r\n var fromIndex = opt_fromIndex == null ?\r\n 0 :\r\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\r\n opt_fromIndex);\r\n\r\n if (goog.isString(arr)) {\r\n // Array.prototype.indexOf uses === so only strings should be found.\r\n if (!goog.isString(obj) || obj.length != 1) {\r\n return -1;\r\n }\r\n return arr.indexOf(obj, fromIndex);\r\n }\r\n\r\n for (var i = fromIndex; i < arr.length; i++) {\r\n if (i in arr && arr[i] === obj) return i;\r\n }\r\n return -1;\r\n };\r\n\r\n\r\n/**\r\n * Returns the index of the last element of an array with a specified value, or\r\n * -1 if the element is not present in the array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\r\n *\r\n * @param {!IArrayLike<T>|string} arr The array to be searched.\r\n * @param {T} obj The object for which we are searching.\r\n * @param {?number=} opt_fromIndex The index at which to start the search. If\r\n * omitted the search starts at the end of the array.\r\n * @return {number} The index of the last matching array element.\r\n * @template T\r\n */\r\ngoog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\r\n function(arr, obj, opt_fromIndex) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n // Firefox treats undefined and null as 0 in the fromIndex argument which\r\n // leads it to always return -1\r\n var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\r\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\r\n } :\r\n function(arr, obj, opt_fromIndex) {\r\n var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\r\n\r\n if (fromIndex < 0) {\r\n fromIndex = Math.max(0, arr.length + fromIndex);\r\n }\r\n\r\n if (goog.isString(arr)) {\r\n // Array.prototype.lastIndexOf uses === so only strings should be found.\r\n if (!goog.isString(obj) || obj.length != 1) {\r\n return -1;\r\n }\r\n return arr.lastIndexOf(obj, fromIndex);\r\n }\r\n\r\n for (var i = fromIndex; i >= 0; i--) {\r\n if (i in arr && arr[i] === obj) return i;\r\n }\r\n return -1;\r\n };\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array. Skips holes in the array.\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array like object over\r\n * which to iterate.\r\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\r\n * element. This function takes 3 arguments (the element, the index and the\r\n * array). The return value is ignored.\r\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\r\n * @template T,S\r\n */\r\ngoog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n Array.prototype.forEach.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2) {\r\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\r\n }\r\n }\r\n };\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array, starting from the last\r\n * element rather than the first.\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\r\n * element. This function\r\n * takes 3 arguments (the element, the index and the array). The return\r\n * value is ignored.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @template T,S\r\n */\r\ngoog.array.forEachRight = function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = l - 1; i >= 0; --i) {\r\n if (i in arr2) {\r\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array, and if the function returns\r\n * true adds the element to a new array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\r\n * every element. This function\r\n * takes 3 arguments (the element, the index and the array) and must\r\n * return a Boolean. If the return value is true the element is added to the\r\n * result array. If it is false the element is not included.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {!Array<T>} a new array in which only elements that passed the test\r\n * are present.\r\n * @template T,S\r\n */\r\ngoog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.filter.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var res = [];\r\n var resLength = 0;\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2) {\r\n var val = arr2[i]; // in case f mutates arr2\r\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\r\n res[resLength++] = val;\r\n }\r\n }\r\n }\r\n return res;\r\n };\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array and inserts the result into a\r\n * new array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\r\n *\r\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\r\n * over which to iterate.\r\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\r\n * for every element. This function takes 3 arguments (the element,\r\n * the index and the array) and should return something. The result will be\r\n * inserted into a new array.\r\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\r\n * @return {!Array<RESULT>} a new array with the results from f.\r\n * @template THIS, VALUE, RESULT\r\n */\r\ngoog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.map.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var res = new Array(l);\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2) {\r\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\r\n }\r\n }\r\n return res;\r\n };\r\n\r\n\r\n/**\r\n * Passes every element of an array into a function and accumulates the result.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\r\n *\r\n * For example:\r\n * var a = [1, 2, 3, 4];\r\n * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);\r\n * returns 10\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\r\n * every element. This function\r\n * takes 4 arguments (the function's previous result or the initial value,\r\n * the value of the current array element, the current array index, and the\r\n * array itself)\r\n * function(previousValue, currentValue, index, array).\r\n * @param {?} val The initial value to pass into the function on the first call.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {R} Result of evaluating f repeatedly across the values of the array.\r\n * @template T,S,R\r\n */\r\ngoog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\r\n function(arr, f, val, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n if (opt_obj) {\r\n f = goog.bind(f, opt_obj);\r\n }\r\n return Array.prototype.reduce.call(arr, f, val);\r\n } :\r\n function(arr, f, val, opt_obj) {\r\n var rval = val;\r\n goog.array.forEach(arr, function(val, index) {\r\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\r\n });\r\n return rval;\r\n };\r\n\r\n\r\n/**\r\n * Passes every element of an array into a function and accumulates the result,\r\n * starting from the last element and working towards the first.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\r\n *\r\n * For example:\r\n * var a = ['a', 'b', 'c'];\r\n * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\r\n * returns 'cba'\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\r\n * every element. This function\r\n * takes 4 arguments (the function's previous result or the initial value,\r\n * the value of the current array element, the current array index, and the\r\n * array itself)\r\n * function(previousValue, currentValue, index, array).\r\n * @param {?} val The initial value to pass into the function on the first call.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {R} Object returned as a result of evaluating f repeatedly across the\r\n * values of the array.\r\n * @template T,S,R\r\n */\r\ngoog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\r\n function(arr, f, val, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n goog.asserts.assert(f != null);\r\n if (opt_obj) {\r\n f = goog.bind(f, opt_obj);\r\n }\r\n return Array.prototype.reduceRight.call(arr, f, val);\r\n } :\r\n function(arr, f, val, opt_obj) {\r\n var rval = val;\r\n goog.array.forEachRight(arr, function(val, index) {\r\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\r\n });\r\n return rval;\r\n };\r\n\r\n\r\n/**\r\n * Calls f for each element of an array. If any call returns true, some()\r\n * returns true (without checking the remaining elements). If all calls\r\n * return false, some() returns false.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\r\n * for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a boolean.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {boolean} true if any element passes the test.\r\n * @template T,S\r\n */\r\ngoog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.some.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n\r\n\r\n/**\r\n * Call f for each element of an array. If all calls return true, every()\r\n * returns true. If any call returns false, every() returns false and\r\n * does not continue to check the remaining elements.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\r\n * for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a boolean.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {boolean} false if any element fails the test.\r\n * @template T,S\r\n */\r\ngoog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.every.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n\r\n\r\n/**\r\n * Counts the array elements that fulfill the predicate, i.e. for which the\r\n * callback function returns true. Skips holes in the array.\r\n *\r\n * @param {!IArrayLike<T>|string} arr Array or array like object\r\n * over which to iterate.\r\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\r\n * every element. Takes 3 arguments (the element, the index and the array).\r\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\r\n * @return {number} The number of the matching elements.\r\n * @template T,S\r\n */\r\ngoog.array.count = function(arr, f, opt_obj) {\r\n var count = 0;\r\n goog.array.forEach(arr, function(element, index, arr) {\r\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\r\n ++count;\r\n }\r\n }, opt_obj);\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Search an array for the first element that satisfies a given condition and\r\n * return that element.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {T|null} The first array element that passes the test, or null if no\r\n * element is found.\r\n * @template T,S\r\n */\r\ngoog.array.find = function(arr, f, opt_obj) {\r\n var i = goog.array.findIndex(arr, f, opt_obj);\r\n return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];\r\n};\r\n\r\n\r\n/**\r\n * Search an array for the first element that satisfies a given condition and\r\n * return its index.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\r\n * every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {number} The index of the first array element that passes the test,\r\n * or -1 if no element is found.\r\n * @template T,S\r\n */\r\ngoog.array.findIndex = function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n};\r\n\r\n\r\n/**\r\n * Search an array (in reverse order) for the last element that satisfies a\r\n * given condition and return that element.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {T|null} The last array element that passes the test, or null if no\r\n * element is found.\r\n * @template T,S\r\n */\r\ngoog.array.findRight = function(arr, f, opt_obj) {\r\n var i = goog.array.findIndexRight(arr, f, opt_obj);\r\n return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];\r\n};\r\n\r\n\r\n/**\r\n * Search an array (in reverse order) for the last element that satisfies a\r\n * given condition and return its index.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {number} The index of the last array element that passes the test,\r\n * or -1 if no element is found.\r\n * @template T,S\r\n */\r\ngoog.array.findIndexRight = function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = l - 1; i >= 0; i--) {\r\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n};\r\n\r\n\r\n/**\r\n * Whether the array contains the given object.\r\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\r\n * element.\r\n * @param {*} obj The object for which to test.\r\n * @return {boolean} true if obj is present.\r\n */\r\ngoog.array.contains = function(arr, obj) {\r\n return goog.array.indexOf(arr, obj) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * Whether the array is empty.\r\n * @param {IArrayLike<?>|string} arr The array to test.\r\n * @return {boolean} true if empty.\r\n */\r\ngoog.array.isEmpty = function(arr) {\r\n return arr.length == 0;\r\n};\r\n\r\n\r\n/**\r\n * Clears the array.\r\n * @param {IArrayLike<?>} arr Array or array like object to clear.\r\n */\r\ngoog.array.clear = function(arr) {\r\n // For non real arrays we don't have the magic length so we delete the\r\n // indices.\r\n if (!goog.isArray(arr)) {\r\n for (var i = arr.length - 1; i >= 0; i--) {\r\n delete arr[i];\r\n }\r\n }\r\n arr.length = 0;\r\n};\r\n\r\n\r\n/**\r\n * Pushes an item into an array, if it's not already in the array.\r\n * @param {Array<T>} arr Array into which to insert the item.\r\n * @param {T} obj Value to add.\r\n * @template T\r\n */\r\ngoog.array.insert = function(arr, obj) {\r\n if (!goog.array.contains(arr, obj)) {\r\n arr.push(obj);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Inserts an object at the given index of the array.\r\n * @param {IArrayLike<?>} arr The array to modify.\r\n * @param {*} obj The object to insert.\r\n * @param {number=} opt_i The index at which to insert the object. If omitted,\r\n * treated as 0. A negative index is counted from the end of the array.\r\n */\r\ngoog.array.insertAt = function(arr, obj, opt_i) {\r\n goog.array.splice(arr, opt_i, 0, obj);\r\n};\r\n\r\n\r\n/**\r\n * Inserts at the given index of the array, all elements of another array.\r\n * @param {IArrayLike<?>} arr The array to modify.\r\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\r\n * @param {number=} opt_i The index at which to insert the object. If omitted,\r\n * treated as 0. A negative index is counted from the end of the array.\r\n */\r\ngoog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {\r\n goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);\r\n};\r\n\r\n\r\n/**\r\n * Inserts an object into an array before a specified object.\r\n * @param {Array<T>} arr The array to modify.\r\n * @param {T} obj The object to insert.\r\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\r\n * is omitted or not found, obj is inserted at the end of the array.\r\n * @template T\r\n */\r\ngoog.array.insertBefore = function(arr, obj, opt_obj2) {\r\n var i;\r\n if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {\r\n arr.push(obj);\r\n } else {\r\n goog.array.insertAt(arr, obj, i);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes the first occurrence of a particular value from an array.\r\n * @param {IArrayLike<T>} arr Array from which to remove\r\n * value.\r\n * @param {T} obj Object to remove.\r\n * @return {boolean} True if an element was removed.\r\n * @template T\r\n */\r\ngoog.array.remove = function(arr, obj) {\r\n var i = goog.array.indexOf(arr, obj);\r\n var rv;\r\n if ((rv = i >= 0)) {\r\n goog.array.removeAt(arr, i);\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Removes the last occurrence of a particular value from an array.\r\n * @param {!IArrayLike<T>} arr Array from which to remove value.\r\n * @param {T} obj Object to remove.\r\n * @return {boolean} True if an element was removed.\r\n * @template T\r\n */\r\ngoog.array.removeLast = function(arr, obj) {\r\n var i = goog.array.lastIndexOf(arr, obj);\r\n if (i >= 0) {\r\n goog.array.removeAt(arr, i);\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes from an array the element at index i\r\n * @param {IArrayLike<?>} arr Array or array like object from which to\r\n * remove value.\r\n * @param {number} i The index to remove.\r\n * @return {boolean} True if an element was removed.\r\n */\r\ngoog.array.removeAt = function(arr, i) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n // use generic form of splice\r\n // splice returns the removed items and if successful the length of that\r\n // will be 1\r\n return Array.prototype.splice.call(arr, i, 1).length == 1;\r\n};\r\n\r\n\r\n/**\r\n * Removes the first value that satisfies the given condition.\r\n * @param {IArrayLike<T>} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {boolean} True if an element was removed.\r\n * @template T,S\r\n */\r\ngoog.array.removeIf = function(arr, f, opt_obj) {\r\n var i = goog.array.findIndex(arr, f, opt_obj);\r\n if (i >= 0) {\r\n goog.array.removeAt(arr, i);\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes all values that satisfy the given condition.\r\n * @param {IArrayLike<T>} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {number} The number of items removed\r\n * @template T,S\r\n */\r\ngoog.array.removeAllIf = function(arr, f, opt_obj) {\r\n var removedCount = 0;\r\n goog.array.forEachRight(arr, function(val, index) {\r\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\r\n if (goog.array.removeAt(arr, index)) {\r\n removedCount++;\r\n }\r\n }\r\n });\r\n return removedCount;\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array that is the result of joining the arguments. If arrays\r\n * are passed then their items are added, however, if non-arrays are passed they\r\n * will be added to the return array as is.\r\n *\r\n * Note that ArrayLike objects will be added as is, rather than having their\r\n * items added.\r\n *\r\n * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\r\n * goog.array.concat(0, [1, 2]) -> [0, 1, 2]\r\n * goog.array.concat([1, 2], null) -> [1, 2, null]\r\n *\r\n * There is bug in all current versions of IE (6, 7 and 8) where arrays created\r\n * in an iframe become corrupted soon (not immediately) after the iframe is\r\n * destroyed. This is common if loading data via goog.net.IframeIo, for example.\r\n * This corruption only affects the concat method which will start throwing\r\n * Catastrophic Errors (#-2147418113).\r\n *\r\n * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.\r\n *\r\n * Internally goog.array should use this, so that all methods will continue to\r\n * work on these broken array objects.\r\n *\r\n * @param {...*} var_args Items to concatenate. Arrays will have each item\r\n * added, while primitives and objects will be added as is.\r\n * @return {!Array<?>} The new resultant array.\r\n */\r\ngoog.array.concat = function(var_args) {\r\n return Array.prototype.concat.apply([], arguments);\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array that contains the contents of all the arrays passed.\r\n * @param {...!Array<T>} var_args\r\n * @return {!Array<T>}\r\n * @template T\r\n */\r\ngoog.array.join = function(var_args) {\r\n return Array.prototype.concat.apply([], arguments);\r\n};\r\n\r\n\r\n/**\r\n * Converts an object to an array.\r\n * @param {IArrayLike<T>|string} object The object to convert to an\r\n * array.\r\n * @return {!Array<T>} The object converted into an array. If object has a\r\n * length property, every property indexed with a non-negative number\r\n * less than length will be included in the result. If object does not\r\n * have a length property, an empty array will be returned.\r\n * @template T\r\n */\r\ngoog.array.toArray = function(object) {\r\n var length = object.length;\r\n\r\n // If length is not a number the following is false. This case is kept for\r\n // backwards compatibility since there are callers that pass objects that are\r\n // not array like.\r\n if (length > 0) {\r\n var rv = new Array(length);\r\n for (var i = 0; i < length; i++) {\r\n rv[i] = object[i];\r\n }\r\n return rv;\r\n }\r\n return [];\r\n};\r\n\r\n\r\n/**\r\n * Does a shallow copy of an array.\r\n * @param {IArrayLike<T>|string} arr Array or array-like object to\r\n * clone.\r\n * @return {!Array<T>} Clone of the input array.\r\n * @template T\r\n */\r\ngoog.array.clone = goog.array.toArray;\r\n\r\n\r\n/**\r\n * Extends an array with another array, element, or \"array like\" object.\r\n * This function operates 'in-place', it does not create a new Array.\r\n *\r\n * Example:\r\n * var a = [];\r\n * goog.array.extend(a, [0, 1]);\r\n * a; // [0, 1]\r\n * goog.array.extend(a, 2);\r\n * a; // [0, 1, 2]\r\n *\r\n * @param {Array<VALUE>} arr1 The array to modify.\r\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\r\n * elements to add to arr1.\r\n * @template VALUE\r\n */\r\ngoog.array.extend = function(arr1, var_args) {\r\n for (var i = 1; i < arguments.length; i++) {\r\n var arr2 = arguments[i];\r\n if (goog.isArrayLike(arr2)) {\r\n var len1 = arr1.length || 0;\r\n var len2 = arr2.length || 0;\r\n arr1.length = len1 + len2;\r\n for (var j = 0; j < len2; j++) {\r\n arr1[len1 + j] = arr2[j];\r\n }\r\n } else {\r\n arr1.push(arr2);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds or removes elements from an array. This is a generic version of Array\r\n * splice. This means that it might work on other objects similar to arrays,\r\n * such as the arguments object.\r\n *\r\n * @param {IArrayLike<T>} arr The array to modify.\r\n * @param {number|undefined} index The index at which to start changing the\r\n * array. If not defined, treated as 0.\r\n * @param {number} howMany How many elements to remove (0 means no removal. A\r\n * value below 0 is treated as zero and so is any other non number. Numbers\r\n * are floored).\r\n * @param {...T} var_args Optional, additional elements to insert into the\r\n * array.\r\n * @return {!Array<T>} the removed elements.\r\n * @template T\r\n */\r\ngoog.array.splice = function(arr, index, howMany, var_args) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1));\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array from a segment of an array. This is a generic version of\r\n * Array slice. This means that it might work on other objects similar to\r\n * arrays, such as the arguments object.\r\n *\r\n * @param {IArrayLike<T>|string} arr The array from\r\n * which to copy a segment.\r\n * @param {number} start The index of the first element to copy.\r\n * @param {number=} opt_end The index after the last element to copy.\r\n * @return {!Array<T>} A new array containing the specified segment of the\r\n * original array.\r\n * @template T\r\n */\r\ngoog.array.slice = function(arr, start, opt_end) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n // passing 1 arg to slice is not the same as passing 2 where the second is\r\n // null or undefined (in that case the second argument is treated as 0).\r\n // we could use slice on the arguments object and then use apply instead of\r\n // testing the length\r\n if (arguments.length <= 2) {\r\n return Array.prototype.slice.call(arr, start);\r\n } else {\r\n return Array.prototype.slice.call(arr, start, opt_end);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes all duplicates from an array (retaining only the first\r\n * occurrence of each array element). This function modifies the\r\n * array in place and doesn't change the order of the non-duplicate items.\r\n *\r\n * For objects, duplicates are identified as having the same unique ID as\r\n * defined by {@link goog.getUid}.\r\n *\r\n * Alternatively you can specify a custom hash function that returns a unique\r\n * value for each item in the array it should consider unique.\r\n *\r\n * Runtime: N,\r\n * Worstcase space: 2N (no dupes)\r\n *\r\n * @param {IArrayLike<T>} arr The array from which to remove\r\n * duplicates.\r\n * @param {Array=} opt_rv An optional array in which to return the results,\r\n * instead of performing the removal inplace. If specified, the original\r\n * array will remain unchanged.\r\n * @param {function(T):string=} opt_hashFn An optional function to use to\r\n * apply to every item in the array. This function should return a unique\r\n * value for each item in the array it should consider unique.\r\n * @template T\r\n */\r\ngoog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {\r\n var returnArray = opt_rv || arr;\r\n var defaultHashFn = function(item) {\r\n // Prefix each type with a single character representing the type to\r\n // prevent conflicting keys (e.g. true and 'true').\r\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\r\n (typeof item).charAt(0) + item;\r\n };\r\n var hashFn = opt_hashFn || defaultHashFn;\r\n\r\n var seen = {}, cursorInsert = 0, cursorRead = 0;\r\n while (cursorRead < arr.length) {\r\n var current = arr[cursorRead++];\r\n var key = hashFn(current);\r\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\r\n seen[key] = true;\r\n returnArray[cursorInsert++] = current;\r\n }\r\n }\r\n returnArray.length = cursorInsert;\r\n};\r\n\r\n\r\n/**\r\n * Searches the specified array for the specified target using the binary\r\n * search algorithm. If no opt_compareFn is specified, elements are compared\r\n * using <code>goog.array.defaultCompare</code>, which compares the elements\r\n * using the built in < and > operators. This will produce the expected\r\n * behavior for homogeneous arrays of String(s) and Number(s). The array\r\n * specified <b>must</b> be sorted in ascending order (as defined by the\r\n * comparison function). If the array is not sorted, results are undefined.\r\n * If the array contains multiple instances of the specified target value, any\r\n * of these instances may be found.\r\n *\r\n * Runtime: O(log n)\r\n *\r\n * @param {IArrayLike<VALUE>} arr The array to be searched.\r\n * @param {TARGET} target The sought value.\r\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is ordered. Should take 2 arguments to\r\n * compare, the target value and an element from your array, and return a\r\n * negative number, zero, or a positive number depending on whether the\r\n * first argument is less than, equal to, or greater than the second.\r\n * @return {number} Lowest index of the target value if found, otherwise\r\n * (-(insertion point) - 1). The insertion point is where the value should\r\n * be inserted into arr to preserve the sorted property. Return value >= 0\r\n * iff target is found.\r\n * @template TARGET, VALUE\r\n */\r\ngoog.array.binarySearch = function(arr, target, opt_compareFn) {\r\n return goog.array.binarySearch_(\r\n arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,\r\n target);\r\n};\r\n\r\n\r\n/**\r\n * Selects an index in the specified array using the binary search algorithm.\r\n * The evaluator receives an element and determines whether the desired index\r\n * is before, at, or after it. The evaluator must be consistent (formally,\r\n * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)\r\n * must be monotonically non-increasing).\r\n *\r\n * Runtime: O(log n)\r\n *\r\n * @param {IArrayLike<VALUE>} arr The array to be searched.\r\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\r\n * Evaluator function that receives 3 arguments (the element, the index and\r\n * the array). Should return a negative number, zero, or a positive number\r\n * depending on whether the desired index is before, at, or after the\r\n * element passed to it.\r\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\r\n * within evaluator.\r\n * @return {number} Index of the leftmost element matched by the evaluator, if\r\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\r\n * the index of the first element for which the evaluator returns negative,\r\n * or arr.length if no such element exists. The return value is non-negative\r\n * iff a match is found.\r\n * @template THIS, VALUE\r\n */\r\ngoog.array.binarySelect = function(arr, evaluator, opt_obj) {\r\n return goog.array.binarySearch_(\r\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\r\n opt_obj);\r\n};\r\n\r\n\r\n/**\r\n * Implementation of a binary search algorithm which knows how to use both\r\n * comparison functions and evaluators. If an evaluator is provided, will call\r\n * the evaluator with the given optional data object, conforming to the\r\n * interface defined in binarySelect. Otherwise, if a comparison function is\r\n * provided, will call the comparison function against the given data object.\r\n *\r\n * This implementation purposefully does not use goog.bind or goog.partial for\r\n * performance reasons.\r\n *\r\n * Runtime: O(log n)\r\n *\r\n * @param {IArrayLike<?>} arr The array to be searched.\r\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\r\n * Either an evaluator or a comparison function, as defined by binarySearch\r\n * and binarySelect above.\r\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\r\n * comparison function.\r\n * @param {?=} opt_target If the function is a comparison function, then\r\n * this is the target to binary search for.\r\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\r\n * optional this object for the evaluator.\r\n * @return {number} Lowest index of the target value if found, otherwise\r\n * (-(insertion point) - 1). The insertion point is where the value should\r\n * be inserted into arr to preserve the sorted property. Return value >= 0\r\n * iff target is found.\r\n * @private\r\n */\r\ngoog.array.binarySearch_ = function(\r\n arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\r\n var left = 0; // inclusive\r\n var right = arr.length; // exclusive\r\n var found;\r\n while (left < right) {\r\n var middle = (left + right) >> 1;\r\n var compareResult;\r\n if (isEvaluator) {\r\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\r\n } else {\r\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\r\n // for the type of binarySearch_, which the type system can't express yet.\r\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\r\n opt_target, arr[middle]);\r\n }\r\n if (compareResult > 0) {\r\n left = middle + 1;\r\n } else {\r\n right = middle;\r\n // We are looking for the lowest index so we can't return immediately.\r\n found = !compareResult;\r\n }\r\n }\r\n // left is the index if found, or the insertion point otherwise.\r\n // ~left is a shorthand for -left - 1.\r\n return found ? left : ~left;\r\n};\r\n\r\n\r\n/**\r\n * Sorts the specified array into ascending order. If no opt_compareFn is\r\n * specified, elements are compared using\r\n * <code>goog.array.defaultCompare</code>, which compares the elements using\r\n * the built in < and > operators. This will produce the expected behavior\r\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\r\n * but will give unpredictable results for heterogeneous lists of strings and\r\n * numbers with different numbers of digits.\r\n *\r\n * This sort is not guaranteed to be stable.\r\n *\r\n * Runtime: Same as <code>Array.prototype.sort</code>\r\n *\r\n * @param {Array<T>} arr The array to be sorted.\r\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\r\n * function by which the\r\n * array is to be ordered. Should take 2 arguments to compare, and return a\r\n * negative number, zero, or a positive number depending on whether the\r\n * first argument is less than, equal to, or greater than the second.\r\n * @template T\r\n */\r\ngoog.array.sort = function(arr, opt_compareFn) {\r\n // TODO(arv): Update type annotation since null is not accepted.\r\n arr.sort(opt_compareFn || goog.array.defaultCompare);\r\n};\r\n\r\n\r\n/**\r\n * Sorts the specified array into ascending order in a stable way. If no\r\n * opt_compareFn is specified, elements are compared using\r\n * <code>goog.array.defaultCompare</code>, which compares the elements using\r\n * the built in < and > operators. This will produce the expected behavior\r\n * for homogeneous arrays of String(s) and Number(s).\r\n *\r\n * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional\r\n * O(n) overhead of copying the array twice.\r\n *\r\n * @param {Array<T>} arr The array to be sorted.\r\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\r\n * by which the array is to be ordered. Should take 2 arguments to compare,\r\n * and return a negative number, zero, or a positive number depending on\r\n * whether the first argument is less than, equal to, or greater than the\r\n * second.\r\n * @template T\r\n */\r\ngoog.array.stableSort = function(arr, opt_compareFn) {\r\n var compArr = new Array(arr.length);\r\n for (var i = 0; i < arr.length; i++) {\r\n compArr[i] = {index: i, value: arr[i]};\r\n }\r\n var valueCompareFn = opt_compareFn || goog.array.defaultCompare;\r\n function stableCompareFn(obj1, obj2) {\r\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\r\n }\r\n goog.array.sort(compArr, stableCompareFn);\r\n for (var i = 0; i < arr.length; i++) {\r\n arr[i] = compArr[i].value;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sort the specified array into ascending order based on item keys\r\n * returned by the specified key function.\r\n * If no opt_compareFn is specified, the keys are compared in ascending order\r\n * using <code>goog.array.defaultCompare</code>.\r\n *\r\n * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>\r\n * and f(n) is runtime of the key function.\r\n *\r\n * @param {Array<T>} arr The array to be sorted.\r\n * @param {function(T): K} keyFn Function taking array element and returning\r\n * a key used for sorting this element.\r\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\r\n * by which the keys are to be ordered. Should take 2 arguments to compare,\r\n * and return a negative number, zero, or a positive number depending on\r\n * whether the first argument is less than, equal to, or greater than the\r\n * second.\r\n * @template T,K\r\n */\r\ngoog.array.sortByKey = function(arr, keyFn, opt_compareFn) {\r\n var keyCompareFn = opt_compareFn || goog.array.defaultCompare;\r\n goog.array.sort(\r\n arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); });\r\n};\r\n\r\n\r\n/**\r\n * Sorts an array of objects by the specified object key and compare\r\n * function. If no compare function is provided, the key values are\r\n * compared in ascending order using <code>goog.array.defaultCompare</code>.\r\n * This won't work for keys that get renamed by the compiler. So use\r\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\r\n * @param {Array<Object>} arr An array of objects to sort.\r\n * @param {string} key The object key to sort by.\r\n * @param {Function=} opt_compareFn The function to use to compare key\r\n * values.\r\n */\r\ngoog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {\r\n goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn);\r\n};\r\n\r\n\r\n/**\r\n * Tells if the array is sorted.\r\n * @param {!IArrayLike<T>} arr The array.\r\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\r\n * array elements.\r\n * Should take 2 arguments to compare, and return a negative number, zero,\r\n * or a positive number depending on whether the first argument is less\r\n * than, equal to, or greater than the second.\r\n * @param {boolean=} opt_strict If true no equal elements are allowed.\r\n * @return {boolean} Whether the array is sorted.\r\n * @template T\r\n */\r\ngoog.array.isSorted = function(arr, opt_compareFn, opt_strict) {\r\n var compare = opt_compareFn || goog.array.defaultCompare;\r\n for (var i = 1; i < arr.length; i++) {\r\n var compareResult = compare(arr[i - 1], arr[i]);\r\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Compares two arrays for equality. Two arrays are considered equal if they\r\n * have the same length and their corresponding elements are equal according to\r\n * the comparison function.\r\n *\r\n * @param {IArrayLike<?>} arr1 The first array to compare.\r\n * @param {IArrayLike<?>} arr2 The second array to compare.\r\n * @param {Function=} opt_equalsFn Optional comparison function.\r\n * Should take 2 arguments to compare, and return true if the arguments\r\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\r\n * compares the elements using the built-in '===' operator.\r\n * @return {boolean} Whether the two arrays are equal.\r\n */\r\ngoog.array.equals = function(arr1, arr2, opt_equalsFn) {\r\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\r\n arr1.length != arr2.length) {\r\n return false;\r\n }\r\n var l = arr1.length;\r\n var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;\r\n for (var i = 0; i < l; i++) {\r\n if (!equalsFn(arr1[i], arr2[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * 3-way array compare function.\r\n * @param {!IArrayLike<VALUE>} arr1 The first array to\r\n * compare.\r\n * @param {!IArrayLike<VALUE>} arr2 The second array to\r\n * compare.\r\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is to be ordered. Should take 2 arguments to\r\n * compare, and return a negative number, zero, or a positive number\r\n * depending on whether the first argument is less than, equal to, or\r\n * greater than the second.\r\n * @return {number} Negative number, zero, or a positive number depending on\r\n * whether the first argument is less than, equal to, or greater than the\r\n * second.\r\n * @template VALUE\r\n */\r\ngoog.array.compare3 = function(arr1, arr2, opt_compareFn) {\r\n var compare = opt_compareFn || goog.array.defaultCompare;\r\n var l = Math.min(arr1.length, arr2.length);\r\n for (var i = 0; i < l; i++) {\r\n var result = compare(arr1[i], arr2[i]);\r\n if (result != 0) {\r\n return result;\r\n }\r\n }\r\n return goog.array.defaultCompare(arr1.length, arr2.length);\r\n};\r\n\r\n\r\n/**\r\n * Compares its two arguments for order, using the built in < and >\r\n * operators.\r\n * @param {VALUE} a The first object to be compared.\r\n * @param {VALUE} b The second object to be compared.\r\n * @return {number} A negative number, zero, or a positive number as the first\r\n * argument is less than, equal to, or greater than the second,\r\n * respectively.\r\n * @template VALUE\r\n */\r\ngoog.array.defaultCompare = function(a, b) {\r\n return a > b ? 1 : a < b ? -1 : 0;\r\n};\r\n\r\n\r\n/**\r\n * Compares its two arguments for inverse order, using the built in < and >\r\n * operators.\r\n * @param {VALUE} a The first object to be compared.\r\n * @param {VALUE} b The second object to be compared.\r\n * @return {number} A negative number, zero, or a positive number as the first\r\n * argument is greater than, equal to, or less than the second,\r\n * respectively.\r\n * @template VALUE\r\n */\r\ngoog.array.inverseDefaultCompare = function(a, b) {\r\n return -goog.array.defaultCompare(a, b);\r\n};\r\n\r\n\r\n/**\r\n * Compares its two arguments for equality, using the built in === operator.\r\n * @param {*} a The first object to compare.\r\n * @param {*} b The second object to compare.\r\n * @return {boolean} True if the two arguments are equal, false otherwise.\r\n */\r\ngoog.array.defaultCompareEquality = function(a, b) {\r\n return a === b;\r\n};\r\n\r\n\r\n/**\r\n * Inserts a value into a sorted array. The array is not modified if the\r\n * value is already present.\r\n * @param {IArrayLike<VALUE>} array The array to modify.\r\n * @param {VALUE} value The object to insert.\r\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is ordered. Should take 2 arguments to\r\n * compare, and return a negative number, zero, or a positive number\r\n * depending on whether the first argument is less than, equal to, or\r\n * greater than the second.\r\n * @return {boolean} True if an element was inserted.\r\n * @template VALUE\r\n */\r\ngoog.array.binaryInsert = function(array, value, opt_compareFn) {\r\n var index = goog.array.binarySearch(array, value, opt_compareFn);\r\n if (index < 0) {\r\n goog.array.insertAt(array, value, -(index + 1));\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes a value from a sorted array.\r\n * @param {!IArrayLike<VALUE>} array The array to modify.\r\n * @param {VALUE} value The object to remove.\r\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is ordered. Should take 2 arguments to\r\n * compare, and return a negative number, zero, or a positive number\r\n * depending on whether the first argument is less than, equal to, or\r\n * greater than the second.\r\n * @return {boolean} True if an element was removed.\r\n * @template VALUE\r\n */\r\ngoog.array.binaryRemove = function(array, value, opt_compareFn) {\r\n var index = goog.array.binarySearch(array, value, opt_compareFn);\r\n return (index >= 0) ? goog.array.removeAt(array, index) : false;\r\n};\r\n\r\n\r\n/**\r\n * Splits an array into disjoint buckets according to a splitting function.\r\n * @param {IArrayLike<T>} array The array.\r\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\r\n * call for every element. This takes 3 arguments (the element, the index\r\n * and the array) and must return a valid object key (a string, number,\r\n * etc), or undefined, if that object should not be placed in a bucket.\r\n * @param {S=} opt_obj The object to be used as the value of 'this' within\r\n * sorter.\r\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\r\n * return values of sorter, and values being arrays containing the items for\r\n * which the splitter returned that key.\r\n * @template T,S\r\n */\r\ngoog.array.bucket = function(array, sorter, opt_obj) {\r\n var buckets = {};\r\n\r\n for (var i = 0; i < array.length; i++) {\r\n var value = array[i];\r\n var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\r\n if (goog.isDef(key)) {\r\n // Push the value to the right bucket, creating it if necessary.\r\n var bucket = buckets[key] || (buckets[key] = []);\r\n bucket.push(value);\r\n }\r\n }\r\n\r\n return buckets;\r\n};\r\n\r\n\r\n/**\r\n * Creates a new object built from the provided array and the key-generation\r\n * function.\r\n * @param {IArrayLike<T>} arr Array or array like object over\r\n * which to iterate whose elements will be the values in the new object.\r\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\r\n * call for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a string that will be used as the\r\n * key for the element in the new object. If the function returns the same\r\n * key for more than one element, the value for that key is\r\n * implementation-defined.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within keyFunc.\r\n * @return {!Object<T>} The new object.\r\n * @template T,S\r\n */\r\ngoog.array.toObject = function(arr, keyFunc, opt_obj) {\r\n var ret = {};\r\n goog.array.forEach(arr, function(element, index) {\r\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\r\n element;\r\n });\r\n return ret;\r\n};\r\n\r\n\r\n/**\r\n * Creates a range of numbers in an arithmetic progression.\r\n *\r\n * Range takes 1, 2, or 3 arguments:\r\n * <pre>\r\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\r\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\r\n * range(-2, -5, -1) produces [-2, -3, -4]\r\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\r\n * </pre>\r\n *\r\n * @param {number} startOrEnd The starting value of the range if an end argument\r\n * is provided. Otherwise, the start value is 0, and this is the end value.\r\n * @param {number=} opt_end The optional end value of the range.\r\n * @param {number=} opt_step The step size between range values. Defaults to 1\r\n * if opt_step is undefined or 0.\r\n * @return {!Array<number>} An array of numbers for the requested range. May be\r\n * an empty array if adding the step would not converge toward the end\r\n * value.\r\n */\r\ngoog.array.range = function(startOrEnd, opt_end, opt_step) {\r\n var array = [];\r\n var start = 0;\r\n var end = startOrEnd;\r\n var step = opt_step || 1;\r\n if (opt_end !== undefined) {\r\n start = startOrEnd;\r\n end = opt_end;\r\n }\r\n\r\n if (step * (end - start) < 0) {\r\n // Sign mismatch: start + step will never reach the end value.\r\n return [];\r\n }\r\n\r\n if (step > 0) {\r\n for (var i = start; i < end; i += step) {\r\n array.push(i);\r\n }\r\n } else {\r\n for (var i = start; i > end; i += step) {\r\n array.push(i);\r\n }\r\n }\r\n return array;\r\n};\r\n\r\n\r\n/**\r\n * Returns an array consisting of the given value repeated N times.\r\n *\r\n * @param {VALUE} value The value to repeat.\r\n * @param {number} n The repeat count.\r\n * @return {!Array<VALUE>} An array with the repeated value.\r\n * @template VALUE\r\n */\r\ngoog.array.repeat = function(value, n) {\r\n var array = [];\r\n for (var i = 0; i < n; i++) {\r\n array[i] = value;\r\n }\r\n return array;\r\n};\r\n\r\n\r\n/**\r\n * Returns an array consisting of every argument with all arrays\r\n * expanded in-place recursively.\r\n *\r\n * @param {...*} var_args The values to flatten.\r\n * @return {!Array<?>} An array containing the flattened values.\r\n */\r\ngoog.array.flatten = function(var_args) {\r\n var CHUNK_SIZE = 8192;\r\n\r\n var result = [];\r\n for (var i = 0; i < arguments.length; i++) {\r\n var element = arguments[i];\r\n if (goog.isArray(element)) {\r\n for (var c = 0; c < element.length; c += CHUNK_SIZE) {\r\n var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);\r\n var recurseResult = goog.array.flatten.apply(null, chunk);\r\n for (var r = 0; r < recurseResult.length; r++) {\r\n result.push(recurseResult[r]);\r\n }\r\n }\r\n } else {\r\n result.push(element);\r\n }\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Rotates an array in-place. After calling this method, the element at\r\n * index i will be the element previously at index (i - n) %\r\n * array.length, for all values of i between 0 and array.length - 1,\r\n * inclusive.\r\n *\r\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\r\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\r\n *\r\n * @param {!Array<T>} array The array to rotate.\r\n * @param {number} n The amount to rotate.\r\n * @return {!Array<T>} The array.\r\n * @template T\r\n */\r\ngoog.array.rotate = function(array, n) {\r\n goog.asserts.assert(array.length != null);\r\n\r\n if (array.length) {\r\n n %= array.length;\r\n if (n > 0) {\r\n Array.prototype.unshift.apply(array, array.splice(-n, n));\r\n } else if (n < 0) {\r\n Array.prototype.push.apply(array, array.splice(0, -n));\r\n }\r\n }\r\n return array;\r\n};\r\n\r\n\r\n/**\r\n * Moves one item of an array to a new position keeping the order of the rest\r\n * of the items. Example use case: keeping a list of JavaScript objects\r\n * synchronized with the corresponding list of DOM elements after one of the\r\n * elements has been dragged to a new position.\r\n * @param {!IArrayLike<?>} arr The array to modify.\r\n * @param {number} fromIndex Index of the item to move between 0 and\r\n * {@code arr.length - 1}.\r\n * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.\r\n */\r\ngoog.array.moveItem = function(arr, fromIndex, toIndex) {\r\n goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\r\n goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);\r\n // Remove 1 item at fromIndex.\r\n var removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\r\n // Insert the removed item at toIndex.\r\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\r\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\r\n // significantly slower than splice.\r\n};\r\n\r\n\r\n/**\r\n * Creates a new array for which the element at position i is an array of the\r\n * ith element of the provided arrays. The returned array will only be as long\r\n * as the shortest array provided; additional values are ignored. For example,\r\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\r\n *\r\n * This is similar to the zip() function in Python. See {@link\r\n * http://docs.python.org/library/functions.html#zip}\r\n *\r\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\r\n * @return {!Array<!Array<?>>} A new array of arrays created from\r\n * provided arrays.\r\n */\r\ngoog.array.zip = function(var_args) {\r\n if (!arguments.length) {\r\n return [];\r\n }\r\n var result = [];\r\n var minLen = arguments[0].length;\r\n for (var i = 1; i < arguments.length; i++) {\r\n if (arguments[i].length < minLen) {\r\n minLen = arguments[i].length;\r\n }\r\n }\r\n for (var i = 0; i < minLen; i++) {\r\n var value = [];\r\n for (var j = 0; j < arguments.length; j++) {\r\n value.push(arguments[j][i]);\r\n }\r\n result.push(value);\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Shuffles the values in the specified array using the Fisher-Yates in-place\r\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\r\n * and so resets the state of that random number generator. Similarly, may reset\r\n * the state of any other specified random number generator.\r\n *\r\n * Runtime: O(n)\r\n *\r\n * @param {!Array<?>} arr The array to be shuffled.\r\n * @param {function():number=} opt_randFn Optional random function to use for\r\n * shuffling.\r\n * Takes no arguments, and returns a random number on the interval [0, 1).\r\n * Defaults to Math.random() using JavaScript's built-in Math library.\r\n */\r\ngoog.array.shuffle = function(arr, opt_randFn) {\r\n var randFn = opt_randFn || Math.random;\r\n\r\n for (var i = arr.length - 1; i > 0; i--) {\r\n // Choose a random array index in [0, i] (inclusive with i).\r\n var j = Math.floor(randFn() * (i + 1));\r\n\r\n var tmp = arr[i];\r\n arr[i] = arr[j];\r\n arr[j] = tmp;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array of elements from arr, based on the indexes of elements\r\n * provided by index_arr. For example, the result of index copying\r\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\r\n *\r\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\r\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\r\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\r\n * @template T\r\n */\r\ngoog.array.copyByIndex = function(arr, index_arr) {\r\n var result = [];\r\n goog.array.forEach(index_arr, function(index) { result.push(arr[index]); });\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Maps each element of the input array into zero or more elements of the output\r\n * array.\r\n *\r\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\r\n * over which to iterate.\r\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\r\n * to call for every element. This function takes 3 arguments (the element,\r\n * the index and the array) and should return an array. The result will be\r\n * used to extend a new array.\r\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\r\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\r\n * returned from f.\r\n * @template THIS, VALUE, RESULT\r\n */\r\ngoog.array.concatMap = function(arr, f, opt_obj) {\r\n return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj));\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview String functions called from Closure packages that couldn't\r\n * depend on each other. Outside Closure, use goog.string function which\r\n * delegate to these.\r\n */\r\n\r\n\r\ngoog.provide('goog.string.internal');\r\n\r\n\r\n/**\r\n * Fast prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the start of `str`.\r\n * @return {boolean} True if `str` begins with `prefix`.\r\n * @see goog.string.startsWith\r\n */\r\ngoog.string.internal.startsWith = function(str, prefix) {\r\n return str.lastIndexOf(prefix, 0) == 0;\r\n};\r\n\r\n\r\n/**\r\n * Fast suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix`.\r\n * @see goog.string.endsWith\r\n */\r\ngoog.string.internal.endsWith = function(str, suffix) {\r\n var l = str.length - suffix.length;\r\n return l >= 0 && str.indexOf(suffix, l) == l;\r\n};\r\n\r\n\r\n/**\r\n * Case-insensitive prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` begins with `prefix` (ignoring\r\n * case).\r\n * @see goog.string.caseInsensitiveStartsWith\r\n */\r\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\r\n return goog.string.internal.caseInsensitiveCompare(\r\n prefix, str.substr(0, prefix.length)) == 0;\r\n};\r\n\r\n\r\n/**\r\n * Case-insensitive suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix` (ignoring\r\n * case).\r\n * @see goog.string.caseInsensitiveEndsWith\r\n */\r\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\r\n return (\r\n goog.string.internal.caseInsensitiveCompare(\r\n suffix, str.substr(str.length - suffix.length, suffix.length)) == 0);\r\n};\r\n\r\n\r\n/**\r\n * Case-insensitive equality checker.\r\n * @param {string} str1 First string to check.\r\n * @param {string} str2 Second string to check.\r\n * @return {boolean} True if `str1` and `str2` are the same string,\r\n * ignoring case.\r\n * @see goog.string.caseInsensitiveEquals\r\n */\r\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\r\n return str1.toLowerCase() == str2.toLowerCase();\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is empty or contains only whitespaces.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty or whitespace only.\r\n * @see goog.string.isEmptyOrWhitespace\r\n */\r\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\r\n // testing length == 0 first is actually slower in all browsers (about the\r\n // same in Opera).\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return /^[\\s\\xa0]*$/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Trims white spaces to the left and right of a string.\r\n * @param {string} str The string to trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.internal.trim =\r\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\r\n return str.trim();\r\n } : function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\r\n // character class (as required by section 7.2 of the ECMAScript spec),\r\n // we explicitly include it in the regexp to enforce consistent\r\n // cross-browser behavior.\r\n // NOTE: We don't use String#replace because it might have side effects\r\n // causing this function to not compile to 0 bytes.\r\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\r\n };\r\n\r\n\r\n/**\r\n * A string comparator that ignores case.\r\n * -1 = str1 less than str2\r\n * 0 = str1 equals str2\r\n * 1 = str1 greater than str2\r\n *\r\n * @param {string} str1 The string to compare.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} The comparator result, as described above.\r\n * @see goog.string.caseInsensitiveCompare\r\n */\r\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\r\n var test1 = String(str1).toLowerCase();\r\n var test2 = String(str2).toLowerCase();\r\n\r\n if (test1 < test2) {\r\n return -1;\r\n } else if (test1 == test2) {\r\n return 0;\r\n } else {\r\n return 1;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Converts \\n to <br>s or <br />s.\r\n * @param {string} str The string in which to convert newlines.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} A copy of `str` with converted newlines.\r\n * @see goog.string.newLineToBr\r\n */\r\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\r\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\r\n};\r\n\r\n\r\n/**\r\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\r\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\r\n * value within double or single quotes.\r\n * @param {string} str string to be escaped.\r\n * @param {boolean=} opt_isLikelyToContainHtmlChars\r\n * @return {string} An escaped copy of `str`.\r\n * @see goog.string.htmlEscape\r\n */\r\ngoog.string.internal.htmlEscape = function(\r\n str, opt_isLikelyToContainHtmlChars) {\r\n if (opt_isLikelyToContainHtmlChars) {\r\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;')\r\n .replace(goog.string.internal.LT_RE_, '&lt;')\r\n .replace(goog.string.internal.GT_RE_, '&gt;')\r\n .replace(goog.string.internal.QUOT_RE_, '&quot;')\r\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;')\r\n .replace(goog.string.internal.NULL_RE_, '&#0;');\r\n return str;\r\n\r\n } else {\r\n // quick test helps in the case when there are no chars to replace, in\r\n // worst case this makes barely a difference to the time taken\r\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\r\n\r\n // str.indexOf is faster than regex.test in this case\r\n if (str.indexOf('&') != -1) {\r\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;');\r\n }\r\n if (str.indexOf('<') != -1) {\r\n str = str.replace(goog.string.internal.LT_RE_, '&lt;');\r\n }\r\n if (str.indexOf('>') != -1) {\r\n str = str.replace(goog.string.internal.GT_RE_, '&gt;');\r\n }\r\n if (str.indexOf('\"') != -1) {\r\n str = str.replace(goog.string.internal.QUOT_RE_, '&quot;');\r\n }\r\n if (str.indexOf('\\'') != -1) {\r\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;');\r\n }\r\n if (str.indexOf('\\x00') != -1) {\r\n str = str.replace(goog.string.internal.NULL_RE_, '&#0;');\r\n }\r\n return str;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Regular expression that matches an ampersand, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.AMP_RE_ = /&/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a less than sign, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.LT_RE_ = /</g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a greater than sign, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.GT_RE_ = />/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a double quote, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.QUOT_RE_ = /\"/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a single quote, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches null character, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.NULL_RE_ = /\\x00/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches any character that needs to be escaped.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\r\n\r\n\r\n/**\r\n * Do escaping of whitespace to preserve spatial formatting. We use character\r\n * entity #160 to make it safer for xml.\r\n * @param {string} str The string in which to escape whitespace.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} An escaped copy of `str`.\r\n * @see goog.string.whitespaceEscape\r\n */\r\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\r\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\r\n return goog.string.internal.newLineToBr(\r\n str.replace(/ /g, ' &#160;'), opt_xml);\r\n};\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n * @see goog.string.contains\r\n */\r\ngoog.string.internal.contains = function(str, subString) {\r\n return str.indexOf(subString) != -1;\r\n};\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring, ignoring case.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n * @see goog.string.caseInsensitiveContains\r\n */\r\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\r\n return goog.string.internal.contains(\r\n str.toLowerCase(), subString.toLowerCase());\r\n};\r\n\r\n\r\n/**\r\n * Compares two version numbers.\r\n *\r\n * @param {string|number} version1 Version of first item.\r\n * @param {string|number} version2 Version of second item.\r\n *\r\n * @return {number} 1 if `version1` is higher.\r\n * 0 if arguments are equal.\r\n * -1 if `version2` is higher.\r\n * @see goog.string.compareVersions\r\n */\r\ngoog.string.internal.compareVersions = function(version1, version2) {\r\n var order = 0;\r\n // Trim leading and trailing whitespace and split the versions into\r\n // subversions.\r\n var v1Subs = goog.string.internal.trim(String(version1)).split('.');\r\n var v2Subs = goog.string.internal.trim(String(version2)).split('.');\r\n var subCount = Math.max(v1Subs.length, v2Subs.length);\r\n\r\n // Iterate over the subversions, as long as they appear to be equivalent.\r\n for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\r\n var v1Sub = v1Subs[subIdx] || '';\r\n var v2Sub = v2Subs[subIdx] || '';\r\n\r\n do {\r\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\r\n // Two different RegExp objects are use to make it clear the code\r\n // is side-effect free\r\n var v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\r\n var v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\r\n // Break if there are no more matches.\r\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\r\n break;\r\n }\r\n\r\n // Parse the numeric part of the subversion. A missing number is\r\n // equivalent to 0.\r\n var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\r\n var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\r\n\r\n // Compare the subversion components. The number has the highest\r\n // precedence. Next, if the numbers are equal, a subversion without any\r\n // qualifier is always higher than a subversion with any qualifier. Next,\r\n // the qualifiers are compared as strings.\r\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\r\n goog.string.internal.compareElements_(\r\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\r\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\r\n // Stop as soon as an inequality is discovered.\r\n\r\n v1Sub = v1Comp[3];\r\n v2Sub = v2Comp[3];\r\n } while (order == 0);\r\n }\r\n\r\n return order;\r\n};\r\n\r\n\r\n/**\r\n * Compares elements of a version number.\r\n *\r\n * @param {string|number|boolean} left An element from a version number.\r\n * @param {string|number|boolean} right An element from a version number.\r\n *\r\n * @return {number} 1 if `left` is higher.\r\n * 0 if arguments are equal.\r\n * -1 if `right` is higher.\r\n * @private\r\n */\r\ngoog.string.internal.compareElements_ = function(left, right) {\r\n if (left < right) {\r\n return -1;\r\n } else if (left > right) {\r\n return 1;\r\n }\r\n return 0;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\r\n * should not be used outside of goog.labs.userAgent.*.\r\n *\r\n * @author nnaze@google.com (Nathan Naze)\r\n */\r\n\r\ngoog.provide('goog.labs.userAgent.util');\r\n\r\ngoog.require('goog.string.internal');\r\n\r\n\r\n/**\r\n * Gets the native userAgent string from navigator if it exists.\r\n * If navigator or navigator.userAgent string is missing, returns an empty\r\n * string.\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.labs.userAgent.util.getNativeUserAgentString_ = function() {\r\n var navigator = goog.labs.userAgent.util.getNavigator_();\r\n if (navigator) {\r\n var userAgent = navigator.userAgent;\r\n if (userAgent) {\r\n return userAgent;\r\n }\r\n }\r\n return '';\r\n};\r\n\r\n\r\n/**\r\n * Getter for the native navigator.\r\n * This is a separate function so it can be stubbed out in testing.\r\n * @return {Navigator}\r\n * @private\r\n */\r\ngoog.labs.userAgent.util.getNavigator_ = function() {\r\n return goog.global.navigator;\r\n};\r\n\r\n\r\n/**\r\n * A possible override for applications which wish to not check\r\n * navigator.userAgent but use a specified value for detection instead.\r\n * @private {string}\r\n */\r\ngoog.labs.userAgent.util.userAgent_ =\r\n goog.labs.userAgent.util.getNativeUserAgentString_();\r\n\r\n\r\n/**\r\n * Applications may override browser detection on the built in\r\n * navigator.userAgent object by setting this string. Set to null to use the\r\n * browser object instead.\r\n * @param {?string=} opt_userAgent The User-Agent override.\r\n */\r\ngoog.labs.userAgent.util.setUserAgent = function(opt_userAgent) {\r\n goog.labs.userAgent.util.userAgent_ =\r\n opt_userAgent || goog.labs.userAgent.util.getNativeUserAgentString_();\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The user agent string.\r\n */\r\ngoog.labs.userAgent.util.getUserAgent = function() {\r\n return goog.labs.userAgent.util.userAgent_;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} str\r\n * @return {boolean} Whether the user agent contains the given string.\r\n */\r\ngoog.labs.userAgent.util.matchUserAgent = function(str) {\r\n var userAgent = goog.labs.userAgent.util.getUserAgent();\r\n return goog.string.internal.contains(userAgent, str);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} str\r\n * @return {boolean} Whether the user agent contains the given string, ignoring\r\n * case.\r\n */\r\ngoog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) {\r\n var userAgent = goog.labs.userAgent.util.getUserAgent();\r\n return goog.string.internal.caseInsensitiveContains(userAgent, str);\r\n};\r\n\r\n\r\n/**\r\n * Parses the user agent into tuples for each section.\r\n * @param {string} userAgent\r\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents\r\n * of the parenthetical.\r\n */\r\ngoog.labs.userAgent.util.extractVersionTuples = function(userAgent) {\r\n // Matches each section of a user agent string.\r\n // Example UA:\r\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\r\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\r\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\r\n\r\n var versionRegExp = new RegExp(\r\n // Key. Note that a key may have a space.\r\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\r\n '(\\\\w[\\\\w ]+)' +\r\n\r\n '/' + // slash\r\n '([^\\\\s]+)' + // version (i.e. '5.0b')\r\n '\\\\s*' + // whitespace\r\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\r\n 'g');\r\n\r\n var data = [];\r\n var match;\r\n\r\n // Iterate and collect the version tuples. Each iteration will be the\r\n // next regex match.\r\n while (match = versionRegExp.exec(userAgent)) {\r\n data.push([\r\n match[1], // key\r\n match[2], // value\r\n // || undefined as this is not undefined in IE7 and IE8\r\n match[3] || undefined // info\r\n ]);\r\n }\r\n\r\n return data;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for manipulating objects/maps/hashes.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\ngoog.provide('goog.object');\r\n\r\n\r\n/**\r\n * Whether two values are not observably distinguishable. This\r\n * correctly detects that 0 is not the same as -0 and two NaNs are\r\n * practically equivalent.\r\n *\r\n * The implementation is as suggested by harmony:egal proposal.\r\n *\r\n * @param {*} v The first value to compare.\r\n * @param {*} v2 The second value to compare.\r\n * @return {boolean} Whether two values are not observably distinguishable.\r\n * @see http://wiki.ecmascript.org/doku.php?id=harmony:egal\r\n */\r\ngoog.object.is = function(v, v2) {\r\n if (v === v2) {\r\n // 0 === -0, but they are not identical.\r\n // We need the cast because the compiler requires that v2 is a\r\n // number (although 1/v2 works with non-number). We cast to ? to\r\n // stop the compiler from type-checking this statement.\r\n return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2);\r\n }\r\n\r\n // NaN is non-reflexive: NaN !== NaN, although they are identical.\r\n return v !== v && v2 !== v2;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash.\r\n *\r\n * @param {Object<K,V>} obj The object over which to iterate.\r\n * @param {function(this:T,V,?,Object<K,V>):?} f The function to call\r\n * for every element. This function takes 3 arguments (the value, the\r\n * key and the object) and the return value is ignored.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @template T,K,V\r\n */\r\ngoog.object.forEach = function(obj, f, opt_obj) {\r\n for (var key in obj) {\r\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash. If that call returns\r\n * true, adds the element to a new object.\r\n *\r\n * @param {Object<K,V>} obj The object over which to iterate.\r\n * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call\r\n * for every element. This\r\n * function takes 3 arguments (the value, the key and the object)\r\n * and should return a boolean. If the return value is true the\r\n * element is added to the result object. If it is false the\r\n * element is not included.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {!Object<K,V>} a new object in which only elements that passed the\r\n * test are present.\r\n * @template T,K,V\r\n */\r\ngoog.object.filter = function(obj, f, opt_obj) {\r\n var res = {};\r\n for (var key in obj) {\r\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\r\n res[key] = obj[key];\r\n }\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * For every element in an object/map/hash calls a function and inserts the\r\n * result into a new object.\r\n *\r\n * @param {Object<K,V>} obj The object over which to iterate.\r\n * @param {function(this:T,V,?,Object<K,V>):R} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the value, the key and the object)\r\n * and should return something. The result will be inserted\r\n * into a new object.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {!Object<K,R>} a new object with the results from f.\r\n * @template T,K,V,R\r\n */\r\ngoog.object.map = function(obj, f, opt_obj) {\r\n var res = {};\r\n for (var key in obj) {\r\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash. If any\r\n * call returns true, returns true (without checking the rest). If\r\n * all calls return false, returns false.\r\n *\r\n * @param {Object<K,V>} obj The object to check.\r\n * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to\r\n * call for every element. This function\r\n * takes 3 arguments (the value, the key and the object) and should\r\n * return a boolean.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {boolean} true if any element passes the test.\r\n * @template T,K,V\r\n */\r\ngoog.object.some = function(obj, f, opt_obj) {\r\n for (var key in obj) {\r\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash. If\r\n * all calls return true, returns true. If any call returns false, returns\r\n * false at this point and does not continue to check the remaining elements.\r\n *\r\n * @param {Object<K,V>} obj The object to check.\r\n * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to\r\n * call for every element. This function\r\n * takes 3 arguments (the value, the key and the object) and should\r\n * return a boolean.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {boolean} false if any element fails the test.\r\n * @template T,K,V\r\n */\r\ngoog.object.every = function(obj, f, opt_obj) {\r\n for (var key in obj) {\r\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of key-value pairs in the object map.\r\n *\r\n * @param {Object} obj The object for which to get the number of key-value\r\n * pairs.\r\n * @return {number} The number of key-value pairs in the object map.\r\n */\r\ngoog.object.getCount = function(obj) {\r\n var rv = 0;\r\n for (var key in obj) {\r\n rv++;\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Returns one key from the object map, if any exists.\r\n * For map literals the returned key will be the first one in most of the\r\n * browsers (a know exception is Konqueror).\r\n *\r\n * @param {Object} obj The object to pick a key from.\r\n * @return {string|undefined} The key or undefined if the object is empty.\r\n */\r\ngoog.object.getAnyKey = function(obj) {\r\n for (var key in obj) {\r\n return key;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns one value from the object map, if any exists.\r\n * For map literals the returned value will be the first one in most of the\r\n * browsers (a know exception is Konqueror).\r\n *\r\n * @param {Object<K,V>} obj The object to pick a value from.\r\n * @return {V|undefined} The value or undefined if the object is empty.\r\n * @template K,V\r\n */\r\ngoog.object.getAnyValue = function(obj) {\r\n for (var key in obj) {\r\n return obj[key];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/hash/map contains the given object as a value.\r\n * An alias for goog.object.containsValue(obj, val).\r\n *\r\n * @param {Object<K,V>} obj The object in which to look for val.\r\n * @param {V} val The object for which to check.\r\n * @return {boolean} true if val is present.\r\n * @template K,V\r\n */\r\ngoog.object.contains = function(obj, val) {\r\n return goog.object.containsValue(obj, val);\r\n};\r\n\r\n\r\n/**\r\n * Returns the values of the object/map/hash.\r\n *\r\n * @param {Object<K,V>} obj The object from which to get the values.\r\n * @return {!Array<V>} The values in the object/map/hash.\r\n * @template K,V\r\n */\r\ngoog.object.getValues = function(obj) {\r\n var res = [];\r\n var i = 0;\r\n for (var key in obj) {\r\n res[i++] = obj[key];\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * Returns the keys of the object/map/hash.\r\n *\r\n * @param {Object} obj The object from which to get the keys.\r\n * @return {!Array<string>} Array of property keys.\r\n */\r\ngoog.object.getKeys = function(obj) {\r\n var res = [];\r\n var i = 0;\r\n for (var key in obj) {\r\n res[i++] = key;\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * Get a value from an object multiple levels deep. This is useful for\r\n * pulling values from deeply nested objects, such as JSON responses.\r\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\r\n *\r\n * @param {!Object} obj An object to get the value from. Can be array-like.\r\n * @param {...(string|number|!IArrayLike<number|string>)}\r\n * var_args A number of keys\r\n * (as strings, or numbers, for array-like objects). Can also be\r\n * specified as a single array of keys.\r\n * @return {*} The resulting value. If, at any point, the value for a key\r\n * in the current object is null or undefined, returns undefined.\r\n */\r\ngoog.object.getValueByKeys = function(obj, var_args) {\r\n var isArrayLike = goog.isArrayLike(var_args);\r\n var keys = isArrayLike ?\r\n /** @type {!IArrayLike<number|string>} */ (var_args) :\r\n arguments;\r\n\r\n // Start with the 2nd parameter for the variable parameters syntax.\r\n for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) {\r\n if (obj == null) return undefined;\r\n obj = obj[keys[i]];\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/map/hash contains the given key.\r\n *\r\n * @param {Object} obj The object in which to look for key.\r\n * @param {?} key The key for which to check.\r\n * @return {boolean} true If the map contains the key.\r\n */\r\ngoog.object.containsKey = function(obj, key) {\r\n return obj !== null && key in obj;\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/map/hash contains the given value. This is O(n).\r\n *\r\n * @param {Object<K,V>} obj The object in which to look for val.\r\n * @param {V} val The value for which to check.\r\n * @return {boolean} true If the map contains the value.\r\n * @template K,V\r\n */\r\ngoog.object.containsValue = function(obj, val) {\r\n for (var key in obj) {\r\n if (obj[key] == val) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Searches an object for an element that satisfies the given condition and\r\n * returns its key.\r\n * @param {Object<K,V>} obj The object to search in.\r\n * @param {function(this:T,V,string,Object<K,V>):boolean} f The\r\n * function to call for every element. Takes 3 arguments (the value,\r\n * the key and the object) and should return a boolean.\r\n * @param {T=} opt_this An optional \"this\" context for the function.\r\n * @return {string|undefined} The key of an element for which the function\r\n * returns true or undefined if no such element is found.\r\n * @template T,K,V\r\n */\r\ngoog.object.findKey = function(obj, f, opt_this) {\r\n for (var key in obj) {\r\n if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) {\r\n return key;\r\n }\r\n }\r\n return undefined;\r\n};\r\n\r\n\r\n/**\r\n * Searches an object for an element that satisfies the given condition and\r\n * returns its value.\r\n * @param {Object<K,V>} obj The object to search in.\r\n * @param {function(this:T,V,string,Object<K,V>):boolean} f The function\r\n * to call for every element. Takes 3 arguments (the value, the key\r\n * and the object) and should return a boolean.\r\n * @param {T=} opt_this An optional \"this\" context for the function.\r\n * @return {V} The value of an element for which the function returns true or\r\n * undefined if no such element is found.\r\n * @template T,K,V\r\n */\r\ngoog.object.findValue = function(obj, f, opt_this) {\r\n var key = goog.object.findKey(obj, f, opt_this);\r\n return key && obj[key];\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/map/hash is empty.\r\n *\r\n * @param {Object} obj The object to test.\r\n * @return {boolean} true if obj is empty.\r\n */\r\ngoog.object.isEmpty = function(obj) {\r\n for (var key in obj) {\r\n return false;\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Removes all key value pairs from the object/map/hash.\r\n *\r\n * @param {Object} obj The object to clear.\r\n */\r\ngoog.object.clear = function(obj) {\r\n for (var i in obj) {\r\n delete obj[i];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes a key-value pair based on the key.\r\n *\r\n * @param {Object} obj The object from which to remove the key.\r\n * @param {?} key The key to remove.\r\n * @return {boolean} Whether an element was removed.\r\n */\r\ngoog.object.remove = function(obj, key) {\r\n var rv;\r\n if (rv = key in /** @type {!Object} */ (obj)) {\r\n delete obj[key];\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the object. Throws an exception if the key is\r\n * already in use. Use set if you want to change an existing pair.\r\n *\r\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {V} val The value to add.\r\n * @template K,V\r\n */\r\ngoog.object.add = function(obj, key, val) {\r\n if (obj !== null && key in obj) {\r\n throw new Error('The object already contains the key \"' + key + '\"');\r\n }\r\n goog.object.set(obj, key, val);\r\n};\r\n\r\n\r\n/**\r\n * Returns the value for the given key.\r\n *\r\n * @param {Object<K,V>} obj The object from which to get the value.\r\n * @param {string} key The key for which to get the value.\r\n * @param {R=} opt_val The value to return if no item is found for the given\r\n * key (default is undefined).\r\n * @return {V|R|undefined} The value for the given key.\r\n * @template K,V,R\r\n */\r\ngoog.object.get = function(obj, key, opt_val) {\r\n if (obj !== null && key in obj) {\r\n return obj[key];\r\n }\r\n return opt_val;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the object/map/hash.\r\n *\r\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {V} value The value to add.\r\n * @template K,V\r\n */\r\ngoog.object.set = function(obj, key, value) {\r\n obj[key] = value;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\r\n *\r\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {V} value The value to add if the key wasn't present.\r\n * @return {V} The value of the entry at the end of the function.\r\n * @template K,V\r\n */\r\ngoog.object.setIfUndefined = function(obj, key, value) {\r\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\r\n};\r\n\r\n\r\n/**\r\n * Sets a key and value to an object if the key is not set. The value will be\r\n * the return value of the given function. If the key already exists, the\r\n * object will not be changed and the function will not be called (the function\r\n * will be lazily evaluated -- only called if necessary).\r\n *\r\n * This function is particularly useful when used with an `Object` which is\r\n * acting as a cache.\r\n *\r\n * @param {!Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {function():V} f The value to add if the key wasn't present.\r\n * @return {V} The value of the entry at the end of the function.\r\n * @template K,V\r\n */\r\ngoog.object.setWithReturnValueIfNotSet = function(obj, key, f) {\r\n if (key in obj) {\r\n return obj[key];\r\n }\r\n\r\n var val = f();\r\n obj[key] = val;\r\n return val;\r\n};\r\n\r\n\r\n/**\r\n * Compares two objects for equality using === on the values.\r\n *\r\n * @param {!Object<K,V>} a\r\n * @param {!Object<K,V>} b\r\n * @return {boolean}\r\n * @template K,V\r\n */\r\ngoog.object.equals = function(a, b) {\r\n for (var k in a) {\r\n if (!(k in b) || a[k] !== b[k]) {\r\n return false;\r\n }\r\n }\r\n for (var k in b) {\r\n if (!(k in a)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Returns a shallow clone of the object.\r\n *\r\n * @param {Object<K,V>} obj Object to clone.\r\n * @return {!Object<K,V>} Clone of the input object.\r\n * @template K,V\r\n */\r\ngoog.object.clone = function(obj) {\r\n // We cannot use the prototype trick because a lot of methods depend on where\r\n // the actual key is set.\r\n\r\n var res = {};\r\n for (var key in obj) {\r\n res[key] = obj[key];\r\n }\r\n return res;\r\n // We could also use goog.mixin but I wanted this to be independent from that.\r\n};\r\n\r\n\r\n/**\r\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\r\n * arrays will be cloned recursively.\r\n *\r\n * WARNINGS:\r\n * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects\r\n * that refer to themselves will cause infinite recursion.\r\n *\r\n * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and\r\n * copies UIDs created by <code>getUid</code> into cloned results.\r\n *\r\n * @param {T} obj The value to clone.\r\n * @return {T} A clone of the input value.\r\n * @template T\r\n */\r\ngoog.object.unsafeClone = function(obj) {\r\n var type = goog.typeOf(obj);\r\n if (type == 'object' || type == 'array') {\r\n if (goog.isFunction(obj.clone)) {\r\n return obj.clone();\r\n }\r\n var clone = type == 'array' ? [] : {};\r\n for (var key in obj) {\r\n clone[key] = goog.object.unsafeClone(obj[key]);\r\n }\r\n return clone;\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * Returns a new object in which all the keys and values are interchanged\r\n * (keys become values and values become keys). If multiple keys map to the\r\n * same value, the chosen transposed value is implementation-dependent.\r\n *\r\n * @param {Object} obj The object to transpose.\r\n * @return {!Object} The transposed object.\r\n */\r\ngoog.object.transpose = function(obj) {\r\n var transposed = {};\r\n for (var key in obj) {\r\n transposed[obj[key]] = key;\r\n }\r\n return transposed;\r\n};\r\n\r\n\r\n/**\r\n * The names of the fields that are defined on Object.prototype.\r\n * @type {Array<string>}\r\n * @private\r\n */\r\ngoog.object.PROTOTYPE_FIELDS_ = [\r\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\r\n 'toLocaleString', 'toString', 'valueOf'\r\n];\r\n\r\n\r\n/**\r\n * Extends an object with another object.\r\n * This operates 'in-place'; it does not create a new Object.\r\n *\r\n * Example:\r\n * var o = {};\r\n * goog.object.extend(o, {a: 0, b: 1});\r\n * o; // {a: 0, b: 1}\r\n * goog.object.extend(o, {b: 2, c: 3});\r\n * o; // {a: 0, b: 2, c: 3}\r\n *\r\n * @param {Object} target The object to modify. Existing properties will be\r\n * overwritten if they are also present in one of the objects in\r\n * `var_args`.\r\n * @param {...(Object|null|undefined)} var_args The objects from which values\r\n * will be copied.\r\n */\r\ngoog.object.extend = function(target, var_args) {\r\n var key, source;\r\n for (var i = 1; i < arguments.length; i++) {\r\n source = arguments[i];\r\n for (key in source) {\r\n target[key] = source[key];\r\n }\r\n\r\n // For IE the for-in-loop does not contain any properties that are not\r\n // enumerable on the prototype object (for example isPrototypeOf from\r\n // Object.prototype) and it will also not include 'replace' on objects that\r\n // extend String and change 'replace' (not that it is common for anyone to\r\n // extend anything except Object).\r\n\r\n for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {\r\n key = goog.object.PROTOTYPE_FIELDS_[j];\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n target[key] = source[key];\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Creates a new object built from the key-value pairs provided as arguments.\r\n * @param {...*} var_args If only one argument is provided and it is an array\r\n * then this is used as the arguments, otherwise even arguments are used as\r\n * the property names and odd arguments are used as the property values.\r\n * @return {!Object} The new object.\r\n * @throws {Error} If there are uneven number of arguments or there is only one\r\n * non array argument.\r\n */\r\ngoog.object.create = function(var_args) {\r\n var argLength = arguments.length;\r\n if (argLength == 1 && goog.isArray(arguments[0])) {\r\n return goog.object.create.apply(null, arguments[0]);\r\n }\r\n\r\n if (argLength % 2) {\r\n throw new Error('Uneven number of arguments');\r\n }\r\n\r\n var rv = {};\r\n for (var i = 0; i < argLength; i += 2) {\r\n rv[arguments[i]] = arguments[i + 1];\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Creates a new object where the property names come from the arguments but\r\n * the value is always set to true\r\n * @param {...*} var_args If only one argument is provided and it is an array\r\n * then this is used as the arguments, otherwise the arguments are used\r\n * as the property names.\r\n * @return {!Object} The new object.\r\n */\r\ngoog.object.createSet = function(var_args) {\r\n var argLength = arguments.length;\r\n if (argLength == 1 && goog.isArray(arguments[0])) {\r\n return goog.object.createSet.apply(null, arguments[0]);\r\n }\r\n\r\n var rv = {};\r\n for (var i = 0; i < argLength; i++) {\r\n rv[arguments[i]] = true;\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Creates an immutable view of the underlying object, if the browser\r\n * supports immutable objects.\r\n *\r\n * In default mode, writes to this view will fail silently. In strict mode,\r\n * they will throw an error.\r\n *\r\n * @param {!Object<K,V>} obj An object.\r\n * @return {!Object<K,V>} An immutable view of that object, or the\r\n * original object if this browser does not support immutables.\r\n * @template K,V\r\n */\r\ngoog.object.createImmutableView = function(obj) {\r\n var result = obj;\r\n if (Object.isFrozen && !Object.isFrozen(obj)) {\r\n result = Object.create(obj);\r\n Object.freeze(result);\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * @param {!Object} obj An object.\r\n * @return {boolean} Whether this is an immutable view of the object.\r\n */\r\ngoog.object.isImmutableView = function(obj) {\r\n return !!Object.isFrozen && Object.isFrozen(obj);\r\n};\r\n\r\n\r\n/**\r\n * Get all properties names on a given Object regardless of enumerability.\r\n *\r\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\r\n * `Object.getPrototypeOf` then this is equivalent to using\r\n * `goog.object.getKeys`\r\n *\r\n * @param {?Object} obj The object to get the properties of.\r\n * @param {boolean=} opt_includeObjectPrototype Whether properties defined on\r\n * `Object.prototype` should be included in the result.\r\n * @param {boolean=} opt_includeFunctionPrototype Whether properties defined on\r\n * `Function.prototype` should be included in the result.\r\n * @return {!Array<string>}\r\n * @public\r\n */\r\ngoog.object.getAllPropertyNames = function(\r\n obj, opt_includeObjectPrototype, opt_includeFunctionPrototype) {\r\n if (!obj) {\r\n return [];\r\n }\r\n\r\n // Naively use a for..in loop to get the property names if the browser doesn't\r\n // support any other APIs for getting it.\r\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\r\n return goog.object.getKeys(obj);\r\n }\r\n\r\n var visitedSet = {};\r\n\r\n // Traverse the prototype chain and add all properties to the visited set.\r\n var proto = obj;\r\n while (proto &&\r\n (proto !== Object.prototype || !!opt_includeObjectPrototype) &&\r\n (proto !== Function.prototype || !!opt_includeFunctionPrototype)) {\r\n var names = Object.getOwnPropertyNames(proto);\r\n for (var i = 0; i < names.length; i++) {\r\n visitedSet[names[i]] = true;\r\n }\r\n proto = Object.getPrototypeOf(proto);\r\n }\r\n\r\n return goog.object.getKeys(visitedSet);\r\n};\r\n","// Copyright 2009 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Useful compiler idioms.\r\n *\r\n * @author johnlenz@google.com (John Lenz)\r\n */\r\n\r\ngoog.provide('goog.reflect');\r\n\r\n\r\n/**\r\n * Syntax for object literal casts.\r\n * @see http://go/jscompiler-renaming\r\n * @see https://goo.gl/CRs09P\r\n *\r\n * Use this if you have an object literal whose keys need to have the same names\r\n * as the properties of some class even after they are renamed by the compiler.\r\n *\r\n * @param {!Function} type Type to cast to.\r\n * @param {Object} object Object literal to cast.\r\n * @return {Object} The object literal.\r\n */\r\ngoog.reflect.object = function(type, object) {\r\n return object;\r\n};\r\n\r\n/**\r\n * Syntax for renaming property strings.\r\n * @see http://go/jscompiler-renaming\r\n * @see https://goo.gl/CRs09P\r\n *\r\n * Use this if you have an need to access a property as a string, but want\r\n * to also have the property renamed by the compiler. In contrast to\r\n * goog.reflect.object, this method takes an instance of an object.\r\n *\r\n * Properties must be simple names (not qualified names).\r\n *\r\n * @param {string} prop Name of the property\r\n * @param {!Object} object Instance of the object whose type will be used\r\n * for renaming\r\n * @return {string} The renamed property.\r\n */\r\ngoog.reflect.objectProperty = function(prop, object) {\r\n return prop;\r\n};\r\n\r\n/**\r\n * To assert to the compiler that an operation is needed when it would\r\n * otherwise be stripped. For example:\r\n * <code>\r\n * // Force a layout\r\n * goog.reflect.sinkValue(dialog.offsetHeight);\r\n * </code>\r\n * @param {T} x\r\n * @return {T}\r\n * @template T\r\n */\r\ngoog.reflect.sinkValue = function(x) {\r\n goog.reflect.sinkValue[' '](x);\r\n return x;\r\n};\r\n\r\n\r\n/**\r\n * The compiler should optimize this function away iff no one ever uses\r\n * goog.reflect.sinkValue.\r\n */\r\ngoog.reflect.sinkValue[' '] = goog.nullFunction;\r\n\r\n\r\n/**\r\n * Check if a property can be accessed without throwing an exception.\r\n * @param {Object} obj The owner of the property.\r\n * @param {string} prop The property name.\r\n * @return {boolean} Whether the property is accessible. Will also return true\r\n * if obj is null.\r\n */\r\ngoog.reflect.canAccessProperty = function(obj, prop) {\r\n\r\n try {\r\n goog.reflect.sinkValue(obj[prop]);\r\n return true;\r\n } catch (e) {\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Retrieves a value from a cache given a key. The compiler provides special\r\n * consideration for this call such that it is generally considered side-effect\r\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\r\n * then the entire call is considered to have side-effects.\r\n *\r\n * Conventionally storing the value on the cache would be considered a\r\n * side-effect and preclude unused calls from being pruned, ie. even if\r\n * the value was never used, it would still always be stored in the cache.\r\n *\r\n * Providing a side-effect free `valueFn` and `opt_keyFn`\r\n * allows unused calls to `goog.reflect.cache` to be pruned.\r\n *\r\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\r\n * @param {?} key The key to lookup in the cache. If it is not string or number\r\n * then a `opt_keyFn` should be provided. The key is also used as the\r\n * parameter to the `valueFn`.\r\n * @param {function(?):V} valueFn The value provider to use to calculate the\r\n * value to store in the cache. This function should be side-effect free\r\n * to take advantage of the optimization.\r\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\r\n * map key. This should be used if the given key is not a string or number.\r\n * If not provided then the given key is used. This function should be\r\n * side-effect free to take advantage of the optimization.\r\n * @return {V} The cached or calculated value.\r\n * @template K\r\n * @template V\r\n */\r\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\r\n var storedKey = opt_keyFn ? opt_keyFn(key) : key;\r\n\r\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\r\n return cacheObj[storedKey];\r\n }\r\n\r\n return (cacheObj[storedKey] = valueFn(key));\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Rendering engine detection.\r\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\r\n * For information on the browser brand (such as Safari versus Chrome), see\r\n * goog.userAgent.product.\r\n * @author arv@google.com (Erik Arvidsson)\r\n * @see ../demos/useragent.html\r\n */\r\n\r\ngoog.provide('goog.userAgent');\r\n\r\ngoog.require('goog.labs.userAgent.browser');\r\ngoog.require('goog.labs.userAgent.engine');\r\ngoog.require('goog.labs.userAgent.platform');\r\ngoog.require('goog.labs.userAgent.util');\r\ngoog.require('goog.reflect');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is IE.\r\n */\r\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is EDGE.\r\n */\r\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\r\n */\r\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\r\n */\r\ngoog.userAgent.ASSUME_WEBKIT =\r\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is a\r\n * mobile device running WebKit e.g. iPhone or Android.\r\n */\r\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\r\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is OPERA.\r\n */\r\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the\r\n * `goog.userAgent.isVersionOrHigher`\r\n * function will return true for any version.\r\n */\r\ngoog.userAgent.ASSUME_ANY_VERSION =\r\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\r\n\r\n\r\n/**\r\n * Whether we know the browser engine at compile-time.\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\r\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\r\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\r\n goog.userAgent.ASSUME_OPERA;\r\n\r\n\r\n/**\r\n * Returns the userAgent string for the current browser.\r\n *\r\n * @return {string} The userAgent string.\r\n */\r\ngoog.userAgent.getUserAgentString = function() {\r\n return goog.labs.userAgent.util.getUserAgent();\r\n};\r\n\r\n\r\n/**\r\n * @return {?Navigator} The native navigator object.\r\n */\r\ngoog.userAgent.getNavigatorTyped = function() {\r\n // Need a local navigator reference instead of using the global one,\r\n // to avoid the rare case where they reference different objects.\r\n // (in a WorkerPool, for example).\r\n return goog.global['navigator'] || null;\r\n};\r\n\r\n\r\n/**\r\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\r\n * @return {?Object} The native navigator object.\r\n */\r\ngoog.userAgent.getNavigator = function() {\r\n return goog.userAgent.getNavigatorTyped();\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is Opera.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_OPERA :\r\n goog.labs.userAgent.browser.isOpera();\r\n\r\n\r\n/**\r\n * Whether the user agent is Internet Explorer.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_IE :\r\n goog.labs.userAgent.browser.isIE();\r\n\r\n\r\n/**\r\n * Whether the user agent is Microsoft Edge.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_EDGE :\r\n goog.labs.userAgent.engine.isEdge();\r\n\r\n\r\n/**\r\n * Whether the user agent is MS Internet Explorer or MS Edge.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\r\n\r\n\r\n/**\r\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\r\n * Mozilla, Firefox, and others.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_GECKO :\r\n goog.labs.userAgent.engine.isGecko();\r\n\r\n\r\n/**\r\n * Whether the user agent is WebKit. WebKit is the rendering engine that\r\n * Safari, Android and others use.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\r\n goog.labs.userAgent.engine.isWebKit();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a mobile device.\r\n *\r\n * This is a separate function so that the logic can be tested.\r\n *\r\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\r\n *\r\n * @return {boolean} Whether the user agent is running on a mobile device.\r\n * @private\r\n */\r\ngoog.userAgent.isMobile_ = function() {\r\n return goog.userAgent.WEBKIT &&\r\n goog.labs.userAgent.util.matchUserAgent('Mobile');\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a mobile device.\r\n *\r\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\r\n * is promoted as the gecko/webkit logic is likely inaccurate.\r\n *\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.MOBILE =\r\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\r\n\r\n\r\n/**\r\n * Used while transitioning code to use WEBKIT instead.\r\n * @type {boolean}\r\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\r\n * TODO(nicksantos): Delete this from goog.userAgent.\r\n */\r\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\r\n\r\n\r\n/**\r\n * @return {string} the platform (operating system) the user agent is running\r\n * on. Default to empty string because navigator.platform may not be defined\r\n * (on Rhino, for example).\r\n * @private\r\n */\r\ngoog.userAgent.determinePlatform_ = function() {\r\n var navigator = goog.userAgent.getNavigatorTyped();\r\n return navigator && navigator.platform || '';\r\n};\r\n\r\n\r\n/**\r\n * The platform (operating system) the user agent is running on. Default to\r\n * empty string because navigator.platform may not be defined (on Rhino, for\r\n * example).\r\n * @type {string}\r\n */\r\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a Macintosh operating\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a Windows operating\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_WINDOWS =\r\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a Linux operating\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a X11 windowing\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on Android.\r\n */\r\ngoog.userAgent.ASSUME_ANDROID =\r\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on an iPhone.\r\n */\r\ngoog.userAgent.ASSUME_IPHONE =\r\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on an iPad.\r\n */\r\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on an iPod.\r\n */\r\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on KaiOS.\r\n */\r\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on Go2Phone.\r\n */\r\ngoog.userAgent.ASSUME_GO2PHONE =\r\n goog.define('goog.userAgent.ASSUME_GO2PHONE', false);\r\n\r\n\r\n/**\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\r\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\r\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\r\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\r\n goog.userAgent.ASSUME_IPOD;\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a Macintosh operating system.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_MAC :\r\n goog.labs.userAgent.platform.isMacintosh();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a Windows operating system.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_WINDOWS :\r\n goog.labs.userAgent.platform.isWindows();\r\n\r\n\r\n/**\r\n * Whether the user agent is Linux per the legacy behavior of\r\n * goog.userAgent.LINUX, which considered ChromeOS to also be\r\n * Linux.\r\n * @return {boolean}\r\n * @private\r\n */\r\ngoog.userAgent.isLegacyLinux_ = function() {\r\n return goog.labs.userAgent.platform.isLinux() ||\r\n goog.labs.userAgent.platform.isChromeOS();\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a Linux operating system.\r\n *\r\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\r\n * while goog.labs.userAgent.platform considers ChromeOS and\r\n * Linux to be different OSes.\r\n *\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_LINUX :\r\n goog.userAgent.isLegacyLinux_();\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user agent is an X11 windowing system.\r\n * @private\r\n */\r\ngoog.userAgent.isX11_ = function() {\r\n var navigator = goog.userAgent.getNavigatorTyped();\r\n return !!navigator &&\r\n goog.string.contains(navigator['appVersion'] || '', 'X11');\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a X11 windowing system.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_X11 :\r\n goog.userAgent.isX11_();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on Android.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_ANDROID :\r\n goog.labs.userAgent.platform.isAndroid();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on an iPhone.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_IPHONE :\r\n goog.labs.userAgent.platform.isIphone();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on an iPad.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_IPAD :\r\n goog.labs.userAgent.platform.isIpad();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on an iPod.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_IPOD :\r\n goog.labs.userAgent.platform.isIpod();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on iOS.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\r\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\r\n goog.userAgent.ASSUME_IPOD) :\r\n goog.labs.userAgent.platform.isIos();\r\n\r\n/**\r\n * Whether the user agent is running on KaiOS.\r\n */\r\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_KAIOS :\r\n goog.labs.userAgent.platform.isKaiOS();\r\n\r\n/**\r\n * Whether the user agent is running on Go2Phone.\r\n */\r\ngoog.userAgent.GO2PHONE = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_GO2PHONE :\r\n goog.labs.userAgent.platform.isGo2Phone();\r\n\r\n\r\n/**\r\n * @return {string} The string that describes the version number of the user\r\n * agent.\r\n * @private\r\n */\r\ngoog.userAgent.determineVersion_ = function() {\r\n // All browsers have different ways to detect the version and they all have\r\n // different naming schemes.\r\n // version is a string rather than a number because it may contain 'b', 'a',\r\n // and so on.\r\n var version = '';\r\n var arr = goog.userAgent.getVersionRegexResult_();\r\n if (arr) {\r\n version = arr ? arr[1] : '';\r\n }\r\n\r\n if (goog.userAgent.IE) {\r\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\r\n // version. If it is identifying as a version lower than 9 we take the\r\n // documentMode as the version instead. IE8 has similar behavior.\r\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\r\n // uses documentMode 9.\r\n var docMode = goog.userAgent.getDocumentMode_();\r\n if (docMode != null && docMode > parseFloat(version)) {\r\n return String(docMode);\r\n }\r\n }\r\n\r\n return version;\r\n};\r\n\r\n\r\n/**\r\n * @return {?IArrayLike<string>|undefined} The version regex matches from\r\n * parsing the user\r\n * agent string. These regex statements must be executed inline so they can\r\n * be compiled out by the closure compiler with the rest of the useragent\r\n * detection logic when ASSUME_* is specified.\r\n * @private\r\n */\r\ngoog.userAgent.getVersionRegexResult_ = function() {\r\n var userAgent = goog.userAgent.getUserAgentString();\r\n if (goog.userAgent.GECKO) {\r\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.EDGE) {\r\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.IE) {\r\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.WEBKIT) {\r\n // WebKit/125.4\r\n return /WebKit\\/(\\S+)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.OPERA) {\r\n // If none of the above browsers were detected but the browser is Opera, the\r\n // only string that is of interest is 'Version/<number>'.\r\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\r\n }\r\n return undefined;\r\n};\r\n\r\n\r\n/**\r\n * @return {number|undefined} Returns the document mode (for testing).\r\n * @private\r\n */\r\ngoog.userAgent.getDocumentMode_ = function() {\r\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\r\n var doc = goog.global['document'];\r\n return doc ? doc['documentMode'] : undefined;\r\n};\r\n\r\n\r\n/**\r\n * The version of the user agent. This is a string because it might contain\r\n * 'b' (as in beta) as well as multiple dots.\r\n * @type {string}\r\n */\r\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\r\n\r\n\r\n/**\r\n * Compares two version numbers.\r\n *\r\n * @param {string} v1 Version of first item.\r\n * @param {string} v2 Version of second item.\r\n *\r\n * @return {number} 1 if first argument is higher\r\n * 0 if arguments are equal\r\n * -1 if second argument is higher.\r\n * @deprecated Use goog.string.compareVersions.\r\n */\r\ngoog.userAgent.compare = function(v1, v2) {\r\n return goog.string.compareVersions(v1, v2);\r\n};\r\n\r\n\r\n/**\r\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\r\n * Calls to compareVersions are surprisingly expensive and, as a browser's\r\n * version number is unlikely to change during a session, we cache the results.\r\n * @const\r\n * @private\r\n */\r\ngoog.userAgent.isVersionOrHigherCache_ = {};\r\n\r\n\r\n/**\r\n * Whether the user agent version is higher or the same as the given version.\r\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\r\n * use the engine's version, not the browser's version number. For example,\r\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\r\n * Opera and Internet Explorer versions match the product release number.<br>\r\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\r\n * Webkit</a>\r\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\r\n *\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the user agent version is higher or the same as\r\n * the given version.\r\n */\r\ngoog.userAgent.isVersionOrHigher = function(version) {\r\n return goog.userAgent.ASSUME_ANY_VERSION ||\r\n goog.reflect.cache(\r\n goog.userAgent.isVersionOrHigherCache_, version, function() {\r\n return goog.string.compareVersions(\r\n goog.userAgent.VERSION, version) >= 0;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Deprecated alias to `goog.userAgent.isVersionOrHigher`.\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the user agent version is higher or the same as\r\n * the given version.\r\n * @deprecated Use goog.userAgent.isVersionOrHigher().\r\n */\r\ngoog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;\r\n\r\n\r\n/**\r\n * Whether the IE effective document mode is higher or the same as the given\r\n * document mode version.\r\n * NOTE: Only for IE, return false for another browser.\r\n *\r\n * @param {number} documentMode The document mode version to check.\r\n * @return {boolean} Whether the IE effective document mode is higher or the\r\n * same as the given version.\r\n */\r\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\r\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\r\n};\r\n\r\n\r\n/**\r\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\r\n * @param {number} version The version to check.\r\n * @return {boolean} Whether the IE effective document mode is higher or the\r\n * same as the given version.\r\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\r\n */\r\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\r\n\r\n\r\n/**\r\n * For IE version < 7, documentMode is undefined, so attempt to use the\r\n * CSS1Compat property to see if we are in standards mode. If we are in\r\n * standards mode, treat the browser version as the document mode. Otherwise,\r\n * IE is emulating version 5.\r\n * @type {number|undefined}\r\n * @const\r\n */\r\ngoog.userAgent.DOCUMENT_MODE = (function() {\r\n var doc = goog.global['document'];\r\n var mode = goog.userAgent.getDocumentMode_();\r\n if (!doc || !goog.userAgent.IE) {\r\n return undefined;\r\n }\r\n return mode || (doc['compatMode'] == 'CSS1Compat' ?\r\n parseInt(goog.userAgent.VERSION, 10) :\r\n 5);\r\n})();\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Closure user agent detection (Browser).\r\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\r\n * For more information on rendering engine, platform, or device see the other\r\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\r\n * goog.labs.userAgent.device respectively.)\r\n *\r\n * @author martone@google.com (Andy Martone)\r\n */\r\n\r\ngoog.provide('goog.labs.userAgent.browser');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.labs.userAgent.util');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string.internal');\r\n\r\n\r\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\r\n// functions.\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium\r\n * based Opera (Opera 15+) is detected as Chrome to avoid unnecessary\r\n * special casing.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchOpera_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Opera');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is IE.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchIE_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Trident') ||\r\n goog.labs.userAgent.util.matchUserAgent('MSIE');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Edge.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchEdge_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Edge');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Firefox.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchFirefox_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Firefox') ||\r\n goog.labs.userAgent.util.matchUserAgent('FxiOS');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Safari.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchSafari_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Safari') &&\r\n !(goog.labs.userAgent.browser.matchChrome_() ||\r\n goog.labs.userAgent.browser.matchCoast_() ||\r\n goog.labs.userAgent.browser.matchOpera_() ||\r\n goog.labs.userAgent.browser.matchEdge_() ||\r\n goog.labs.userAgent.browser.matchFirefox_() ||\r\n goog.labs.userAgent.browser.isSilk() ||\r\n goog.labs.userAgent.util.matchUserAgent('Android'));\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\r\n * iOS browser).\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchCoast_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Coast');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is iOS Webview.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchIosWebview_ = function() {\r\n // iOS Webview does not show up as Chrome or Safari. Also check for Opera's\r\n // WebKit-based iOS browser, Coast.\r\n return (goog.labs.userAgent.util.matchUserAgent('iPad') ||\r\n goog.labs.userAgent.util.matchUserAgent('iPhone')) &&\r\n !goog.labs.userAgent.browser.matchSafari_() &&\r\n !goog.labs.userAgent.browser.matchChrome_() &&\r\n !goog.labs.userAgent.browser.matchCoast_() &&\r\n !goog.labs.userAgent.browser.matchFirefox_() &&\r\n goog.labs.userAgent.util.matchUserAgent('AppleWebKit');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Chrome.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchChrome_ = function() {\r\n return (goog.labs.userAgent.util.matchUserAgent('Chrome') ||\r\n goog.labs.userAgent.util.matchUserAgent('CriOS')) &&\r\n !goog.labs.userAgent.browser.matchEdge_();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is the Android browser.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchAndroidBrowser_ = function() {\r\n // Android can appear in the user agent string for Chrome on Android.\r\n // This is not the Android standalone browser if it does.\r\n return goog.labs.userAgent.util.matchUserAgent('Android') &&\r\n !(goog.labs.userAgent.browser.isChrome() ||\r\n goog.labs.userAgent.browser.isFirefox() ||\r\n goog.labs.userAgent.browser.isOpera() ||\r\n goog.labs.userAgent.browser.isSilk());\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Opera.\r\n */\r\ngoog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is IE.\r\n */\r\ngoog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Edge.\r\n */\r\ngoog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdge_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Firefox.\r\n */\r\ngoog.labs.userAgent.browser.isFirefox =\r\n goog.labs.userAgent.browser.matchFirefox_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Safari.\r\n */\r\ngoog.labs.userAgent.browser.isSafari = goog.labs.userAgent.browser.matchSafari_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\r\n * iOS browser).\r\n */\r\ngoog.labs.userAgent.browser.isCoast = goog.labs.userAgent.browser.matchCoast_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is iOS Webview.\r\n */\r\ngoog.labs.userAgent.browser.isIosWebview =\r\n goog.labs.userAgent.browser.matchIosWebview_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Chrome.\r\n */\r\ngoog.labs.userAgent.browser.isChrome = goog.labs.userAgent.browser.matchChrome_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is the Android browser.\r\n */\r\ngoog.labs.userAgent.browser.isAndroidBrowser =\r\n goog.labs.userAgent.browser.matchAndroidBrowser_;\r\n\r\n\r\n/**\r\n * For more information, see:\r\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\r\n * @return {boolean} Whether the user's browser is Silk.\r\n */\r\ngoog.labs.userAgent.browser.isSilk = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Silk');\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The browser version or empty string if version cannot be\r\n * determined. Note that for Internet Explorer, this returns the version of\r\n * the browser, not the version of the rendering engine. (IE 8 in\r\n * compatibility mode will return 8.0 rather than 7.0. To determine the\r\n * rendering engine version, look at document.documentMode instead. See\r\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\r\n * details.)\r\n */\r\ngoog.labs.userAgent.browser.getVersion = function() {\r\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\r\n // Special case IE since IE's version is inside the parenthesis and\r\n // without the '/'.\r\n if (goog.labs.userAgent.browser.isIE()) {\r\n return goog.labs.userAgent.browser.getIEVersion_(userAgentString);\r\n }\r\n\r\n var versionTuples =\r\n goog.labs.userAgent.util.extractVersionTuples(userAgentString);\r\n\r\n // Construct a map for easy lookup.\r\n var versionMap = {};\r\n goog.array.forEach(versionTuples, function(tuple) {\r\n // Note that the tuple is of length three, but we only care about the\r\n // first two.\r\n var key = tuple[0];\r\n var value = tuple[1];\r\n versionMap[key] = value;\r\n });\r\n\r\n var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap);\r\n\r\n // Gives the value with the first key it finds, otherwise empty string.\r\n function lookUpValueWithKeys(keys) {\r\n var key = goog.array.find(keys, versionMapHasKey);\r\n return versionMap[key] || '';\r\n }\r\n\r\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\r\n // See\r\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\r\n if (goog.labs.userAgent.browser.isOpera()) {\r\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\r\n // Opera uses 'OPR' for more recent UAs.\r\n return lookUpValueWithKeys(['Version', 'Opera']);\r\n }\r\n\r\n // Check Edge before Chrome since it has Chrome in the string.\r\n if (goog.labs.userAgent.browser.isEdge()) {\r\n return lookUpValueWithKeys(['Edge']);\r\n }\r\n\r\n if (goog.labs.userAgent.browser.isChrome()) {\r\n return lookUpValueWithKeys(['Chrome', 'CriOS']);\r\n }\r\n\r\n // Usually products browser versions are in the third tuple after \"Mozilla\"\r\n // and the engine.\r\n var tuple = versionTuples[2];\r\n return tuple && tuple[1] || '';\r\n};\r\n\r\n\r\n/**\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the browser version is higher or the same as the\r\n * given version.\r\n */\r\ngoog.labs.userAgent.browser.isVersionOrHigher = function(version) {\r\n return goog.string.internal.compareVersions(\r\n goog.labs.userAgent.browser.getVersion(), version) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * Determines IE version. More information:\r\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\r\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\r\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\r\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\r\n *\r\n * @param {string} userAgent the User-Agent.\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.getIEVersion_ = function(userAgent) {\r\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\r\n // bug. Example UA:\r\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\r\n // like Gecko.\r\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\r\n var rv = /rv: *([\\d\\.]*)/.exec(userAgent);\r\n if (rv && rv[1]) {\r\n return rv[1];\r\n }\r\n\r\n var version = '';\r\n var msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\r\n if (msie && msie[1]) {\r\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\r\n // case, use the Trident version to determine the version of IE. For more\r\n // details, see the links above.\r\n var tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\r\n if (msie[1] == '7.0') {\r\n if (tridentVersion && tridentVersion[1]) {\r\n switch (tridentVersion[1]) {\r\n case '4.0':\r\n version = '8.0';\r\n break;\r\n case '5.0':\r\n version = '9.0';\r\n break;\r\n case '6.0':\r\n version = '10.0';\r\n break;\r\n case '7.0':\r\n version = '11.0';\r\n break;\r\n }\r\n } else {\r\n version = '7.0';\r\n }\r\n } else {\r\n version = msie[1];\r\n }\r\n }\r\n return version;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Closure user agent detection.\r\n * @see http://en.wikipedia.org/wiki/User_agent\r\n * For more information on browser brand, platform, or device see the other\r\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\r\n *\r\n */\r\n\r\ngoog.provide('goog.labs.userAgent.engine');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.labs.userAgent.util');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Presto.\r\n */\r\ngoog.labs.userAgent.engine.isPresto = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Presto');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Trident.\r\n */\r\ngoog.labs.userAgent.engine.isTrident = function() {\r\n // IE only started including the Trident token in IE8.\r\n return goog.labs.userAgent.util.matchUserAgent('Trident') ||\r\n goog.labs.userAgent.util.matchUserAgent('MSIE');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Edge.\r\n */\r\ngoog.labs.userAgent.engine.isEdge = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Edge');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is WebKit.\r\n */\r\ngoog.labs.userAgent.engine.isWebKit = function() {\r\n return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') &&\r\n !goog.labs.userAgent.engine.isEdge();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Gecko.\r\n */\r\ngoog.labs.userAgent.engine.isGecko = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Gecko') &&\r\n !goog.labs.userAgent.engine.isWebKit() &&\r\n !goog.labs.userAgent.engine.isTrident() &&\r\n !goog.labs.userAgent.engine.isEdge();\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The rendering engine's version or empty string if version\r\n * can't be determined.\r\n */\r\ngoog.labs.userAgent.engine.getVersion = function() {\r\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\r\n if (userAgentString) {\r\n var tuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString);\r\n\r\n var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples);\r\n if (engineTuple) {\r\n // In Gecko, the version string is either in the browser info or the\r\n // Firefox version. See Gecko user agent string reference:\r\n // http://goo.gl/mULqa\r\n if (engineTuple[0] == 'Gecko') {\r\n return goog.labs.userAgent.engine.getVersionForKey_(tuples, 'Firefox');\r\n }\r\n\r\n return engineTuple[1];\r\n }\r\n\r\n // MSIE has only one version identifier, and the Trident version is\r\n // specified in the parenthetical. IE Edge is covered in the engine tuple\r\n // detection.\r\n var browserTuple = tuples[0];\r\n var info;\r\n if (browserTuple && (info = browserTuple[2])) {\r\n var match = /Trident\\/([^\\s;]+)/.exec(info);\r\n if (match) {\r\n return match[1];\r\n }\r\n }\r\n }\r\n return '';\r\n};\r\n\r\n\r\n/**\r\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\r\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\r\n * found.\r\n * @private\r\n */\r\ngoog.labs.userAgent.engine.getEngineTuple_ = function(tuples) {\r\n if (!goog.labs.userAgent.engine.isEdge()) {\r\n return tuples[1];\r\n }\r\n for (var i = 0; i < tuples.length; i++) {\r\n var tuple = tuples[i];\r\n if (tuple[0] == 'Edge') {\r\n return tuple;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the rendering engine version is higher or the same\r\n * as the given version.\r\n */\r\ngoog.labs.userAgent.engine.isVersionOrHigher = function(version) {\r\n return goog.string.compareVersions(\r\n goog.labs.userAgent.engine.getVersion(), version) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * @param {!Array<!Array<string>>} tuples Version tuples.\r\n * @param {string} key The key to look for.\r\n * @return {string} The version string of the given key, if present.\r\n * Otherwise, the empty string.\r\n * @private\r\n */\r\ngoog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) {\r\n // TODO(nnaze): Move to util if useful elsewhere.\r\n\r\n var pair = goog.array.find(tuples, function(pair) { return key == pair[0]; });\r\n\r\n return pair && pair[1] || '';\r\n};\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Browser capability checks for the events package.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.events.BrowserFeature');\r\n\r\ngoog.require('goog.userAgent');\r\ngoog.scope(function() {\r\n\r\n\r\n\r\n/**\r\n * Enum of browser capabilities.\r\n * @enum {boolean}\r\n */\r\ngoog.events.BrowserFeature = {\r\n /**\r\n * Whether the button attribute of the event is W3C compliant. False in\r\n * Internet Explorer prior to version 9; document-version dependent.\r\n */\r\n HAS_W3C_BUTTON:\r\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),\r\n\r\n /**\r\n * Whether the browser supports full W3C event model.\r\n */\r\n HAS_W3C_EVENT_SUPPORT:\r\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),\r\n\r\n /**\r\n * To prevent default in IE7-8 for certain keydown events we need set the\r\n * keyCode to -1.\r\n */\r\n SET_KEY_CODE_TO_PREVENT_DEFAULT:\r\n goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),\r\n\r\n /**\r\n * Whether the `navigator.onLine` property is supported.\r\n */\r\n HAS_NAVIGATOR_ONLINE_PROPERTY:\r\n !goog.userAgent.WEBKIT || goog.userAgent.isVersionOrHigher('528'),\r\n\r\n /**\r\n * Whether HTML5 network online/offline events are supported.\r\n */\r\n HAS_HTML5_NETWORK_EVENT_SUPPORT:\r\n goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9b') ||\r\n goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8') ||\r\n goog.userAgent.OPERA && goog.userAgent.isVersionOrHigher('9.5') ||\r\n goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('528'),\r\n\r\n /**\r\n * Whether HTML5 network events fire on document.body, or otherwise the\r\n * window.\r\n */\r\n HTML5_NETWORK_EVENTS_FIRE_ON_BODY:\r\n goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('8') ||\r\n goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),\r\n\r\n /**\r\n * Whether touch is enabled in the browser.\r\n */\r\n TOUCH_ENABLED:\r\n ('ontouchstart' in goog.global ||\r\n !!(goog.global['document'] && document.documentElement &&\r\n 'ontouchstart' in document.documentElement) ||\r\n // IE10 uses non-standard touch events, so it has a different check.\r\n !!(goog.global['navigator'] &&\r\n (goog.global['navigator']['maxTouchPoints'] ||\r\n goog.global['navigator']['msMaxTouchPoints']))),\r\n\r\n /**\r\n * Whether addEventListener supports W3C standard pointer events.\r\n * http://www.w3.org/TR/pointerevents/\r\n */\r\n POINTER_EVENTS: ('PointerEvent' in goog.global),\r\n\r\n /**\r\n * Whether addEventListener supports MSPointer events (only used in IE10).\r\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\r\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\r\n */\r\n MSPOINTER_EVENTS:\r\n ('MSPointerEvent' in goog.global &&\r\n !!(goog.global['navigator'] &&\r\n goog.global['navigator']['msPointerEnabled'])),\r\n\r\n /**\r\n * Whether addEventListener supports {passive: true}.\r\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\r\n */\r\n PASSIVE_EVENTS: purify(function() {\r\n // If we're in a web worker or other custom environment, we can't tell.\r\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\r\n return false;\r\n }\r\n\r\n var passive = false;\r\n var options = Object.defineProperty({}, 'passive', {\r\n get: function() {\r\n passive = true;\r\n }\r\n });\r\n try {\r\n goog.global.addEventListener('test', goog.nullFunction, options);\r\n goog.global.removeEventListener('test', goog.nullFunction, options);\r\n } catch (e) {\r\n }\r\n\r\n return passive;\r\n })\r\n};\r\n\r\n\r\n/**\r\n * Tricks Closure Compiler into believing that a function is pure. The compiler\r\n * assumes that any `valueOf` function is pure, without analyzing its contents.\r\n *\r\n * @param {function(): T} fn\r\n * @return {T}\r\n * @template T\r\n */\r\nfunction purify(fn) {\r\n return ({valueOf: fn}).valueOf();\r\n}\r\n}); // goog.scope\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A base class for event objects.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.events.Event');\r\ngoog.provide('goog.events.EventLike');\r\n\r\n/**\r\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\r\n * goog.Disposable here to not break projects which assume this dependency.\r\n * @suppress {extraRequire}\r\n */\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.events.EventId');\r\n\r\n\r\n/**\r\n * A typedef for event like objects that are dispatchable via the\r\n * goog.events.dispatchEvent function. strings are treated as the type for a\r\n * goog.events.Event. Objects are treated as an extension of a new\r\n * goog.events.Event with the type property of the object being used as the type\r\n * of the Event.\r\n * @typedef {string|Object|goog.events.Event|goog.events.EventId}\r\n */\r\ngoog.events.EventLike;\r\n\r\n\r\n\r\n/**\r\n * A base class for event objects, so that they can support preventDefault and\r\n * stopPropagation.\r\n *\r\n * @suppress {underscore} Several properties on this class are technically\r\n * public, but referencing these properties outside this package is strongly\r\n * discouraged.\r\n *\r\n * @param {string|!goog.events.EventId} type Event Type.\r\n * @param {Object=} opt_target Reference to the object that is the target of\r\n * this event. It has to implement the `EventTarget` interface\r\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\r\n * @constructor\r\n */\r\ngoog.events.Event = function(type, opt_target) {\r\n /**\r\n * Event type.\r\n * @type {string}\r\n */\r\n this.type = type instanceof goog.events.EventId ? String(type) : type;\r\n\r\n /**\r\n * TODO(tbreisacher): The type should probably be\r\n * EventTarget|goog.events.EventTarget.\r\n *\r\n * Target of the event.\r\n * @type {Object|undefined}\r\n */\r\n this.target = opt_target;\r\n\r\n /**\r\n * Object that had the listener attached.\r\n * @type {Object|undefined}\r\n */\r\n this.currentTarget = this.target;\r\n\r\n /**\r\n * Whether to cancel the event in internal capture/bubble processing for IE.\r\n * @type {boolean}\r\n * @public\r\n */\r\n this.propagationStopped_ = false;\r\n\r\n /**\r\n * Whether the default action has been prevented.\r\n * This is a property to match the W3C specification at\r\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\r\n * #events-event-type-defaultPrevented}.\r\n * Must be treated as read-only outside the class.\r\n * @type {boolean}\r\n */\r\n this.defaultPrevented = false;\r\n\r\n /**\r\n * Return value for in internal capture/bubble processing for IE.\r\n * @type {boolean}\r\n * @public\r\n */\r\n this.returnValue_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Stops event propagation.\r\n */\r\ngoog.events.Event.prototype.stopPropagation = function() {\r\n this.propagationStopped_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Prevents the default action, for example a link redirecting to a url.\r\n */\r\ngoog.events.Event.prototype.preventDefault = function() {\r\n this.defaultPrevented = true;\r\n this.returnValue_ = false;\r\n};\r\n\r\n\r\n/**\r\n * Stops the propagation of the event. It is equivalent to\r\n * `e.stopPropagation()`, but can be used as the callback argument of\r\n * {@link goog.events.listen} without declaring another function.\r\n * @param {!goog.events.Event} e An event.\r\n */\r\ngoog.events.Event.stopPropagation = function(e) {\r\n e.stopPropagation();\r\n};\r\n\r\n\r\n/**\r\n * Prevents the default action. It is equivalent to\r\n * `e.preventDefault()`, but can be used as the callback argument of\r\n * {@link goog.events.listen} without declaring another function.\r\n * @param {!goog.events.Event} e An event.\r\n */\r\ngoog.events.Event.preventDefault = function(e) {\r\n e.preventDefault();\r\n};\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A patched, standardized event object for browser events.\r\n *\r\n * <pre>\r\n * The patched event object contains the following members:\r\n * - type {string} Event type, e.g. 'click'\r\n * - target {Object} The element that actually triggered the event\r\n * - currentTarget {Object} The element the listener is attached to\r\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\r\n * - offsetX {number} X-coordinate relative to target\r\n * - offsetY {number} Y-coordinate relative to target\r\n * - clientX {number} X-coordinate relative to viewport\r\n * - clientY {number} Y-coordinate relative to viewport\r\n * - screenX {number} X-coordinate relative to the edge of the screen\r\n * - screenY {number} Y-coordinate relative to the edge of the screen\r\n * - button {number} Mouse button. Use isButton() to test.\r\n * - keyCode {number} Key-code\r\n * - ctrlKey {boolean} Was ctrl key depressed\r\n * - altKey {boolean} Was alt key depressed\r\n * - shiftKey {boolean} Was shift key depressed\r\n * - metaKey {boolean} Was meta key depressed\r\n * - pointerId {number} Pointer ID\r\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\r\n * - defaultPrevented {boolean} Whether the default action has been prevented\r\n * - state {Object} History state object\r\n *\r\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\r\n * key and character code use {@link goog.events.KeyHandler}.\r\n * </pre>\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\ngoog.provide('goog.events.BrowserEvent');\r\ngoog.provide('goog.events.BrowserEvent.MouseButton');\r\ngoog.provide('goog.events.BrowserEvent.PointerType');\r\n\r\ngoog.require('goog.debug');\r\ngoog.require('goog.events.BrowserFeature');\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.EventType');\r\ngoog.require('goog.reflect');\r\ngoog.require('goog.userAgent');\r\n\r\n/**\r\n * @define {boolean} If true, use the layerX and layerY properties of a native\r\n * browser event over the offsetX and offsetY properties, which cause expensive\r\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\r\n * as usual.\r\n */\r\ngoog.events.USE_LAYER_XY_AS_OFFSET_XY =\r\n goog.define('goog.events.USE_LAYER_XY_AS_OFFSET_XY', false);\r\n\r\n/**\r\n * Accepts a browser event object and creates a patched, cross browser event\r\n * object.\r\n * The content of this object will not be initialized if no event object is\r\n * provided. If this is the case, init() needs to be invoked separately.\r\n * @param {Event=} opt_e Browser event object.\r\n * @param {EventTarget=} opt_currentTarget Current target for event.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\r\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\r\n\r\n /**\r\n * Target that fired the event.\r\n * @override\r\n * @type {?Node}\r\n */\r\n this.target = null;\r\n\r\n /**\r\n * Node that had the listener attached.\r\n * @override\r\n * @type {?Node|undefined}\r\n */\r\n this.currentTarget = null;\r\n\r\n /**\r\n * For mouseover and mouseout events, the related object for the event.\r\n * @type {?Node}\r\n */\r\n this.relatedTarget = null;\r\n\r\n /**\r\n * X-coordinate relative to target.\r\n * @type {number}\r\n */\r\n this.offsetX = 0;\r\n\r\n /**\r\n * Y-coordinate relative to target.\r\n * @type {number}\r\n */\r\n this.offsetY = 0;\r\n\r\n /**\r\n * X-coordinate relative to the window.\r\n * @type {number}\r\n */\r\n this.clientX = 0;\r\n\r\n /**\r\n * Y-coordinate relative to the window.\r\n * @type {number}\r\n */\r\n this.clientY = 0;\r\n\r\n /**\r\n * X-coordinate relative to the monitor.\r\n * @type {number}\r\n */\r\n this.screenX = 0;\r\n\r\n /**\r\n * Y-coordinate relative to the monitor.\r\n * @type {number}\r\n */\r\n this.screenY = 0;\r\n\r\n /**\r\n * Which mouse button was pressed.\r\n * @type {number}\r\n */\r\n this.button = 0;\r\n\r\n /**\r\n * Key of key press.\r\n * @type {string}\r\n */\r\n this.key = '';\r\n\r\n /**\r\n * Keycode of key press.\r\n * @type {number}\r\n */\r\n this.keyCode = 0;\r\n\r\n /**\r\n * Keycode of key press.\r\n * @type {number}\r\n */\r\n this.charCode = 0;\r\n\r\n /**\r\n * Whether control was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.ctrlKey = false;\r\n\r\n /**\r\n * Whether alt was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.altKey = false;\r\n\r\n /**\r\n * Whether shift was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.shiftKey = false;\r\n\r\n /**\r\n * Whether the meta key was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.metaKey = false;\r\n\r\n /**\r\n * History state object, only set for PopState events where it's a copy of the\r\n * state object provided to pushState or replaceState.\r\n * @type {?Object}\r\n */\r\n this.state = null;\r\n\r\n /**\r\n * Whether the default platform modifier key was pressed at time of event.\r\n * (This is control for all platforms except Mac, where it's Meta.)\r\n * @type {boolean}\r\n */\r\n this.platformModifierKey = false;\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.pointerId = 0;\r\n\r\n /**\r\n * @type {string}\r\n */\r\n this.pointerType = '';\r\n\r\n /**\r\n * The browser event object.\r\n * @private {?Event}\r\n */\r\n this.event_ = null;\r\n\r\n if (opt_e) {\r\n this.init(opt_e, opt_currentTarget);\r\n }\r\n};\r\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Normalized button constants for the mouse.\r\n * @enum {number}\r\n */\r\ngoog.events.BrowserEvent.MouseButton = {\r\n LEFT: 0,\r\n MIDDLE: 1,\r\n RIGHT: 2\r\n};\r\n\r\n\r\n/**\r\n * Normalized pointer type constants for pointer events.\r\n * @enum {string}\r\n */\r\ngoog.events.BrowserEvent.PointerType = {\r\n MOUSE: 'mouse',\r\n PEN: 'pen',\r\n TOUCH: 'touch'\r\n};\r\n\r\n\r\n/**\r\n * Static data for mapping mouse buttons.\r\n * @type {!Array<number>}\r\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\r\n */\r\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\r\n 1, // LEFT\r\n 4, // MIDDLE\r\n 2 // RIGHT\r\n]);\r\n\r\n\r\n/**\r\n * Static data for mapping mouse buttons.\r\n * @const {!Array<number>}\r\n */\r\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\r\n\r\n\r\n/**\r\n * Static data for mapping MSPointerEvent types to PointerEvent types.\r\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\r\n */\r\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\r\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\r\n 3: goog.events.BrowserEvent.PointerType.PEN,\r\n 4: goog.events.BrowserEvent.PointerType.MOUSE\r\n});\r\n\r\n\r\n/**\r\n * Accepts a browser event object and creates a patched, cross browser event\r\n * object.\r\n * @param {Event} e Browser event object.\r\n * @param {EventTarget=} opt_currentTarget Current target for event.\r\n */\r\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\r\n var type = this.type = e.type;\r\n\r\n /**\r\n * On touch devices use the first \"changed touch\" as the relevant touch.\r\n * @type {?Touch}\r\n */\r\n var relevantTouch =\r\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\r\n\r\n // TODO(nicksantos): Change this.target to type EventTarget.\r\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\r\n\r\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\r\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\r\n\r\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\r\n if (relatedTarget) {\r\n // There's a bug in FireFox where sometimes, relatedTarget will be a\r\n // chrome element, and accessing any property of it will get a permission\r\n // denied exception. See:\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\r\n if (goog.userAgent.GECKO) {\r\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\r\n relatedTarget = null;\r\n }\r\n }\r\n } else if (type == goog.events.EventType.MOUSEOVER) {\r\n relatedTarget = e.fromElement;\r\n } else if (type == goog.events.EventType.MOUSEOUT) {\r\n relatedTarget = e.toElement;\r\n }\r\n\r\n this.relatedTarget = relatedTarget;\r\n\r\n if (relevantTouch) {\r\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\r\n relevantTouch.pageX;\r\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\r\n relevantTouch.pageY;\r\n this.screenX = relevantTouch.screenX || 0;\r\n this.screenY = relevantTouch.screenY || 0;\r\n } else {\r\n if (goog.events.USE_LAYER_XY_AS_OFFSET_XY) {\r\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\r\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\r\n } else {\r\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\r\n // http://code.google.com/p/chromium/issues/detail?id=101733\r\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\r\n e.offsetX :\r\n e.layerX;\r\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\r\n e.offsetY :\r\n e.layerY;\r\n }\r\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\r\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\r\n this.screenX = e.screenX || 0;\r\n this.screenY = e.screenY || 0;\r\n }\r\n\r\n this.button = e.button;\r\n\r\n this.keyCode = e.keyCode || 0;\r\n this.key = e.key || '';\r\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\r\n this.ctrlKey = e.ctrlKey;\r\n this.altKey = e.altKey;\r\n this.shiftKey = e.shiftKey;\r\n this.metaKey = e.metaKey;\r\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\r\n this.pointerId = e.pointerId || 0;\r\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\r\n this.state = e.state;\r\n this.event_ = e;\r\n if (e.defaultPrevented) {\r\n this.preventDefault();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Tests to see which button was pressed during the event. This is really only\r\n * useful in IE and Gecko browsers. And in IE, it's only useful for\r\n * mousedown/mouseup events, because click only fires for the left mouse button.\r\n *\r\n * Safari 2 only reports the left button being clicked, and uses the value '1'\r\n * instead of 0. Opera only reports a mousedown event for the middle button, and\r\n * no mouse events for the right button. Opera has default behavior for left and\r\n * middle click that can only be overridden via a configuration setting.\r\n *\r\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\r\n *\r\n * @param {goog.events.BrowserEvent.MouseButton} button The button\r\n * to test for.\r\n * @return {boolean} True if button was pressed.\r\n */\r\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\r\n if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {\r\n if (this.type == 'click') {\r\n return button == goog.events.BrowserEvent.MouseButton.LEFT;\r\n } else {\r\n return !!(\r\n this.event_.button & goog.events.BrowserEvent.IE_BUTTON_MAP[button]);\r\n }\r\n } else {\r\n return this.event_.button == button;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Whether this has an \"action\"-producing mouse button.\r\n *\r\n * By definition, this includes left-click on windows/linux, and left-click\r\n * without the ctrl key on Macs.\r\n *\r\n * @return {boolean} The result.\r\n */\r\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\r\n // Webkit does not ctrl+click to be a right-click, so we\r\n // normalize it to behave like Gecko and Opera.\r\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\r\n !(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\r\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\r\n if (this.event_.stopPropagation) {\r\n this.event_.stopPropagation();\r\n } else {\r\n this.event_.cancelBubble = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\r\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\r\n var be = this.event_;\r\n if (!be.preventDefault) {\r\n be.returnValue = false;\r\n if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {\r\n\r\n try {\r\n // Most keys can be prevented using returnValue. Some special keys\r\n // require setting the keyCode to -1 as well:\r\n //\r\n // In IE7:\r\n // F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)\r\n //\r\n // In IE8:\r\n // Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)\r\n //\r\n // We therefore do this for all function keys as well as when Ctrl key\r\n // is pressed.\r\n var VK_F1 = 112;\r\n var VK_F12 = 123;\r\n if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {\r\n be.keyCode = -1;\r\n }\r\n } catch (ex) {\r\n // IE throws an 'access denied' exception when trying to change\r\n // keyCode in some situations (e.g. srcElement is input[type=file],\r\n // or srcElement is an anchor tag rewritten by parent's innerHTML).\r\n // Do nothing in this case.\r\n }\r\n }\r\n } else {\r\n be.preventDefault();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {Event} The underlying browser event object.\r\n */\r\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\r\n return this.event_;\r\n};\r\n\r\n\r\n/**\r\n * Extracts the pointer type from the given event.\r\n * @param {!Event} e\r\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\r\n * @private\r\n */\r\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\r\n if (goog.isString(e.pointerType)) {\r\n return e.pointerType;\r\n }\r\n // IE10 uses integer codes for pointer type.\r\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\r\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\r\n};\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Event Types.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.events.EventType');\r\ngoog.provide('goog.events.MouseAsMouseEventType');\r\ngoog.provide('goog.events.MouseEvents');\r\ngoog.provide('goog.events.PointerAsMouseEventType');\r\ngoog.provide('goog.events.PointerAsTouchEventType');\r\ngoog.provide('goog.events.PointerFallbackEventType');\r\ngoog.provide('goog.events.PointerTouchFallbackEventType');\r\n\r\ngoog.require('goog.events.BrowserFeature');\r\ngoog.require('goog.userAgent');\r\n\r\n\r\n/**\r\n * Returns a prefixed event name for the current browser.\r\n * @param {string} eventName The name of the event.\r\n * @return {string} The prefixed event name.\r\n * @suppress {missingRequire|missingProvide}\r\n * @private\r\n */\r\ngoog.events.getVendorPrefixedName_ = function(eventName) {\r\n return goog.userAgent.WEBKIT ?\r\n 'webkit' + eventName :\r\n (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :\r\n eventName.toLowerCase());\r\n};\r\n\r\n\r\n/**\r\n * Constants for event names.\r\n * @enum {string}\r\n */\r\ngoog.events.EventType = {\r\n // Mouse events\r\n CLICK: 'click',\r\n RIGHTCLICK: 'rightclick',\r\n DBLCLICK: 'dblclick',\r\n AUXCLICK: 'auxclick',\r\n MOUSEDOWN: 'mousedown',\r\n MOUSEUP: 'mouseup',\r\n MOUSEOVER: 'mouseover',\r\n MOUSEOUT: 'mouseout',\r\n MOUSEMOVE: 'mousemove',\r\n MOUSEENTER: 'mouseenter',\r\n MOUSELEAVE: 'mouseleave',\r\n\r\n // Non-existent event; will never fire. This exists as a mouse counterpart to\r\n // POINTERCANCEL.\r\n MOUSECANCEL: 'mousecancel',\r\n\r\n // Selection events.\r\n // https://www.w3.org/TR/selection-api/\r\n SELECTIONCHANGE: 'selectionchange',\r\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\r\n\r\n // Wheel events\r\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\r\n WHEEL: 'wheel',\r\n\r\n // Key events\r\n KEYPRESS: 'keypress',\r\n KEYDOWN: 'keydown',\r\n KEYUP: 'keyup',\r\n\r\n // Focus\r\n BLUR: 'blur',\r\n FOCUS: 'focus',\r\n DEACTIVATE: 'deactivate', // IE only\r\n FOCUSIN: 'focusin',\r\n FOCUSOUT: 'focusout',\r\n\r\n // Forms\r\n CHANGE: 'change',\r\n RESET: 'reset',\r\n SELECT: 'select',\r\n SUBMIT: 'submit',\r\n INPUT: 'input',\r\n PROPERTYCHANGE: 'propertychange', // IE only\r\n\r\n // Drag and drop\r\n DRAGSTART: 'dragstart',\r\n DRAG: 'drag',\r\n DRAGENTER: 'dragenter',\r\n DRAGOVER: 'dragover',\r\n DRAGLEAVE: 'dragleave',\r\n DROP: 'drop',\r\n DRAGEND: 'dragend',\r\n\r\n // Touch events\r\n // Note that other touch events exist, but we should follow the W3C list here.\r\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\r\n TOUCHSTART: 'touchstart',\r\n TOUCHMOVE: 'touchmove',\r\n TOUCHEND: 'touchend',\r\n TOUCHCANCEL: 'touchcancel',\r\n\r\n // Misc\r\n BEFOREUNLOAD: 'beforeunload',\r\n CONSOLEMESSAGE: 'consolemessage',\r\n CONTEXTMENU: 'contextmenu',\r\n DEVICECHANGE: 'devicechange',\r\n DEVICEMOTION: 'devicemotion',\r\n DEVICEORIENTATION: 'deviceorientation',\r\n DOMCONTENTLOADED: 'DOMContentLoaded',\r\n ERROR: 'error',\r\n HELP: 'help',\r\n LOAD: 'load',\r\n LOSECAPTURE: 'losecapture',\r\n ORIENTATIONCHANGE: 'orientationchange',\r\n READYSTATECHANGE: 'readystatechange',\r\n RESIZE: 'resize',\r\n SCROLL: 'scroll',\r\n UNLOAD: 'unload',\r\n\r\n // Media events\r\n CANPLAY: 'canplay',\r\n CANPLAYTHROUGH: 'canplaythrough',\r\n DURATIONCHANGE: 'durationchange',\r\n EMPTIED: 'emptied',\r\n ENDED: 'ended',\r\n LOADEDDATA: 'loadeddata',\r\n LOADEDMETADATA: 'loadedmetadata',\r\n PAUSE: 'pause',\r\n PLAY: 'play',\r\n PLAYING: 'playing',\r\n RATECHANGE: 'ratechange',\r\n SEEKED: 'seeked',\r\n SEEKING: 'seeking',\r\n STALLED: 'stalled',\r\n SUSPEND: 'suspend',\r\n TIMEUPDATE: 'timeupdate',\r\n VOLUMECHANGE: 'volumechange',\r\n WAITING: 'waiting',\r\n\r\n // Media Source Extensions events\r\n // https://www.w3.org/TR/media-source/#mediasource-events\r\n SOURCEOPEN: 'sourceopen',\r\n SOURCEENDED: 'sourceended',\r\n SOURCECLOSED: 'sourceclosed',\r\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\r\n ABORT: 'abort',\r\n UPDATE: 'update',\r\n UPDATESTART: 'updatestart',\r\n UPDATEEND: 'updateend',\r\n\r\n // HTML 5 History events\r\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\r\n HASHCHANGE: 'hashchange',\r\n PAGEHIDE: 'pagehide',\r\n PAGESHOW: 'pageshow',\r\n POPSTATE: 'popstate',\r\n\r\n // Copy and Paste\r\n // Support is limited. Make sure it works on your favorite browser\r\n // before using.\r\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\r\n COPY: 'copy',\r\n PASTE: 'paste',\r\n CUT: 'cut',\r\n BEFORECOPY: 'beforecopy',\r\n BEFORECUT: 'beforecut',\r\n BEFOREPASTE: 'beforepaste',\r\n\r\n // HTML5 online/offline events.\r\n // http://www.w3.org/TR/offline-webapps/#related\r\n ONLINE: 'online',\r\n OFFLINE: 'offline',\r\n\r\n // HTML 5 worker events\r\n MESSAGE: 'message',\r\n CONNECT: 'connect',\r\n\r\n // Service Worker Events - ServiceWorkerGlobalScope context\r\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\r\n // Note: message event defined in worker events section\r\n INSTALL: 'install',\r\n ACTIVATE: 'activate',\r\n FETCH: 'fetch',\r\n FOREIGNFETCH: 'foreignfetch',\r\n MESSAGEERROR: 'messageerror',\r\n\r\n // Service Worker Events - Document context\r\n // See https://w3c.github.io/ServiceWorker/#document-context-events\r\n STATECHANGE: 'statechange',\r\n UPDATEFOUND: 'updatefound',\r\n CONTROLLERCHANGE: 'controllerchange',\r\n\r\n // CSS animation events.\r\n /** @suppress {missingRequire} */\r\n ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),\r\n /** @suppress {missingRequire} */\r\n ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),\r\n /** @suppress {missingRequire} */\r\n ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),\r\n\r\n // CSS transition events. Based on the browser support described at:\r\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\r\n /** @suppress {missingRequire} */\r\n TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),\r\n\r\n // W3C Pointer Events\r\n // http://www.w3.org/TR/pointerevents/\r\n POINTERDOWN: 'pointerdown',\r\n POINTERUP: 'pointerup',\r\n POINTERCANCEL: 'pointercancel',\r\n POINTERMOVE: 'pointermove',\r\n POINTEROVER: 'pointerover',\r\n POINTEROUT: 'pointerout',\r\n POINTERENTER: 'pointerenter',\r\n POINTERLEAVE: 'pointerleave',\r\n GOTPOINTERCAPTURE: 'gotpointercapture',\r\n LOSTPOINTERCAPTURE: 'lostpointercapture',\r\n\r\n // IE specific events.\r\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\r\n // Note: these events will be supplanted in IE11.\r\n MSGESTURECHANGE: 'MSGestureChange',\r\n MSGESTUREEND: 'MSGestureEnd',\r\n MSGESTUREHOLD: 'MSGestureHold',\r\n MSGESTURESTART: 'MSGestureStart',\r\n MSGESTURETAP: 'MSGestureTap',\r\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\r\n MSINERTIASTART: 'MSInertiaStart',\r\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\r\n MSPOINTERCANCEL: 'MSPointerCancel',\r\n MSPOINTERDOWN: 'MSPointerDown',\r\n MSPOINTERENTER: 'MSPointerEnter',\r\n MSPOINTERHOVER: 'MSPointerHover',\r\n MSPOINTERLEAVE: 'MSPointerLeave',\r\n MSPOINTERMOVE: 'MSPointerMove',\r\n MSPOINTEROUT: 'MSPointerOut',\r\n MSPOINTEROVER: 'MSPointerOver',\r\n MSPOINTERUP: 'MSPointerUp',\r\n\r\n // Native IMEs/input tools events.\r\n TEXT: 'text',\r\n // The textInput event is supported in IE9+, but only in lower case. All other\r\n // browsers use the camel-case event name.\r\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\r\n COMPOSITIONSTART: 'compositionstart',\r\n COMPOSITIONUPDATE: 'compositionupdate',\r\n COMPOSITIONEND: 'compositionend',\r\n\r\n // The beforeinput event is initially only supported in Safari. See\r\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\r\n // implementation tracking.\r\n BEFOREINPUT: 'beforeinput',\r\n\r\n // Webview tag events\r\n // See https://developer.chrome.com/apps/tags/webview\r\n EXIT: 'exit',\r\n LOADABORT: 'loadabort',\r\n LOADCOMMIT: 'loadcommit',\r\n LOADREDIRECT: 'loadredirect',\r\n LOADSTART: 'loadstart',\r\n LOADSTOP: 'loadstop',\r\n RESPONSIVE: 'responsive',\r\n SIZECHANGED: 'sizechanged',\r\n UNRESPONSIVE: 'unresponsive',\r\n\r\n // HTML5 Page Visibility API. See details at\r\n // `goog.labs.dom.PageVisibilityMonitor`.\r\n VISIBILITYCHANGE: 'visibilitychange',\r\n\r\n // LocalStorage event.\r\n STORAGE: 'storage',\r\n\r\n // DOM Level 2 mutation events (deprecated).\r\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\r\n DOMNODEINSERTED: 'DOMNodeInserted',\r\n DOMNODEREMOVED: 'DOMNodeRemoved',\r\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\r\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\r\n DOMATTRMODIFIED: 'DOMAttrModified',\r\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\r\n\r\n // Print events.\r\n BEFOREPRINT: 'beforeprint',\r\n AFTERPRINT: 'afterprint',\r\n\r\n // Web app manifest events.\r\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\r\n APPINSTALLED: 'appinstalled'\r\n};\r\n\r\n\r\n/**\r\n * Returns one of the given pointer fallback event names in order of preference:\r\n * 1. pointerEventName\r\n * 2. msPointerEventName\r\n * 3. fallbackEventName\r\n * @param {string} pointerEventName\r\n * @param {string} msPointerEventName\r\n * @param {string} fallbackEventName\r\n * @return {string} The supported pointer or fallback (mouse or touch) event\r\n * name.\r\n * @private\r\n */\r\ngoog.events.getPointerFallbackEventName_ = function(\r\n pointerEventName, msPointerEventName, fallbackEventName) {\r\n if (goog.events.BrowserFeature.POINTER_EVENTS) {\r\n return pointerEventName;\r\n }\r\n if (goog.events.BrowserFeature.MSPOINTER_EVENTS) {\r\n return msPointerEventName;\r\n }\r\n return fallbackEventName;\r\n};\r\n\r\n\r\n/**\r\n * Constants for pointer event names that fall back to corresponding mouse event\r\n * names on unsupported platforms. These are intended to be drop-in replacements\r\n * for corresponding values in `goog.events.EventType`.\r\n * @enum {string}\r\n */\r\ngoog.events.PointerFallbackEventType = {\r\n POINTERDOWN: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\r\n goog.events.EventType.MOUSEDOWN),\r\n POINTERUP: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\r\n goog.events.EventType.MOUSEUP),\r\n POINTERCANCEL: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERCANCEL,\r\n goog.events.EventType.MSPOINTERCANCEL,\r\n // When falling back to mouse events, there is no MOUSECANCEL equivalent\r\n // of POINTERCANCEL. In this case POINTERUP already falls back to MOUSEUP\r\n // which represents both UP and CANCEL. POINTERCANCEL does not fall back\r\n // to MOUSEUP to prevent listening twice on the same event.\r\n goog.events.EventType.MOUSECANCEL),\r\n POINTERMOVE: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\r\n goog.events.EventType.MOUSEMOVE),\r\n POINTEROVER: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTEROVER, goog.events.EventType.MSPOINTEROVER,\r\n goog.events.EventType.MOUSEOVER),\r\n POINTEROUT: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTEROUT, goog.events.EventType.MSPOINTEROUT,\r\n goog.events.EventType.MOUSEOUT),\r\n POINTERENTER: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERENTER, goog.events.EventType.MSPOINTERENTER,\r\n goog.events.EventType.MOUSEENTER),\r\n POINTERLEAVE: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERLEAVE, goog.events.EventType.MSPOINTERLEAVE,\r\n goog.events.EventType.MOUSELEAVE)\r\n};\r\n\r\n\r\n/**\r\n * Constants for pointer event names that fall back to corresponding touch event\r\n * names on unsupported platforms. These are intended to be drop-in replacements\r\n * for corresponding values in `goog.events.EventType`.\r\n * @enum {string}\r\n */\r\ngoog.events.PointerTouchFallbackEventType = {\r\n POINTERDOWN: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\r\n goog.events.EventType.TOUCHSTART),\r\n POINTERUP: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\r\n goog.events.EventType.TOUCHEND),\r\n POINTERCANCEL: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERCANCEL,\r\n goog.events.EventType.MSPOINTERCANCEL, goog.events.EventType.TOUCHCANCEL),\r\n POINTERMOVE: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\r\n goog.events.EventType.TOUCHMOVE)\r\n};\r\n\r\n\r\n/**\r\n * Mapping of mouse event names to underlying browser event names.\r\n * @typedef {{\r\n * MOUSEDOWN: string,\r\n * MOUSEUP: string,\r\n * MOUSECANCEL:string,\r\n * MOUSEMOVE:string,\r\n * MOUSEOVER:string,\r\n * MOUSEOUT:string,\r\n * MOUSEENTER:string,\r\n * MOUSELEAVE: string,\r\n * }}\r\n */\r\ngoog.events.MouseEvents;\r\n\r\n\r\n/**\r\n * An alias for `goog.events.EventType.MOUSE*` event types that is overridden by\r\n * corresponding `POINTER*` event types.\r\n * @const {!goog.events.MouseEvents}\r\n */\r\ngoog.events.PointerAsMouseEventType = {\r\n MOUSEDOWN: goog.events.PointerFallbackEventType.POINTERDOWN,\r\n MOUSEUP: goog.events.PointerFallbackEventType.POINTERUP,\r\n MOUSECANCEL: goog.events.PointerFallbackEventType.POINTERCANCEL,\r\n MOUSEMOVE: goog.events.PointerFallbackEventType.POINTERMOVE,\r\n MOUSEOVER: goog.events.PointerFallbackEventType.POINTEROVER,\r\n MOUSEOUT: goog.events.PointerFallbackEventType.POINTEROUT,\r\n MOUSEENTER: goog.events.PointerFallbackEventType.POINTERENTER,\r\n MOUSELEAVE: goog.events.PointerFallbackEventType.POINTERLEAVE\r\n};\r\n\r\n\r\n/**\r\n * An alias for `goog.events.EventType.MOUSE*` event types that continue to use\r\n * mouse events.\r\n * @const {!goog.events.MouseEvents}\r\n */\r\ngoog.events.MouseAsMouseEventType = {\r\n MOUSEDOWN: goog.events.EventType.MOUSEDOWN,\r\n MOUSEUP: goog.events.EventType.MOUSEUP,\r\n MOUSECANCEL: goog.events.EventType.MOUSECANCEL,\r\n MOUSEMOVE: goog.events.EventType.MOUSEMOVE,\r\n MOUSEOVER: goog.events.EventType.MOUSEOVER,\r\n MOUSEOUT: goog.events.EventType.MOUSEOUT,\r\n MOUSEENTER: goog.events.EventType.MOUSEENTER,\r\n MOUSELEAVE: goog.events.EventType.MOUSELEAVE\r\n};\r\n\r\n\r\n/**\r\n * An alias for `goog.events.EventType.TOUCH*` event types that is overridden by\r\n * corresponding `POINTER*` event types.\r\n * @enum {string}\r\n */\r\ngoog.events.PointerAsTouchEventType = {\r\n TOUCHCANCEL: goog.events.PointerTouchFallbackEventType.POINTERCANCEL,\r\n TOUCHEND: goog.events.PointerTouchFallbackEventType.POINTERUP,\r\n TOUCHMOVE: goog.events.PointerTouchFallbackEventType.POINTERMOVE,\r\n TOUCHSTART: goog.events.PointerTouchFallbackEventType.POINTERDOWN\r\n};\r\n","// Copyright 2012 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview An interface for a listenable JavaScript object.\r\n * @author chrishenry@google.com (Chris Henry)\r\n */\r\n\r\ngoog.provide('goog.events.Listenable');\r\ngoog.provide('goog.events.ListenableKey');\r\n\r\n/** @suppress {extraRequire} */\r\ngoog.require('goog.events.EventId');\r\n\r\ngoog.forwardDeclare('goog.events.EventLike');\r\ngoog.forwardDeclare('goog.events.EventTarget');\r\n\r\n\r\n\r\n/**\r\n * A listenable interface. A listenable is an object with the ability\r\n * to dispatch/broadcast events to \"event listeners\" registered via\r\n * listen/listenOnce.\r\n *\r\n * The interface allows for an event propagation mechanism similar\r\n * to one offered by native browser event targets, such as\r\n * capture/bubble mechanism, stopping propagation, and preventing\r\n * default actions. Capture/bubble mechanism depends on the ancestor\r\n * tree constructed via `#getParentEventTarget`; this tree\r\n * must be directed acyclic graph. The meaning of default action(s)\r\n * in preventDefault is specific to a particular use case.\r\n *\r\n * Implementations that do not support capture/bubble or can not have\r\n * a parent listenable can simply not implement any ability to set the\r\n * parent listenable (and have `#getParentEventTarget` return\r\n * null).\r\n *\r\n * Implementation of this class can be used with or independently from\r\n * goog.events.\r\n *\r\n * Implementation must call `#addImplementation(implClass)`.\r\n *\r\n * @interface\r\n * @see goog.events\r\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\r\n */\r\ngoog.events.Listenable = function() {};\r\n\r\n\r\n/**\r\n * An expando property to indicate that an object implements\r\n * goog.events.Listenable.\r\n *\r\n * See addImplementation/isImplementedBy.\r\n *\r\n * @type {string}\r\n * @const\r\n */\r\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\r\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\r\n\r\n\r\n/**\r\n * Marks a given class (constructor) as an implementation of\r\n * Listenable, so that we can query that fact at runtime. The class\r\n * must have already implemented the interface.\r\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\r\n * The corresponding class must have already implemented the interface.\r\n */\r\ngoog.events.Listenable.addImplementation = function(cls) {\r\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\r\n};\r\n\r\n\r\n/**\r\n * @param {Object} obj The object to check.\r\n * @return {boolean} Whether a given instance implements Listenable. The\r\n * class/superclass of the instance must call addImplementation.\r\n */\r\ngoog.events.Listenable.isImplementedBy = function(obj) {\r\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener. A listener can only be added once to an\r\n * object and if it is added again the key for the listener is\r\n * returned. Note that if the existing listener is a one-off listener\r\n * (registered via listenOnce), it will no longer be a one-off\r\n * listener after a call to listen().\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\r\n * method.\r\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\r\n * (defaults to false).\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {!goog.events.ListenableKey} Unique key for the listener.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.listen;\r\n\r\n\r\n/**\r\n * Adds an event listener that is removed automatically after the\r\n * listener fired once.\r\n *\r\n * If an existing listener already exists, listenOnce will do\r\n * nothing. In particular, if the listener was previously registered\r\n * via listen(), listenOnce() will not turn the listener into a\r\n * one-off listener. Similarly, if there is already an existing\r\n * one-off listener, listenOnce does not modify the listeners (it is\r\n * still a once listener).\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\r\n * method.\r\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\r\n * (defaults to false).\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {!goog.events.ListenableKey} Unique key for the listener.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.listenOnce;\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen() or listenOnce().\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\r\n * method.\r\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\r\n * (defaults to false).\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\r\n * the listener.\r\n * @return {boolean} Whether any listener was removed.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.unlisten;\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen() by the key\r\n * returned by listen().\r\n *\r\n * @param {!goog.events.ListenableKey} key The key returned by\r\n * listen() or listenOnce().\r\n * @return {boolean} Whether any listener was removed.\r\n */\r\ngoog.events.Listenable.prototype.unlistenByKey;\r\n\r\n\r\n/**\r\n * Dispatches an event (or event like object) and calls all listeners\r\n * listening for events of this type. The type of the event is decided by the\r\n * type property on the event object.\r\n *\r\n * If any of the listeners returns false OR calls preventDefault then this\r\n * function will return false. If one of the capture listeners calls\r\n * stopPropagation, then the bubble listeners won't fire.\r\n *\r\n * @param {goog.events.EventLike} e Event object.\r\n * @return {boolean} If anyone called preventDefault on the event object (or\r\n * if any of the listeners returns false) this will also return false.\r\n */\r\ngoog.events.Listenable.prototype.dispatchEvent;\r\n\r\n\r\n/**\r\n * Removes all listeners from this listenable. If type is specified,\r\n * it will only remove listeners of the particular type. otherwise all\r\n * registered listeners will be removed.\r\n *\r\n * @param {string=} opt_type Type of event to remove, default is to\r\n * remove all types.\r\n * @return {number} Number of listeners removed.\r\n */\r\ngoog.events.Listenable.prototype.removeAllListeners;\r\n\r\n\r\n/**\r\n * Returns the parent of this event target to use for capture/bubble\r\n * mechanism.\r\n *\r\n * NOTE(chrishenry): The name reflects the original implementation of\r\n * custom event target (`goog.events.EventTarget`). We decided\r\n * that changing the name is not worth it.\r\n *\r\n * @return {goog.events.Listenable} The parent EventTarget or null if\r\n * there is no parent.\r\n */\r\ngoog.events.Listenable.prototype.getParentEventTarget;\r\n\r\n\r\n/**\r\n * Fires all registered listeners in this listenable for the given\r\n * type and capture mode, passing them the given eventObject. This\r\n * does not perform actual capture/bubble. Only implementors of the\r\n * interface should be using this.\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\r\n * listeners to fire.\r\n * @param {boolean} capture The capture mode of the listeners to fire.\r\n * @param {EVENTOBJ} eventObject The event object to fire.\r\n * @return {boolean} Whether all listeners succeeded without\r\n * attempting to prevent default behavior. If any listener returns\r\n * false or called goog.events.Event#preventDefault, this returns\r\n * false.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.fireListeners;\r\n\r\n\r\n/**\r\n * Gets all listeners in this listenable for the given type and\r\n * capture mode.\r\n *\r\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\r\n * @param {boolean} capture The capture mode of the listeners to fire.\r\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\r\n * listeners.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.getListeners;\r\n\r\n\r\n/**\r\n * Gets the goog.events.ListenableKey for the event or null if no such\r\n * listener is in use.\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\r\n * without the 'on' prefix.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\r\n * listener function to get.\r\n * @param {boolean} capture Whether the listener is a capturing listener.\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {goog.events.ListenableKey} the found listener or null if not found.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.getListener;\r\n\r\n\r\n/**\r\n * Whether there is any active listeners matching the specified\r\n * signature. If either the type or capture parameters are\r\n * unspecified, the function will match on the remaining criteria.\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\r\n * @param {boolean=} opt_capture Whether to check for capture or bubble\r\n * listeners.\r\n * @return {boolean} Whether there is any active listeners matching\r\n * the requested type and/or capture phase.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.hasListener;\r\n\r\n\r\n\r\n/**\r\n * An interface that describes a single registered listener.\r\n * @interface\r\n */\r\ngoog.events.ListenableKey = function() {};\r\n\r\n\r\n/**\r\n * Counter used to create a unique key\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.events.ListenableKey.counter_ = 0;\r\n\r\n\r\n/**\r\n * Reserves a key to be used for ListenableKey#key field.\r\n * @return {number} A number to be used to fill ListenableKey#key\r\n * field.\r\n */\r\ngoog.events.ListenableKey.reserveKey = function() {\r\n return ++goog.events.ListenableKey.counter_;\r\n};\r\n\r\n\r\n/**\r\n * The source event target.\r\n * @type {Object|goog.events.Listenable|goog.events.EventTarget}\r\n */\r\ngoog.events.ListenableKey.prototype.src;\r\n\r\n\r\n/**\r\n * The event type the listener is listening to.\r\n * @type {string}\r\n */\r\ngoog.events.ListenableKey.prototype.type;\r\n\r\n\r\n/**\r\n * The listener function.\r\n * @type {function(?):?|{handleEvent:function(?):?}|null}\r\n */\r\ngoog.events.ListenableKey.prototype.listener;\r\n\r\n\r\n/**\r\n * Whether the listener works on capture phase.\r\n * @type {boolean}\r\n */\r\ngoog.events.ListenableKey.prototype.capture;\r\n\r\n\r\n/**\r\n * The 'this' object for the listener function's scope.\r\n * @type {Object|undefined}\r\n */\r\ngoog.events.ListenableKey.prototype.handler;\r\n\r\n\r\n/**\r\n * A globally unique number to identify the key.\r\n * @type {number}\r\n */\r\ngoog.events.ListenableKey.prototype.key;\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Listener object.\r\n * @see ../demos/events.html\r\n */\r\n\r\ngoog.provide('goog.events.Listener');\r\n\r\ngoog.require('goog.events.ListenableKey');\r\n\r\n\r\n\r\n/**\r\n * Simple class that stores information about a listener\r\n * @param {function(?):?} listener Callback function.\r\n * @param {Function} proxy Wrapper for the listener that patches the event.\r\n * @param {EventTarget|goog.events.Listenable} src Source object for\r\n * the event.\r\n * @param {string} type Event type.\r\n * @param {boolean} capture Whether in capture or bubble phase.\r\n * @param {Object=} opt_handler Object in whose context to execute the callback.\r\n * @implements {goog.events.ListenableKey}\r\n * @constructor\r\n */\r\ngoog.events.Listener = function(\r\n listener, proxy, src, type, capture, opt_handler) {\r\n if (goog.events.Listener.ENABLE_MONITORING) {\r\n this.creationStack = new Error().stack;\r\n }\r\n\r\n /** @override */\r\n this.listener = listener;\r\n\r\n /**\r\n * A wrapper over the original listener. This is used solely to\r\n * handle native browser events (it is used to simulate the capture\r\n * phase and to patch the event object).\r\n * @type {Function}\r\n */\r\n this.proxy = proxy;\r\n\r\n /**\r\n * Object or node that callback is listening to\r\n * @type {EventTarget|goog.events.Listenable}\r\n */\r\n this.src = src;\r\n\r\n /**\r\n * The event type.\r\n * @const {string}\r\n */\r\n this.type = type;\r\n\r\n /**\r\n * Whether the listener is being called in the capture or bubble phase\r\n * @const {boolean}\r\n */\r\n this.capture = !!capture;\r\n\r\n /**\r\n * Optional object whose context to execute the listener in\r\n * @type {Object|undefined}\r\n */\r\n this.handler = opt_handler;\r\n\r\n /**\r\n * The key of the listener.\r\n * @const {number}\r\n * @override\r\n */\r\n this.key = goog.events.ListenableKey.reserveKey();\r\n\r\n /**\r\n * Whether to remove the listener after it has been called.\r\n * @type {boolean}\r\n */\r\n this.callOnce = false;\r\n\r\n /**\r\n * Whether the listener has been removed.\r\n * @type {boolean}\r\n */\r\n this.removed = false;\r\n};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to enable the monitoring of the\r\n * goog.events.Listener instances. Switching on the monitoring is only\r\n * recommended for debugging because it has a significant impact on\r\n * performance and memory usage. If switched off, the monitoring code\r\n * compiles down to 0 bytes.\r\n */\r\ngoog.events.Listener.ENABLE_MONITORING =\r\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\r\n\r\n\r\n/**\r\n * If monitoring the goog.events.Listener instances is enabled, stores the\r\n * creation stack trace of the Disposable instance.\r\n * @type {string}\r\n */\r\ngoog.events.Listener.prototype.creationStack;\r\n\r\n\r\n/**\r\n * Marks this listener as removed. This also remove references held by\r\n * this listener object (such as listener and event source).\r\n */\r\ngoog.events.Listener.prototype.markAsRemoved = function() {\r\n this.removed = true;\r\n this.listener = null;\r\n this.proxy = null;\r\n this.src = null;\r\n this.handler = null;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A map of listeners that provides utility functions to\r\n * deal with listeners on an event target. Used by\r\n * `goog.events.EventTarget`.\r\n *\r\n * WARNING: Do not use this class from outside goog.events package.\r\n */\r\n\r\ngoog.provide('goog.events.ListenerMap');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.events.Listener');\r\ngoog.require('goog.object');\r\n\r\n\r\n\r\n/**\r\n * Creates a new listener map.\r\n * @param {EventTarget|goog.events.Listenable} src The src object.\r\n * @constructor\r\n * @final\r\n */\r\ngoog.events.ListenerMap = function(src) {\r\n /** @type {EventTarget|goog.events.Listenable} */\r\n this.src = src;\r\n\r\n /**\r\n * Maps of event type to an array of listeners.\r\n * @type {!Object<string, !Array<!goog.events.Listener>>}\r\n */\r\n this.listeners = {};\r\n\r\n /**\r\n * The count of types in this map that have registered listeners.\r\n * @private {number}\r\n */\r\n this.typeCount_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The count of event types in this map that actually\r\n * have registered listeners.\r\n */\r\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\r\n return this.typeCount_;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} Total number of registered listeners.\r\n */\r\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\r\n var count = 0;\r\n for (var type in this.listeners) {\r\n count += this.listeners[type].length;\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener. A listener can only be added once to an\r\n * object and if it is added again the key for the listener is\r\n * returned.\r\n *\r\n * Note that a one-off listener will not change an existing listener,\r\n * if any. On the other hand a normal listener will change existing\r\n * one-off listener to become a normal listener.\r\n *\r\n * @param {string|!goog.events.EventId} type The listener event type.\r\n * @param {!Function} listener This listener callback method.\r\n * @param {boolean} callOnce Whether the listener is a one-off\r\n * listener.\r\n * @param {boolean=} opt_useCapture The capture mode of the listener.\r\n * @param {Object=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {!goog.events.ListenableKey} Unique key for the listener.\r\n */\r\ngoog.events.ListenerMap.prototype.add = function(\r\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\r\n var typeStr = type.toString();\r\n var listenerArray = this.listeners[typeStr];\r\n if (!listenerArray) {\r\n listenerArray = this.listeners[typeStr] = [];\r\n this.typeCount_++;\r\n }\r\n\r\n var listenerObj;\r\n var index = goog.events.ListenerMap.findListenerIndex_(\r\n listenerArray, listener, opt_useCapture, opt_listenerScope);\r\n if (index > -1) {\r\n listenerObj = listenerArray[index];\r\n if (!callOnce) {\r\n // Ensure that, if there is an existing callOnce listener, it is no\r\n // longer a callOnce listener.\r\n listenerObj.callOnce = false;\r\n }\r\n } else {\r\n listenerObj = new goog.events.Listener(\r\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\r\n listenerObj.callOnce = callOnce;\r\n listenerArray.push(listenerObj);\r\n }\r\n return listenerObj;\r\n};\r\n\r\n\r\n/**\r\n * Removes a matching listener.\r\n * @param {string|!goog.events.EventId} type The listener event type.\r\n * @param {!Function} listener This listener callback method.\r\n * @param {boolean=} opt_useCapture The capture mode of the listener.\r\n * @param {Object=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {boolean} Whether any listener was removed.\r\n */\r\ngoog.events.ListenerMap.prototype.remove = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n var typeStr = type.toString();\r\n if (!(typeStr in this.listeners)) {\r\n return false;\r\n }\r\n\r\n var listenerArray = this.listeners[typeStr];\r\n var index = goog.events.ListenerMap.findListenerIndex_(\r\n listenerArray, listener, opt_useCapture, opt_listenerScope);\r\n if (index > -1) {\r\n var listenerObj = listenerArray[index];\r\n listenerObj.markAsRemoved();\r\n goog.array.removeAt(listenerArray, index);\r\n if (listenerArray.length == 0) {\r\n delete this.listeners[typeStr];\r\n this.typeCount_--;\r\n }\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes the given listener object.\r\n * @param {!goog.events.ListenableKey} listener The listener to remove.\r\n * @return {boolean} Whether the listener is removed.\r\n */\r\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\r\n var type = listener.type;\r\n if (!(type in this.listeners)) {\r\n return false;\r\n }\r\n\r\n var removed = goog.array.remove(this.listeners[type], listener);\r\n if (removed) {\r\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\r\n if (this.listeners[type].length == 0) {\r\n delete this.listeners[type];\r\n this.typeCount_--;\r\n }\r\n }\r\n return removed;\r\n};\r\n\r\n\r\n/**\r\n * Removes all listeners from this map. If opt_type is provided, only\r\n * listeners that match the given type are removed.\r\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\r\n * @return {number} Number of listeners removed.\r\n */\r\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\r\n var typeStr = opt_type && opt_type.toString();\r\n var count = 0;\r\n for (var type in this.listeners) {\r\n if (!typeStr || type == typeStr) {\r\n var listenerArray = this.listeners[type];\r\n for (var i = 0; i < listenerArray.length; i++) {\r\n ++count;\r\n listenerArray[i].markAsRemoved();\r\n }\r\n delete this.listeners[type];\r\n this.typeCount_--;\r\n }\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Gets all listeners that match the given type and capture mode. The\r\n * returned array is a copy (but the listener objects are not).\r\n * @param {string|!goog.events.EventId} type The type of the listeners\r\n * to retrieve.\r\n * @param {boolean} capture The capture mode of the listeners to retrieve.\r\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\r\n * listeners.\r\n */\r\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\r\n var listenerArray = this.listeners[type.toString()];\r\n var rv = [];\r\n if (listenerArray) {\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n var listenerObj = listenerArray[i];\r\n if (listenerObj.capture == capture) {\r\n rv.push(listenerObj);\r\n }\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Gets the goog.events.ListenableKey for the event or null if no such\r\n * listener is in use.\r\n *\r\n * @param {string|!goog.events.EventId} type The type of the listener\r\n * to retrieve.\r\n * @param {!Function} listener The listener function to get.\r\n * @param {boolean} capture Whether the listener is a capturing listener.\r\n * @param {Object=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {goog.events.ListenableKey} the found listener or null if not found.\r\n */\r\ngoog.events.ListenerMap.prototype.getListener = function(\r\n type, listener, capture, opt_listenerScope) {\r\n var listenerArray = this.listeners[type.toString()];\r\n var i = -1;\r\n if (listenerArray) {\r\n i = goog.events.ListenerMap.findListenerIndex_(\r\n listenerArray, listener, capture, opt_listenerScope);\r\n }\r\n return i > -1 ? listenerArray[i] : null;\r\n};\r\n\r\n\r\n/**\r\n * Whether there is a matching listener. If either the type or capture\r\n * parameters are unspecified, the function will match on the\r\n * remaining criteria.\r\n *\r\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\r\n * @param {boolean=} opt_capture The capture mode of the listener.\r\n * @return {boolean} Whether there is an active listener matching\r\n * the requested type and/or capture phase.\r\n */\r\ngoog.events.ListenerMap.prototype.hasListener = function(\r\n opt_type, opt_capture) {\r\n var hasType = goog.isDef(opt_type);\r\n var typeStr = hasType ? opt_type.toString() : '';\r\n var hasCapture = goog.isDef(opt_capture);\r\n\r\n return goog.object.some(this.listeners, function(listenerArray, type) {\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n if ((!hasType || listenerArray[i].type == typeStr) &&\r\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Finds the index of a matching goog.events.Listener in the given\r\n * listenerArray.\r\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\r\n * @param {!Function} listener The listener function.\r\n * @param {boolean=} opt_useCapture The capture flag for the listener.\r\n * @param {Object=} opt_listenerScope The listener scope.\r\n * @return {number} The index of the matching listener within the\r\n * listenerArray.\r\n * @private\r\n */\r\ngoog.events.ListenerMap.findListenerIndex_ = function(\r\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n var listenerObj = listenerArray[i];\r\n if (!listenerObj.removed && listenerObj.listener == listener &&\r\n listenerObj.capture == !!opt_useCapture &&\r\n listenerObj.handler == opt_listenerScope) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n};\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview An event manager for both native browser event\r\n * targets and custom JavaScript event targets\r\n * (`goog.events.Listenable`). This provides an abstraction\r\n * over browsers' event systems.\r\n *\r\n * It also provides a simulation of W3C event model's capture phase in\r\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\r\n * interact well with listeners registered directly on the elements\r\n * (bypassing goog.events) or even with listeners registered via\r\n * goog.events in a separate JS binary. In these cases, we provide\r\n * no ordering guarantees.\r\n *\r\n * The listeners will receive a \"patched\" event object. Such event object\r\n * contains normalized values for certain event properties that differs in\r\n * different browsers.\r\n *\r\n * Example usage:\r\n * <pre>\r\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\r\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\r\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\r\n * goog.events.removeAll(myNode);\r\n * </pre>\r\n *\r\n * in IE and event object patching]\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * @see ../demos/events.html\r\n * @see ../demos/event-propagation.html\r\n * @see ../demos/stopevent.html\r\n */\r\n\r\n// IMPLEMENTATION NOTES:\r\n// goog.events stores an auxiliary data structure on each EventTarget\r\n// source being listened on. This allows us to take advantage of GC,\r\n// having the data structure GC'd when the EventTarget is GC'd. This\r\n// GC behavior is equivalent to using W3C DOM Events directly.\r\n\r\ngoog.provide('goog.events');\r\ngoog.provide('goog.events.CaptureSimulationMode');\r\ngoog.provide('goog.events.Key');\r\ngoog.provide('goog.events.ListenableType');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.debug.entryPointRegistry');\r\ngoog.require('goog.events.BrowserEvent');\r\ngoog.require('goog.events.BrowserFeature');\r\ngoog.require('goog.events.Listenable');\r\ngoog.require('goog.events.ListenerMap');\r\n\r\ngoog.forwardDeclare('goog.debug.ErrorHandler');\r\ngoog.forwardDeclare('goog.events.EventWrapper');\r\n\r\n\r\n/**\r\n * @typedef {number|goog.events.ListenableKey}\r\n */\r\ngoog.events.Key;\r\n\r\n\r\n/**\r\n * @typedef {EventTarget|goog.events.Listenable}\r\n */\r\ngoog.events.ListenableType;\r\n\r\n\r\n/**\r\n * Property name on a native event target for the listener map\r\n * associated with the event target.\r\n * @private @const {string}\r\n */\r\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\r\n\r\n\r\n/**\r\n * String used to prepend to IE event types.\r\n * @const\r\n * @private\r\n */\r\ngoog.events.onString_ = 'on';\r\n\r\n\r\n/**\r\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\r\n * this removes an extra object allocation in goog.events.listen which\r\n * improves IE6 performance.\r\n * @const\r\n * @dict\r\n * @private\r\n */\r\ngoog.events.onStringMap_ = {};\r\n\r\n\r\n/**\r\n * @enum {number} Different capture simulation mode for IE8-.\r\n */\r\ngoog.events.CaptureSimulationMode = {\r\n /**\r\n * Does not perform capture simulation. Will asserts in IE8- when you\r\n * add capture listeners.\r\n */\r\n OFF_AND_FAIL: 0,\r\n\r\n /**\r\n * Does not perform capture simulation, silently ignore capture\r\n * listeners.\r\n */\r\n OFF_AND_SILENT: 1,\r\n\r\n /**\r\n * Performs capture simulation.\r\n */\r\n ON: 2\r\n};\r\n\r\n\r\n/**\r\n * @define {number} The capture simulation mode for IE8-. By default,\r\n * this is ON.\r\n */\r\ngoog.events.CAPTURE_SIMULATION_MODE =\r\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\r\n\r\n\r\n/**\r\n * Estimated count of total native listeners.\r\n * @private {number}\r\n */\r\ngoog.events.listenerCountEstimate_ = 0;\r\n\r\n\r\n/**\r\n * Adds an event listener for a specific event on a native event\r\n * target (such as a DOM element) or an object that has implemented\r\n * {@link goog.events.Listenable}. A listener can only be added once\r\n * to an object and if it is added again the key for the listener is\r\n * returned. Note that if the existing listener is a one-off listener\r\n * (registered via listenOnce), it will no longer be a one-off\r\n * listener after a call to listen().\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The node to listen\r\n * to events on.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\r\n * listener Callback method, or an object with a handleEvent function.\r\n * WARNING: passing an Object is now softly deprecated.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {T=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.Key} Unique key for the listener.\r\n * @template T,EVENTOBJ\r\n */\r\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\r\n if (opt_options && opt_options.once) {\r\n return goog.events.listenOnce(\r\n src, type, listener, opt_options, opt_handler);\r\n }\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\r\n }\r\n return null;\r\n }\r\n\r\n listener = goog.events.wrapListener(listener);\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n return src.listen(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n } else {\r\n return goog.events.listen_(\r\n /** @type {!EventTarget} */ (src), type, listener,\r\n /* callOnce */ false, opt_options, opt_handler);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener for a specific event on a native event\r\n * target. A listener can only be added once to an object and if it\r\n * is added again the key for the listener is returned.\r\n *\r\n * Note that a one-off listener will not change an existing listener,\r\n * if any. On the other hand a normal listener will change existing\r\n * one-off listener to become a normal listener.\r\n *\r\n * @param {EventTarget} src The node to listen to events on.\r\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\r\n * @param {!Function} listener Callback function.\r\n * @param {boolean} callOnce Whether the listener is a one-off\r\n * listener or otherwise.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.ListenableKey} Unique key for the listener.\r\n * @template EVENTOBJ\r\n * @private\r\n */\r\ngoog.events.listen_ = function(\r\n src, type, listener, callOnce, opt_options, opt_handler) {\r\n if (!type) {\r\n throw new Error('Invalid event type');\r\n }\r\n\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n if (capture && !goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {\r\n if (goog.events.CAPTURE_SIMULATION_MODE ==\r\n goog.events.CaptureSimulationMode.OFF_AND_FAIL) {\r\n goog.asserts.fail('Can not register capture listener in IE8-.');\r\n return null;\r\n } else if (\r\n goog.events.CAPTURE_SIMULATION_MODE ==\r\n goog.events.CaptureSimulationMode.OFF_AND_SILENT) {\r\n return null;\r\n }\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(src);\r\n if (!listenerMap) {\r\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\r\n new goog.events.ListenerMap(src);\r\n }\r\n\r\n var listenerObj = /** @type {goog.events.Listener} */ (\r\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\r\n\r\n // If the listenerObj already has a proxy, it has been set up\r\n // previously. We simply return.\r\n if (listenerObj.proxy) {\r\n return listenerObj;\r\n }\r\n\r\n var proxy = goog.events.getProxy();\r\n listenerObj.proxy = proxy;\r\n\r\n proxy.src = src;\r\n proxy.listener = listenerObj;\r\n\r\n // Attach the proxy through the browser's API\r\n if (src.addEventListener) {\r\n // Don't pass an object as `capture` if the browser doesn't support that.\r\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\r\n opt_options = capture;\r\n }\r\n // Don't break tests that expect a boolean.\r\n if (opt_options === undefined) opt_options = false;\r\n src.addEventListener(type.toString(), proxy, opt_options);\r\n } else if (src.attachEvent) {\r\n // The else if above used to be an unconditional else. It would call\r\n // exception on IE11, spoiling the day of some callers. The previous\r\n // incarnation of this code, from 2007, indicates that it replaced an\r\n // earlier still version that caused excess allocations on IE6.\r\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\r\n } else if (src.addListener && src.removeListener) {\r\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\r\n // Safari, there is no global for the MediaQueryList constructor, so we just\r\n // check whether the object \"looks like\" MediaQueryList.\r\n goog.asserts.assert(\r\n type === 'change', 'MediaQueryList only has a change event');\r\n src.addListener(proxy);\r\n } else {\r\n throw new Error('addEventListener and attachEvent are unavailable.');\r\n }\r\n\r\n goog.events.listenerCountEstimate_++;\r\n return listenerObj;\r\n};\r\n\r\n\r\n/**\r\n * Helper function for returning a proxy function.\r\n * @return {!Function} A new or reused function object.\r\n */\r\ngoog.events.getProxy = function() {\r\n var proxyCallbackFunction = goog.events.handleBrowserEvent_;\r\n // Use a local var f to prevent one allocation.\r\n var f =\r\n goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT ? function(eventObject) {\r\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\r\n } : function(eventObject) {\r\n var v = proxyCallbackFunction.call(f.src, f.listener, eventObject);\r\n // NOTE(chrishenry): In IE, we hack in a capture phase. However, if\r\n // there is inline event handler which tries to prevent default (for\r\n // example <a href=\"...\" onclick=\"return false\">...</a>) in a\r\n // descendant element, the prevent default will be overridden\r\n // by this listener if this listener were to return true. Hence, we\r\n // return undefined.\r\n if (!v) return v;\r\n };\r\n return f;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener for a specific event on a native event\r\n * target (such as a DOM element) or an object that has implemented\r\n * {@link goog.events.Listenable}. After the event has fired the event\r\n * listener is removed from the target.\r\n *\r\n * If an existing listener already exists, listenOnce will do\r\n * nothing. In particular, if the listener was previously registered\r\n * via listen(), listenOnce() will not turn the listener into a\r\n * one-off listener. Similarly, if there is already an existing\r\n * one-off listener, listenOnce does not modify the listeners (it is\r\n * still a once listener).\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The node to listen\r\n * to events on.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\r\n * listener Callback method.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {T=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.Key} Unique key for the listener.\r\n * @template T,EVENTOBJ\r\n */\r\ngoog.events.listenOnce = function(\r\n src, type, listener, opt_options, opt_handler) {\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\r\n }\r\n return null;\r\n }\r\n\r\n listener = goog.events.wrapListener(listener);\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n return src.listenOnce(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n } else {\r\n return goog.events.listen_(\r\n /** @type {!EventTarget} */ (src), type, listener,\r\n /* callOnce */ true, opt_options, opt_handler);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.Listenable}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target to\r\n * listen to events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\r\n * Callback method, or an object with a handleEvent function.\r\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\r\n * false).\r\n * @param {T=} opt_handler Element in whose scope to call the listener.\r\n * @template T\r\n */\r\ngoog.events.listenWithWrapper = function(\r\n src, wrapper, listener, opt_capt, opt_handler) {\r\n wrapper.listen(src, listener, opt_capt, opt_handler);\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen().\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target to stop\r\n * listening to events on.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types to unlisten to.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to remove.\r\n * @param {(boolean|!EventListenerOptions)=} opt_options\r\n * whether the listener is fired during the capture or bubble phase of the\r\n * event.\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n * @return {?boolean} indicating whether the listener was there to remove.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\r\n }\r\n return null;\r\n }\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n\r\n listener = goog.events.wrapListener(listener);\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n return src.unlisten(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n }\r\n\r\n if (!src) {\r\n // TODO(chrishenry): We should tighten the API to only accept\r\n // non-null objects, or add an assertion here.\r\n return false;\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (src));\r\n if (listenerMap) {\r\n var listenerObj = listenerMap.getListener(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n if (listenerObj) {\r\n return goog.events.unlistenByKey(listenerObj);\r\n }\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen() by the key\r\n * returned by listen().\r\n *\r\n * @param {goog.events.Key} key The key returned by listen() for this\r\n * event listener.\r\n * @return {boolean} indicating whether the listener was there to remove.\r\n */\r\ngoog.events.unlistenByKey = function(key) {\r\n // TODO(chrishenry): Remove this check when tests that rely on this\r\n // are fixed.\r\n if (goog.isNumber(key)) {\r\n return false;\r\n }\r\n\r\n var listener = key;\r\n if (!listener || listener.removed) {\r\n return false;\r\n }\r\n\r\n var src = listener.src;\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\r\n }\r\n\r\n var type = listener.type;\r\n var proxy = listener.proxy;\r\n if (src.removeEventListener) {\r\n src.removeEventListener(type, proxy, listener.capture);\r\n } else if (src.detachEvent) {\r\n src.detachEvent(goog.events.getOnString_(type), proxy);\r\n } else if (src.addListener && src.removeListener) {\r\n src.removeListener(proxy);\r\n }\r\n goog.events.listenerCountEstimate_--;\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (src));\r\n // TODO(chrishenry): Try to remove this conditional and execute the\r\n // first branch always. This should be safe.\r\n if (listenerMap) {\r\n listenerMap.removeByKey(listener);\r\n if (listenerMap.getTypeCount() == 0) {\r\n // Null the src, just because this is simple to do (and useful\r\n // for IE <= 7).\r\n listenerMap.src = null;\r\n // We don't use delete here because IE does not allow delete\r\n // on a window object.\r\n src[goog.events.LISTENER_MAP_PROP_] = null;\r\n }\r\n } else {\r\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\r\n }\r\n\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listenWithWrapper().\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target to stop\r\n * listening to events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to remove.\r\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase of the\r\n * event.\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n */\r\ngoog.events.unlistenWithWrapper = function(\r\n src, wrapper, listener, opt_capt, opt_handler) {\r\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\r\n};\r\n\r\n\r\n/**\r\n * Removes all listeners from an object. You can also optionally\r\n * remove listeners of a particular type.\r\n *\r\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\r\n * EventTarget or a goog.events.Listenable.\r\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\r\n * Default is all types.\r\n * @return {number} Number of listeners removed.\r\n */\r\ngoog.events.removeAll = function(obj, opt_type) {\r\n // TODO(chrishenry): Change the type of obj to\r\n // (!EventTarget|!goog.events.Listenable).\r\n\r\n if (!obj) {\r\n return 0;\r\n }\r\n\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (obj));\r\n if (!listenerMap) {\r\n return 0;\r\n }\r\n\r\n var count = 0;\r\n var typeStr = opt_type && opt_type.toString();\r\n for (var type in listenerMap.listeners) {\r\n if (!typeStr || type == typeStr) {\r\n // Clone so that we don't need to worry about unlistenByKey\r\n // changing the content of the ListenerMap.\r\n var listeners = listenerMap.listeners[type].concat();\r\n for (var i = 0; i < listeners.length; ++i) {\r\n if (goog.events.unlistenByKey(listeners[i])) {\r\n ++count;\r\n }\r\n }\r\n }\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Gets the listeners for a given object, type and capture phase.\r\n *\r\n * @param {Object} obj Object to get listeners for.\r\n * @param {string|!goog.events.EventId} type Event type.\r\n * @param {boolean} capture Capture phase?.\r\n * @return {Array<!goog.events.Listener>} Array of listener objects.\r\n */\r\ngoog.events.getListeners = function(obj, type, capture) {\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\r\n type, capture);\r\n } else {\r\n if (!obj) {\r\n // TODO(chrishenry): We should tighten the API to accept\r\n // !EventTarget|goog.events.Listenable, and add an assertion here.\r\n return [];\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (obj));\r\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Gets the goog.events.Listener for the event or null if no such listener is\r\n * in use.\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target from\r\n * which to get listeners.\r\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\r\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to get.\r\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the\r\n * capture or bubble phase of the event.\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.ListenableKey} the found listener or null if not found.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\r\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\r\n type = /** @type {string} */ (type);\r\n listener = goog.events.wrapListener(listener);\r\n var capture = !!opt_capt;\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n return src.getListener(type, listener, capture, opt_handler);\r\n }\r\n\r\n if (!src) {\r\n // TODO(chrishenry): We should tighten the API to only accept\r\n // non-null objects, or add an assertion here.\r\n return null;\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (src));\r\n if (listenerMap) {\r\n return listenerMap.getListener(type, listener, capture, opt_handler);\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether an event target has any active listeners matching the\r\n * specified signature. If either the type or capture parameters are\r\n * unspecified, the function will match on the remaining criteria.\r\n *\r\n * @param {EventTarget|goog.events.Listenable} obj Target to get\r\n * listeners for.\r\n * @param {string|!goog.events.EventId=} opt_type Event type.\r\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\r\n * listeners.\r\n * @return {boolean} Whether an event target has one or more listeners matching\r\n * the requested type and/or capture phase.\r\n */\r\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return obj.hasListener(opt_type, opt_capture);\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (obj));\r\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\r\n};\r\n\r\n\r\n/**\r\n * Provides a nice string showing the normalized event objects public members\r\n * @param {Object} e Event Object.\r\n * @return {string} String of the public members of the normalized event object.\r\n */\r\ngoog.events.expose = function(e) {\r\n var str = [];\r\n for (var key in e) {\r\n if (e[key] && e[key].id) {\r\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\r\n } else {\r\n str.push(key + ' = ' + e[key]);\r\n }\r\n }\r\n return str.join('\\n');\r\n};\r\n\r\n\r\n/**\r\n * Returns a string with on prepended to the specified type. This is used for IE\r\n * which expects \"on\" to be prepended. This function caches the string in order\r\n * to avoid extra allocations in steady state.\r\n * @param {string} type Event type.\r\n * @return {string} The type string with 'on' prepended.\r\n * @private\r\n */\r\ngoog.events.getOnString_ = function(type) {\r\n if (type in goog.events.onStringMap_) {\r\n return goog.events.onStringMap_[type];\r\n }\r\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\r\n};\r\n\r\n\r\n/**\r\n * Fires an object's listeners of a particular type and phase\r\n *\r\n * @param {Object} obj Object whose listeners to call.\r\n * @param {string|!goog.events.EventId} type Event type.\r\n * @param {boolean} capture Which event phase.\r\n * @param {Object} eventObject Event object to be passed to listener.\r\n * @return {boolean} True if all listeners returned true else false.\r\n */\r\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\r\n type, capture, eventObject);\r\n }\r\n\r\n return goog.events.fireListeners_(obj, type, capture, eventObject);\r\n};\r\n\r\n\r\n/**\r\n * Fires an object's listeners of a particular type and phase.\r\n * @param {Object} obj Object whose listeners to call.\r\n * @param {string|!goog.events.EventId} type Event type.\r\n * @param {boolean} capture Which event phase.\r\n * @param {Object} eventObject Event object to be passed to listener.\r\n * @return {boolean} True if all listeners returned true else false.\r\n * @private\r\n */\r\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\r\n /** @type {boolean} */\r\n var retval = true;\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {EventTarget} */ (obj));\r\n if (listenerMap) {\r\n // TODO(chrishenry): Original code avoids array creation when there\r\n // is no listener, so we do the same. If this optimization turns\r\n // out to be not required, we can replace this with\r\n // listenerMap.getListeners(type, capture) instead, which is simpler.\r\n var listenerArray = listenerMap.listeners[type.toString()];\r\n if (listenerArray) {\r\n listenerArray = listenerArray.concat();\r\n for (var i = 0; i < listenerArray.length; i++) {\r\n var listener = listenerArray[i];\r\n // We might not have a listener if the listener was removed.\r\n if (listener && listener.capture == capture && !listener.removed) {\r\n var result = goog.events.fireListener(listener, eventObject);\r\n retval = retval && (result !== false);\r\n }\r\n }\r\n }\r\n }\r\n return retval;\r\n};\r\n\r\n\r\n/**\r\n * Fires a listener with a set of arguments\r\n *\r\n * @param {goog.events.Listener} listener The listener object to call.\r\n * @param {Object} eventObject The event object to pass to the listener.\r\n * @return {*} Result of listener.\r\n */\r\ngoog.events.fireListener = function(listener, eventObject) {\r\n var listenerFn = listener.listener;\r\n var listenerHandler = listener.handler || listener.src;\r\n\r\n if (listener.callOnce) {\r\n goog.events.unlistenByKey(listener);\r\n }\r\n return listenerFn.call(listenerHandler, eventObject);\r\n};\r\n\r\n\r\n/**\r\n * Gets the total number of listeners currently in the system.\r\n * @return {number} Number of listeners.\r\n * @deprecated This returns estimated count, now that Closure no longer\r\n * stores a central listener registry. We still return an estimation\r\n * to keep existing listener-related tests passing. In the near future,\r\n * this function will be removed.\r\n */\r\ngoog.events.getTotalListenerCount = function() {\r\n return goog.events.listenerCountEstimate_;\r\n};\r\n\r\n\r\n/**\r\n * Dispatches an event (or event like object) and calls all listeners\r\n * listening for events of this type. The type of the event is decided by the\r\n * type property on the event object.\r\n *\r\n * If any of the listeners returns false OR calls preventDefault then this\r\n * function will return false. If one of the capture listeners calls\r\n * stopPropagation, then the bubble listeners won't fire.\r\n *\r\n * @param {goog.events.Listenable} src The event target.\r\n * @param {goog.events.EventLike} e Event object.\r\n * @return {boolean} If anyone called preventDefault on the event object (or\r\n * if any of the handlers returns false) this will also return false.\r\n * If there are no handlers, or if all handlers return true, this returns\r\n * true.\r\n */\r\ngoog.events.dispatchEvent = function(src, e) {\r\n goog.asserts.assert(\r\n goog.events.Listenable.isImplementedBy(src),\r\n 'Can not use goog.events.dispatchEvent with ' +\r\n 'non-goog.events.Listenable instance.');\r\n return src.dispatchEvent(e);\r\n};\r\n\r\n\r\n/**\r\n * Installs exception protection for the browser event entry point using the\r\n * given error handler.\r\n *\r\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\r\n * protect the entry point.\r\n */\r\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\r\n goog.events.handleBrowserEvent_ =\r\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\r\n};\r\n\r\n\r\n/**\r\n * Handles an event and dispatches it to the correct listeners. This\r\n * function is a proxy for the real listener the user specified.\r\n *\r\n * @param {goog.events.Listener} listener The listener object.\r\n * @param {Event=} opt_evt Optional event object that gets passed in via the\r\n * native event handlers.\r\n * @return {*} Result of the event handler.\r\n * @this {EventTarget} The object or Element that fired the event.\r\n * @private\r\n */\r\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\r\n if (listener.removed) {\r\n return true;\r\n }\r\n\r\n // Synthesize event propagation if the browser does not support W3C\r\n // event model.\r\n if (!goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {\r\n var ieEvent = opt_evt ||\r\n /** @type {Event} */ (goog.getObjectByName('window.event'));\r\n var evt = new goog.events.BrowserEvent(ieEvent, this);\r\n /** @type {*} */\r\n var retval = true;\r\n\r\n if (goog.events.CAPTURE_SIMULATION_MODE ==\r\n goog.events.CaptureSimulationMode.ON) {\r\n // If we have not marked this event yet, we should perform capture\r\n // simulation.\r\n if (!goog.events.isMarkedIeEvent_(ieEvent)) {\r\n goog.events.markIeEvent_(ieEvent);\r\n\r\n var ancestors = [];\r\n for (var parent = evt.currentTarget; parent;\r\n parent = parent.parentNode) {\r\n ancestors.push(parent);\r\n }\r\n\r\n // Fire capture listeners.\r\n var type = listener.type;\r\n for (var i = ancestors.length - 1; !evt.propagationStopped_ && i >= 0;\r\n i--) {\r\n evt.currentTarget = ancestors[i];\r\n var result =\r\n goog.events.fireListeners_(ancestors[i], type, true, evt);\r\n retval = retval && result;\r\n }\r\n\r\n // Fire bubble listeners.\r\n //\r\n // We can technically rely on IE to perform bubble event\r\n // propagation. However, it turns out that IE fires events in\r\n // opposite order of attachEvent registration, which broke\r\n // some code and tests that rely on the order. (While W3C DOM\r\n // Level 2 Events TR leaves the event ordering unspecified,\r\n // modern browsers and W3C DOM Level 3 Events Working Draft\r\n // actually specify the order as the registration order.)\r\n for (var i = 0; !evt.propagationStopped_ && i < ancestors.length; i++) {\r\n evt.currentTarget = ancestors[i];\r\n var result =\r\n goog.events.fireListeners_(ancestors[i], type, false, evt);\r\n retval = retval && result;\r\n }\r\n }\r\n } else {\r\n retval = goog.events.fireListener(listener, evt);\r\n }\r\n return retval;\r\n }\r\n\r\n // Otherwise, simply fire the listener.\r\n return goog.events.fireListener(\r\n listener, new goog.events.BrowserEvent(opt_evt, this));\r\n};\r\n\r\n\r\n/**\r\n * This is used to mark the IE event object so we do not do the Closure pass\r\n * twice for a bubbling event.\r\n * @param {Event} e The IE browser event.\r\n * @private\r\n */\r\ngoog.events.markIeEvent_ = function(e) {\r\n // Only the keyCode and the returnValue can be changed. We use keyCode for\r\n // non keyboard events.\r\n // event.returnValue is a bit more tricky. It is undefined by default. A\r\n // boolean false prevents the default action. In a window.onbeforeunload and\r\n // the returnValue is non undefined it will be alerted. However, we will only\r\n // modify the returnValue for keyboard events. We can get a problem if non\r\n // closure events sets the keyCode or the returnValue\r\n\r\n var useReturnValue = false;\r\n\r\n if (e.keyCode == 0) {\r\n // We cannot change the keyCode in case that srcElement is input[type=file].\r\n // We could test that that is the case but that would allocate 3 objects.\r\n // If we use try/catch we will only allocate extra objects in the case of a\r\n // failure.\r\n\r\n try {\r\n e.keyCode = -1;\r\n return;\r\n } catch (ex) {\r\n useReturnValue = true;\r\n }\r\n }\r\n\r\n if (useReturnValue ||\r\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\r\n e.returnValue = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * This is used to check if an IE event has already been handled by the Closure\r\n * system so we do not do the Closure pass twice for a bubbling event.\r\n * @param {Event} e The IE browser event.\r\n * @return {boolean} True if the event object has been marked.\r\n * @private\r\n */\r\ngoog.events.isMarkedIeEvent_ = function(e) {\r\n return e.keyCode < 0 || e.returnValue != undefined;\r\n};\r\n\r\n\r\n/**\r\n * Counter to create unique event ids.\r\n * @private {number}\r\n */\r\ngoog.events.uniqueIdCounter_ = 0;\r\n\r\n\r\n/**\r\n * Creates a unique event id.\r\n *\r\n * @param {string} identifier The identifier.\r\n * @return {string} A unique identifier.\r\n * @idGenerator {unique}\r\n */\r\ngoog.events.getUniqueId = function(identifier) {\r\n return identifier + '_' + goog.events.uniqueIdCounter_++;\r\n};\r\n\r\n\r\n/**\r\n * @param {EventTarget} src The source object.\r\n * @return {goog.events.ListenerMap} A listener map for the given\r\n * source object, or null if none exists.\r\n * @private\r\n */\r\ngoog.events.getListenerMap_ = function(src) {\r\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\r\n // IE serializes the property as well (e.g. when serializing outer\r\n // HTML). So we must check that the value is of the correct type.\r\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\r\n};\r\n\r\n\r\n/**\r\n * Expando property for listener function wrapper for Object with\r\n * handleEvent.\r\n * @private @const {string}\r\n */\r\ngoog.events.LISTENER_WRAPPER_PROP_ =\r\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\r\n\r\n\r\n/**\r\n * @param {Object|Function} listener The listener function or an\r\n * object that contains handleEvent method.\r\n * @return {!Function} Either the original function or a function that\r\n * calls obj.handleEvent. If the same listener is passed to this\r\n * function more than once, the same function is guaranteed to be\r\n * returned.\r\n */\r\ngoog.events.wrapListener = function(listener) {\r\n goog.asserts.assert(listener, 'Listener can not be null.');\r\n\r\n if (goog.isFunction(listener)) {\r\n return listener;\r\n }\r\n\r\n goog.asserts.assert(\r\n listener.handleEvent, 'An object listener must have handleEvent method.');\r\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\r\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\r\n return /** @type {?} */ (listener).handleEvent(e);\r\n };\r\n }\r\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\r\n};\r\n\r\n\r\n// Register the browser event handler as an entry point, so that\r\n// it can be monitored for exception handling, etc.\r\ngoog.debug.entryPointRegistry.register(\r\n /**\r\n * @param {function(!Function): !Function} transformer The transforming\r\n * function.\r\n */\r\n function(transformer) {\r\n goog.events.handleBrowserEvent_ =\r\n transformer(goog.events.handleBrowserEvent_);\r\n });\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A disposable implementation of a custom\r\n * listenable/event target. See also: documentation for\r\n * `goog.events.Listenable`.\r\n *\r\n * @author arv@google.com (Erik Arvidsson) [Original implementation]\r\n * @see ../demos/eventtarget.html\r\n * @see goog.events.Listenable\r\n */\r\n\r\ngoog.provide('goog.events.EventTarget');\r\n\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.events');\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.Listenable');\r\ngoog.require('goog.events.ListenerMap');\r\ngoog.require('goog.object');\r\n\r\n\r\n\r\n/**\r\n * An implementation of `goog.events.Listenable` with full W3C\r\n * EventTarget-like support (capture/bubble mechanism, stopping event\r\n * propagation, preventing default actions).\r\n *\r\n * You may subclass this class to turn your class into a Listenable.\r\n *\r\n * Unless propagation is stopped, an event dispatched by an\r\n * EventTarget will bubble to the parent returned by\r\n * `getParentEventTarget`. To set the parent, call\r\n * `setParentEventTarget`. Subclasses that don't support\r\n * changing the parent can override the setter to throw an error.\r\n *\r\n * Example usage:\r\n * <pre>\r\n * var source = new goog.events.EventTarget();\r\n * function handleEvent(e) {\r\n * alert('Type: ' + e.type + '; Target: ' + e.target);\r\n * }\r\n * source.listen('foo', handleEvent);\r\n * // Or: goog.events.listen(source, 'foo', handleEvent);\r\n * ...\r\n * source.dispatchEvent('foo'); // will call handleEvent\r\n * ...\r\n * source.unlisten('foo', handleEvent);\r\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\r\n * </pre>\r\n *\r\n * @constructor\r\n * @extends {goog.Disposable}\r\n * @implements {goog.events.Listenable}\r\n */\r\ngoog.events.EventTarget = function() {\r\n goog.Disposable.call(this);\r\n\r\n /**\r\n * Maps of event type to an array of listeners.\r\n * @private {!goog.events.ListenerMap}\r\n */\r\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\r\n\r\n /**\r\n * The object to use for event.target. Useful when mixing in an\r\n * EventTarget to another object.\r\n * @private {!Object}\r\n */\r\n this.actualEventTarget_ = this;\r\n\r\n /**\r\n * Parent event target, used during event bubbling.\r\n *\r\n * TODO(chrishenry): Change this to goog.events.Listenable. This\r\n * currently breaks people who expect getParentEventTarget to return\r\n * goog.events.EventTarget.\r\n *\r\n * @private {?goog.events.EventTarget}\r\n */\r\n this.parentEventTarget_ = null;\r\n};\r\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\r\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\r\n\r\n\r\n/**\r\n * An artificial cap on the number of ancestors you can have. This is mainly\r\n * for loop detection.\r\n * @const {number}\r\n * @private\r\n */\r\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\r\n\r\n\r\n/**\r\n * Returns the parent of this event target to use for bubbling.\r\n *\r\n * @return {goog.events.EventTarget} The parent EventTarget or null if\r\n * there is no parent.\r\n * @override\r\n */\r\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\r\n return this.parentEventTarget_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the parent of this event target to use for capture/bubble\r\n * mechanism.\r\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\r\n */\r\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\r\n this.parentEventTarget_ = parent;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener to the event target. The same handler can only be\r\n * added once per the type. Even if you add the same handler multiple times\r\n * using the same type then it will only be called once when the event is\r\n * dispatched.\r\n *\r\n * @param {string|!goog.events.EventId} type The type of the event to listen for\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\r\n * to handle the event. The handler can also be an object that implements\r\n * the handleEvent method which takes the event object as argument.\r\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase\r\n * of the event.\r\n * @param {Object=} opt_handlerScope Object in whose scope to call\r\n * the listener.\r\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\r\n * `goog.events.listen` if you are passing Object\r\n * (instead of Function) as handler.\r\n */\r\ngoog.events.EventTarget.prototype.addEventListener = function(\r\n type, handler, opt_capture, opt_handlerScope) {\r\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener from the event target. The handler must be the\r\n * same object as the one added. If the handler has not been added then\r\n * nothing is done.\r\n *\r\n * @param {string} type The type of the event to listen for.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\r\n * to handle the event. The handler can also be an object that implements\r\n * the handleEvent method which takes the event object as argument.\r\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase\r\n * of the event.\r\n * @param {Object=} opt_handlerScope Object in whose scope to call\r\n * the listener.\r\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\r\n * `goog.events.unlisten` if you are passing Object\r\n * (instead of Function) as handler.\r\n */\r\ngoog.events.EventTarget.prototype.removeEventListener = function(\r\n type, handler, opt_capture, opt_handlerScope) {\r\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\r\n this.assertInitialized_();\r\n\r\n var ancestorsTree, ancestor = this.getParentEventTarget();\r\n if (ancestor) {\r\n ancestorsTree = [];\r\n var ancestorCount = 1;\r\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\r\n ancestorsTree.push(ancestor);\r\n goog.asserts.assert(\r\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\r\n 'infinite loop');\r\n }\r\n }\r\n\r\n return goog.events.EventTarget.dispatchEventInternal_(\r\n this.actualEventTarget_, e, ancestorsTree);\r\n};\r\n\r\n\r\n/**\r\n * Removes listeners from this object. Classes that extend EventTarget may\r\n * need to override this method in order to remove references to DOM Elements\r\n * and additional listeners.\r\n * @override\r\n * @protected\r\n */\r\ngoog.events.EventTarget.prototype.disposeInternal = function() {\r\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\r\n\r\n this.removeAllListeners();\r\n this.parentEventTarget_ = null;\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.listen = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n this.assertInitialized_();\r\n return this.eventTargetListeners_.add(\r\n String(type), listener, false /* callOnce */, opt_useCapture,\r\n opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.listenOnce = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n return this.eventTargetListeners_.add(\r\n String(type), listener, true /* callOnce */, opt_useCapture,\r\n opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.unlisten = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n return this.eventTargetListeners_.remove(\r\n String(type), listener, opt_useCapture, opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\r\n return this.eventTargetListeners_.removeByKey(key);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\r\n // TODO(chrishenry): Previously, removeAllListeners can be called on\r\n // uninitialized EventTarget, so we preserve that behavior. We\r\n // should remove this when usages that rely on that fact are purged.\r\n if (!this.eventTargetListeners_) {\r\n return 0;\r\n }\r\n return this.eventTargetListeners_.removeAll(opt_type);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.fireListeners = function(\r\n type, capture, eventObject) {\r\n // TODO(chrishenry): Original code avoids array creation when there\r\n // is no listener, so we do the same. If this optimization turns\r\n // out to be not required, we can replace this with\r\n // getListeners(type, capture) instead, which is simpler.\r\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\r\n if (!listenerArray) {\r\n return true;\r\n }\r\n listenerArray = listenerArray.concat();\r\n\r\n var rv = true;\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n var listener = listenerArray[i];\r\n // We might not have a listener if the listener was removed.\r\n if (listener && !listener.removed && listener.capture == capture) {\r\n var listenerFn = listener.listener;\r\n var listenerHandler = listener.handler || listener.src;\r\n\r\n if (listener.callOnce) {\r\n this.unlistenByKey(listener);\r\n }\r\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\r\n }\r\n }\r\n\r\n return rv && eventObject.returnValue_ != false;\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\r\n return this.eventTargetListeners_.getListeners(String(type), capture);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.getListener = function(\r\n type, listener, capture, opt_listenerScope) {\r\n return this.eventTargetListeners_.getListener(\r\n String(type), listener, capture, opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.hasListener = function(\r\n opt_type, opt_capture) {\r\n var id = goog.isDef(opt_type) ? String(opt_type) : undefined;\r\n return this.eventTargetListeners_.hasListener(id, opt_capture);\r\n};\r\n\r\n\r\n/**\r\n * Sets the target to be used for `event.target` when firing\r\n * event. Mainly used for testing. For example, see\r\n * `goog.testing.events.mixinListenable`.\r\n * @param {!Object} target The target.\r\n */\r\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\r\n this.actualEventTarget_ = target;\r\n};\r\n\r\n\r\n/**\r\n * Asserts that the event target instance is initialized properly.\r\n * @private\r\n */\r\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\r\n goog.asserts.assert(\r\n this.eventTargetListeners_,\r\n 'Event target is not initialized. Did you call the superclass ' +\r\n '(goog.events.EventTarget) constructor?');\r\n};\r\n\r\n\r\n/**\r\n * Dispatches the given event on the ancestorsTree.\r\n *\r\n * @param {!Object} target The target to dispatch on.\r\n * @param {goog.events.Event|Object|string} e The event object.\r\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\r\n * tree of the target, in reverse order from the closest ancestor\r\n * to the root event target. May be null if the target has no ancestor.\r\n * @return {boolean} If anyone called preventDefault on the event object (or\r\n * if any of the listeners returns false) this will also return false.\r\n * @private\r\n */\r\ngoog.events.EventTarget.dispatchEventInternal_ = function(\r\n target, e, opt_ancestorsTree) {\r\n /** @suppress {missingProperties} */\r\n var type = e.type || /** @type {string} */ (e);\r\n\r\n // If accepting a string or object, create a custom event object so that\r\n // preventDefault and stopPropagation work with the event.\r\n if (goog.isString(e)) {\r\n e = new goog.events.Event(e, target);\r\n } else if (!(e instanceof goog.events.Event)) {\r\n var oldEvent = e;\r\n e = new goog.events.Event(type, target);\r\n goog.object.extend(e, oldEvent);\r\n } else {\r\n e.target = e.target || target;\r\n }\r\n\r\n var rv = true, currentTarget;\r\n\r\n // Executes all capture listeners on the ancestors, if any.\r\n if (opt_ancestorsTree) {\r\n for (var i = opt_ancestorsTree.length - 1; !e.propagationStopped_ && i >= 0;\r\n i--) {\r\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\r\n rv = currentTarget.fireListeners(type, true, e) && rv;\r\n }\r\n }\r\n\r\n // Executes capture and bubble listeners on the target.\r\n if (!e.propagationStopped_) {\r\n currentTarget = /** @type {?} */ (e.currentTarget = target);\r\n rv = currentTarget.fireListeners(type, true, e) && rv;\r\n if (!e.propagationStopped_) {\r\n rv = currentTarget.fireListeners(type, false, e) && rv;\r\n }\r\n }\r\n\r\n // Executes all bubble listeners on the ancestors, if any.\r\n if (opt_ancestorsTree) {\r\n for (i = 0; !e.propagationStopped_ && i < opt_ancestorsTree.length; i++) {\r\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\r\n rv = currentTarget.fireListeners(type, false, e) && rv;\r\n }\r\n }\r\n\r\n return rv;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview JSON utility functions.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.json');\r\ngoog.provide('goog.json.Replacer');\r\ngoog.provide('goog.json.Reviver');\r\ngoog.provide('goog.json.Serializer');\r\n\r\n\r\n/**\r\n * @define {boolean} If true, use the native JSON parsing API.\r\n * NOTE: The default `goog.json.parse` implementation is able to handle\r\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\r\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\r\n * faster and safer than the default implementation using `eval`.\r\n */\r\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\r\n\r\n/**\r\n * @define {boolean} If true, try the native JSON parsing API first. If it\r\n * fails, log an error and use `eval` instead. This is useful when\r\n * transitioning to `goog.json.USE_NATIVE_JSON`. The error logger needs to\r\n * be set by `goog.json.setErrorLogger`. If it is not set then the error\r\n * is ignored.\r\n */\r\ngoog.json.TRY_NATIVE_JSON = goog.define('goog.json.TRY_NATIVE_JSON', false);\r\n\r\n\r\n/**\r\n * Tests if a string is an invalid JSON string. This only ensures that we are\r\n * not using any invalid characters\r\n * @param {string} s The string to test.\r\n * @return {boolean} True if the input is a valid JSON string.\r\n */\r\ngoog.json.isValid = function(s) {\r\n // All empty whitespace is not valid.\r\n if (/^\\s*$/.test(s)) {\r\n return false;\r\n }\r\n\r\n // This is taken from http://www.json.org/json2.js which is released to the\r\n // public domain.\r\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\r\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\r\n // are in the RFC but IE and Safari does not match \\s to these so we need to\r\n // include them in the reg exps in all places where whitespace is allowed.\r\n // We allowed \\x7f inside strings because some tools don't escape it,\r\n // e.g. http://www.json.org/java/org/json/JSONObject.java\r\n\r\n // Parsing happens in three stages. In the first stage, we run the text\r\n // against regular expressions that look for non-JSON patterns. We are\r\n // especially concerned with '()' and 'new' because they can cause invocation,\r\n // and '=' because it can cause mutation. But just to be safe, we want to\r\n // reject all unexpected forms.\r\n\r\n // We split the first stage into 4 regexp operations in order to work around\r\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\r\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\r\n // replace all simple value tokens with ']' characters, but only when followed\r\n // by a colon, comma, closing bracket or end of string. Third, we delete all\r\n // open brackets that follow a colon or comma or that begin the text. Finally,\r\n // we look to see that the remaining characters are only whitespace or ']' or\r\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\r\n\r\n // Don't make these static since they have the global flag.\r\n var backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\r\n var simpleValuesRe =\r\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\r\n var openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\r\n var remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\r\n\r\n return remainderRe.test(\r\n s.replace(backslashesRe, '@')\r\n .replace(simpleValuesRe, ']')\r\n .replace(openBracketsRe, ''));\r\n};\r\n\r\n/**\r\n * Logs a parsing error in `JSON.parse` solvable by using `eval`\r\n * if `goog.json.TRY_NATIVE_JSON` is enabled.\r\n * @private {function(string, !Error)} The first parameter is the error message,\r\n * the second is the exception thrown by `JSON.parse`.\r\n */\r\ngoog.json.errorLogger_ = goog.nullFunction;\r\n\r\n\r\n/**\r\n * Sets an error logger to use if there's a recoverable parsing error and\r\n * `goog.json.TRY_NATIVE_JSON` is enabled.\r\n * @param {function(string, !Error)} errorLogger The first parameter is the\r\n * error message, the second is the exception thrown by `JSON.parse`.\r\n */\r\ngoog.json.setErrorLogger = function(errorLogger) {\r\n goog.json.errorLogger_ = errorLogger;\r\n};\r\n\r\n\r\n/**\r\n * Parses a JSON string and returns the result. This throws an exception if\r\n * the string is an invalid JSON string.\r\n *\r\n * Note that this is very slow on large strings. Use JSON.parse if possible.\r\n *\r\n * @param {*} s The JSON string to parse.\r\n * @throws Error if s is invalid JSON.\r\n * @return {Object} The object generated from the JSON string, or null.\r\n * @deprecated Use JSON.parse.\r\n */\r\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\r\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\r\n function(s) {\r\n var error;\r\n if (goog.json.TRY_NATIVE_JSON) {\r\n try {\r\n return goog.global['JSON']['parse'](s);\r\n } catch (ex) {\r\n error = ex;\r\n }\r\n }\r\n var o = String(s);\r\n if (goog.json.isValid(o)) {\r\n\r\n try {\r\n var result = /** @type {?Object} */ (eval('(' + o + ')'));\r\n if (error) {\r\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\r\n }\r\n return result;\r\n } catch (ex) {\r\n }\r\n }\r\n throw new Error('Invalid JSON string: ' + o);\r\n };\r\n\r\n\r\n/**\r\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\r\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\r\n *\r\n * TODO(nicksantos): Array should also be a valid replacer.\r\n *\r\n * @typedef {function(this:Object, string, *): *}\r\n */\r\ngoog.json.Replacer;\r\n\r\n\r\n/**\r\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\r\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\r\n *\r\n * @typedef {function(this:Object, string, *): *}\r\n */\r\ngoog.json.Reviver;\r\n\r\n\r\n/**\r\n * Serializes an object or a value to a JSON string.\r\n *\r\n * @param {*} object The object to serialize.\r\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\r\n * called for each (key, value) pair that determines how the value\r\n * should be serialized. By defult, this just returns the value\r\n * and allows default serialization to kick in.\r\n * @throws Error if there are loops in the object graph.\r\n * @return {string} A JSON string representation of the input.\r\n */\r\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\r\n /** @type {function(*, ?goog.json.Replacer=):string} */\r\n (goog.global['JSON']['stringify']) :\r\n function(object, opt_replacer) {\r\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\r\n //\r\n // The last time I evaluated this, JSON.stringify had subtle bugs and\r\n // behavior differences on all browsers, and the performance win was not\r\n // large enough to justify all the issues. This may change in the future\r\n // as browser implementations get better.\r\n //\r\n // assertSerialize in json_test contains if branches for the cases\r\n // that fail.\r\n return new goog.json.Serializer(opt_replacer).serialize(object);\r\n };\r\n\r\n\r\n\r\n/**\r\n * Class that is used to serialize JSON objects to a string.\r\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\r\n * @constructor\r\n */\r\ngoog.json.Serializer = function(opt_replacer) {\r\n /**\r\n * @type {goog.json.Replacer|null|undefined}\r\n * @private\r\n */\r\n this.replacer_ = opt_replacer;\r\n};\r\n\r\n\r\n/**\r\n * Serializes an object or a value to a JSON string.\r\n *\r\n * @param {*} object The object to serialize.\r\n * @throws Error if there are loops in the object graph.\r\n * @return {string} A JSON string representation of the input.\r\n */\r\ngoog.json.Serializer.prototype.serialize = function(object) {\r\n var sb = [];\r\n this.serializeInternal(object, sb);\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Serializes a generic value to a JSON string\r\n * @protected\r\n * @param {*} object The object to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n * @throws Error if there are loops in the object graph.\r\n */\r\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\r\n if (object == null) {\r\n // undefined == null so this branch covers undefined as well as null\r\n sb.push('null');\r\n return;\r\n }\r\n\r\n if (typeof object == 'object') {\r\n if (goog.isArray(object)) {\r\n this.serializeArray(object, sb);\r\n return;\r\n } else if (\r\n object instanceof String || object instanceof Number ||\r\n object instanceof Boolean) {\r\n object = object.valueOf();\r\n // Fall through to switch below.\r\n } else {\r\n this.serializeObject_(/** @type {!Object} */ (object), sb);\r\n return;\r\n }\r\n }\r\n\r\n switch (typeof object) {\r\n case 'string':\r\n this.serializeString_(object, sb);\r\n break;\r\n case 'number':\r\n this.serializeNumber_(object, sb);\r\n break;\r\n case 'boolean':\r\n sb.push(String(object));\r\n break;\r\n case 'function':\r\n sb.push('null');\r\n break;\r\n default:\r\n throw new Error('Unknown type: ' + typeof object);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Character mappings used internally for goog.string.quote\r\n * @private\r\n * @type {!Object}\r\n */\r\ngoog.json.Serializer.charToJsonCharCache_ = {\r\n '\\\"': '\\\\\"',\r\n '\\\\': '\\\\\\\\',\r\n '/': '\\\\/',\r\n '\\b': '\\\\b',\r\n '\\f': '\\\\f',\r\n '\\n': '\\\\n',\r\n '\\r': '\\\\r',\r\n '\\t': '\\\\t',\r\n\r\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\r\n};\r\n\r\n\r\n/**\r\n * Regular expression used to match characters that need to be replaced.\r\n * The S60 browser has a bug where unicode characters are not matched by\r\n * regular expressions. The condition below detects such behaviour and\r\n * adjusts the regular expression accordingly.\r\n * @private\r\n * @type {!RegExp}\r\n */\r\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\r\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\r\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\r\n\r\n\r\n/**\r\n * Serializes a string to a JSON string\r\n * @private\r\n * @param {string} s The string to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n */\r\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\r\n // The official JSON implementation does not work with international\r\n // characters.\r\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\r\n // caching the result improves performance by a factor 2-3\r\n var rv = goog.json.Serializer.charToJsonCharCache_[c];\r\n if (!rv) {\r\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);\r\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\r\n }\r\n return rv;\r\n }), '\"');\r\n};\r\n\r\n\r\n/**\r\n * Serializes a number to a JSON string\r\n * @private\r\n * @param {number} n The number to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n */\r\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\r\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\r\n};\r\n\r\n\r\n/**\r\n * Serializes an array to a JSON string\r\n * @param {Array<string>} arr The array to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n * @protected\r\n */\r\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\r\n var l = arr.length;\r\n sb.push('[');\r\n var sep = '';\r\n for (var i = 0; i < l; i++) {\r\n sb.push(sep);\r\n\r\n var value = arr[i];\r\n this.serializeInternal(\r\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\r\n sb);\r\n\r\n sep = ',';\r\n }\r\n sb.push(']');\r\n};\r\n\r\n\r\n/**\r\n * Serializes an object to a JSON string\r\n * @private\r\n * @param {!Object} obj The object to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n */\r\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\r\n sb.push('{');\r\n var sep = '';\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n var value = obj[key];\r\n // Skip functions.\r\n if (typeof value != 'function') {\r\n sb.push(sep);\r\n this.serializeString_(key, sb);\r\n sb.push(':');\r\n\r\n this.serializeInternal(\r\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\r\n\r\n sep = ',';\r\n }\r\n }\r\n }\r\n sb.push('}');\r\n};\r\n","// Copyright 2015 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Simple freelist.\r\n *\r\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\r\n * objects in the list contain a \"next\" property that can be used to maintain\r\n * the pool.\r\n */\r\n\r\ngoog.provide('goog.async.FreeList');\r\n\r\n\r\n/**\r\n * @template ITEM\r\n */\r\ngoog.async.FreeList = goog.defineClass(null, {\r\n /**\r\n * @param {function():ITEM} create\r\n * @param {function(ITEM):void} reset\r\n * @param {number} limit\r\n */\r\n constructor: function(create, reset, limit) {\r\n /** @private @const {number} */\r\n this.limit_ = limit;\r\n /** @private @const {function()} */\r\n this.create_ = create;\r\n /** @private @const {function(ITEM):void} */\r\n this.reset_ = reset;\r\n\r\n /** @private {number} */\r\n this.occupants_ = 0;\r\n /** @private {ITEM} */\r\n this.head_ = null;\r\n },\r\n\r\n /**\r\n * @return {ITEM}\r\n */\r\n get: function() {\r\n var item;\r\n if (this.occupants_ > 0) {\r\n this.occupants_--;\r\n item = this.head_;\r\n this.head_ = item.next;\r\n item.next = null;\r\n } else {\r\n item = this.create_();\r\n }\r\n return item;\r\n },\r\n\r\n /**\r\n * @param {ITEM} item An item available for possible future reuse.\r\n */\r\n put: function(item) {\r\n this.reset_(item);\r\n if (this.occupants_ < this.limit_) {\r\n this.occupants_++;\r\n item.next = this.head_;\r\n this.head_ = item;\r\n }\r\n },\r\n\r\n /**\r\n * Visible for testing.\r\n * @package\r\n * @return {number}\r\n */\r\n occupants: function() { return this.occupants_; }\r\n});\r\n","// Copyright 2015 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\ngoog.provide('goog.async.WorkItem');\r\ngoog.provide('goog.async.WorkQueue');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.async.FreeList');\r\n\r\n\r\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\r\n// than goog.async.run.\r\n\r\n\r\n\r\n/**\r\n * A low GC workqueue. The key elements of this design:\r\n * - avoids the need for goog.bind or equivalent by carrying scope\r\n * - avoids the need for array reallocation by using a linked list\r\n * - minimizes work entry objects allocation by recycling objects\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\ngoog.async.WorkQueue = function() {\r\n this.workHead_ = null;\r\n this.workTail_ = null;\r\n};\r\n\r\n\r\n/** @define {number} The maximum number of entries to keep for recycling. */\r\ngoog.async.WorkQueue.DEFAULT_MAX_UNUSED =\r\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\r\n\r\n\r\n/** @const @private {goog.async.FreeList<goog.async.WorkItem>} */\r\ngoog.async.WorkQueue.freelist_ = new goog.async.FreeList(\r\n function() { return new goog.async.WorkItem(); },\r\n function(item) { item.reset(); }, goog.async.WorkQueue.DEFAULT_MAX_UNUSED);\r\n\r\n\r\n/**\r\n * @param {function()} fn\r\n * @param {Object|null|undefined} scope\r\n */\r\ngoog.async.WorkQueue.prototype.add = function(fn, scope) {\r\n var item = this.getUnusedItem_();\r\n item.set(fn, scope);\r\n\r\n if (this.workTail_) {\r\n this.workTail_.next = item;\r\n this.workTail_ = item;\r\n } else {\r\n goog.asserts.assert(!this.workHead_);\r\n this.workHead_ = item;\r\n this.workTail_ = item;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {goog.async.WorkItem}\r\n */\r\ngoog.async.WorkQueue.prototype.remove = function() {\r\n var item = null;\r\n\r\n if (this.workHead_) {\r\n item = this.workHead_;\r\n this.workHead_ = this.workHead_.next;\r\n if (!this.workHead_) {\r\n this.workTail_ = null;\r\n }\r\n item.next = null;\r\n }\r\n return item;\r\n};\r\n\r\n\r\n/**\r\n * @param {goog.async.WorkItem} item\r\n */\r\ngoog.async.WorkQueue.prototype.returnUnused = function(item) {\r\n goog.async.WorkQueue.freelist_.put(item);\r\n};\r\n\r\n\r\n/**\r\n * @return {goog.async.WorkItem}\r\n * @private\r\n */\r\ngoog.async.WorkQueue.prototype.getUnusedItem_ = function() {\r\n return goog.async.WorkQueue.freelist_.get();\r\n};\r\n\r\n\r\n\r\n/**\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\ngoog.async.WorkItem = function() {\r\n /** @type {?function()} */\r\n this.fn = null;\r\n /** @type {?Object|null|undefined} */\r\n this.scope = null;\r\n /** @type {?goog.async.WorkItem} */\r\n this.next = null;\r\n};\r\n\r\n\r\n/**\r\n * @param {function()} fn\r\n * @param {Object|null|undefined} scope\r\n */\r\ngoog.async.WorkItem.prototype.set = function(fn, scope) {\r\n this.fn = fn;\r\n this.scope = scope;\r\n this.next = null;\r\n};\r\n\r\n\r\n/** Reset the work item so they don't prevent GC before reuse */\r\ngoog.async.WorkItem.prototype.reset = function() {\r\n this.fn = null;\r\n this.scope = null;\r\n this.next = null;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\ngoog.provide('goog.async.run');\r\n\r\ngoog.require('goog.async.WorkQueue');\r\ngoog.require('goog.async.nextTick');\r\ngoog.require('goog.async.throwException');\r\n\r\n/**\r\n * @define {boolean} If true, use the global Promise to implement goog.async.run\r\n * assuming either the native, or polyfill version will be used. Does still\r\n * permit tests to use forceNextTick.\r\n */\r\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\r\n\r\n/**\r\n * Fires the provided callback just before the current callstack unwinds, or as\r\n * soon as possible after the current JS execution context.\r\n * @param {function(this:THIS)} callback\r\n * @param {THIS=} opt_context Object to use as the \"this value\" when calling\r\n * the provided function.\r\n * @template THIS\r\n */\r\ngoog.async.run = function(callback, opt_context) {\r\n if (!goog.async.run.schedule_) {\r\n goog.async.run.initializeRunner_();\r\n }\r\n if (!goog.async.run.workQueueScheduled_) {\r\n // Nothing is currently scheduled, schedule it now.\r\n goog.async.run.schedule_();\r\n goog.async.run.workQueueScheduled_ = true;\r\n }\r\n\r\n goog.async.run.workQueue_.add(callback, opt_context);\r\n};\r\n\r\n\r\n/**\r\n * Initializes the function to use to process the work queue.\r\n * @private\r\n */\r\ngoog.async.run.initializeRunner_ = function() {\r\n if (goog.ASSUME_NATIVE_PROMISE ||\r\n (goog.global.Promise && goog.global.Promise.resolve)) {\r\n // Use goog.global.Promise instead of just Promise because the relevant\r\n // externs may be missing, and don't alias it because this could confuse the\r\n // compiler into thinking the polyfill is required when it should be treated\r\n // as optional.\r\n var promise = goog.global.Promise.resolve(undefined);\r\n goog.async.run.schedule_ = function() {\r\n promise.then(goog.async.run.processWorkQueue);\r\n };\r\n } else {\r\n goog.async.run.schedule_ = function() {\r\n goog.async.nextTick(goog.async.run.processWorkQueue);\r\n };\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Forces goog.async.run to use nextTick instead of Promise.\r\n *\r\n * This should only be done in unit tests. It's useful because MockClock\r\n * replaces nextTick, but not the browser Promise implementation, so it allows\r\n * Promise-based code to be tested with MockClock.\r\n *\r\n * However, we also want to run promises if the MockClock is no longer in\r\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\r\n * provided.\r\n *\r\n * @param {function(function())=} opt_realSetTimeout\r\n */\r\ngoog.async.run.forceNextTick = function(opt_realSetTimeout) {\r\n goog.async.run.schedule_ = function() {\r\n goog.async.nextTick(goog.async.run.processWorkQueue);\r\n if (opt_realSetTimeout) {\r\n opt_realSetTimeout(goog.async.run.processWorkQueue);\r\n }\r\n };\r\n};\r\n\r\n\r\n/**\r\n * The function used to schedule work asynchronousely.\r\n * @private {function()}\r\n */\r\ngoog.async.run.schedule_;\r\n\r\n\r\n/** @private {boolean} */\r\ngoog.async.run.workQueueScheduled_ = false;\r\n\r\n\r\n/** @private {!goog.async.WorkQueue} */\r\ngoog.async.run.workQueue_ = new goog.async.WorkQueue();\r\n\r\n\r\nif (goog.DEBUG) {\r\n /**\r\n * Reset the work queue. Only available for tests in debug mode.\r\n */\r\n goog.async.run.resetQueue = function() {\r\n goog.async.run.workQueueScheduled_ = false;\r\n goog.async.run.workQueue_ = new goog.async.WorkQueue();\r\n };\r\n}\r\n\r\n\r\n/**\r\n * Run any pending goog.async.run work items. This function is not intended\r\n * for general use, but for use by entry point handlers to run items ahead of\r\n * goog.async.nextTick.\r\n */\r\ngoog.async.run.processWorkQueue = function() {\r\n // NOTE: additional work queue items may be added while processing.\r\n var item = null;\r\n while (item = goog.async.run.workQueue_.remove()) {\r\n try {\r\n item.fn.call(item.scope);\r\n } catch (e) {\r\n goog.async.throwException(e);\r\n }\r\n goog.async.run.workQueue_.returnUnused(item);\r\n }\r\n\r\n // There are no more work items, allow processing to be scheduled again.\r\n goog.async.run.workQueueScheduled_ = false;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Provides a function to schedule running a function as soon\r\n * as possible after the current JS execution stops and yields to the event\r\n * loop.\r\n *\r\n */\r\n\r\ngoog.provide('goog.async.nextTick');\r\ngoog.provide('goog.async.throwException');\r\n\r\ngoog.require('goog.debug.entryPointRegistry');\r\ngoog.require('goog.dom.TagName');\r\ngoog.require('goog.functions');\r\ngoog.require('goog.labs.userAgent.browser');\r\ngoog.require('goog.labs.userAgent.engine');\r\n\r\n\r\n/**\r\n * Throw an item without interrupting the current execution context. For\r\n * example, if processing a group of items in a loop, sometimes it is useful\r\n * to report an error while still allowing the rest of the batch to be\r\n * processed.\r\n * @param {*} exception\r\n */\r\ngoog.async.throwException = function(exception) {\r\n // Each throw needs to be in its own context.\r\n goog.global.setTimeout(function() { throw exception; }, 0);\r\n};\r\n\r\n\r\n/**\r\n * Fires the provided callbacks as soon as possible after the current JS\r\n * execution context. setTimeout(…, 0) takes at least 4ms when called from\r\n * within another setTimeout(…, 0) for legacy reasons.\r\n *\r\n * This will not schedule the callback as a microtask (i.e. a task that can\r\n * preempt user input or networking callbacks). It is meant to emulate what\r\n * setTimeout(_, 0) would do if it were not throttled. If you desire microtask\r\n * behavior, use {@see goog.Promise} instead.\r\n *\r\n * @param {function(this:SCOPE)} callback Callback function to fire as soon as\r\n * possible.\r\n * @param {SCOPE=} opt_context Object in whose scope to call the listener.\r\n * @param {boolean=} opt_useSetImmediate Avoid the IE workaround that\r\n * ensures correctness at the cost of speed. See comments for details.\r\n * @template SCOPE\r\n */\r\ngoog.async.nextTick = function(callback, opt_context, opt_useSetImmediate) {\r\n var cb = callback;\r\n if (opt_context) {\r\n cb = goog.bind(callback, opt_context);\r\n }\r\n cb = goog.async.nextTick.wrapCallback_(cb);\r\n // Note we do allow callers to also request setImmediate if they are willing\r\n // to accept the possible tradeoffs of incorrectness in exchange for speed.\r\n // The IE fallback of readystate change is much slower. See useSetImmediate_\r\n // for details.\r\n if (goog.isFunction(goog.global.setImmediate) &&\r\n (opt_useSetImmediate || goog.async.nextTick.useSetImmediate_())) {\r\n goog.global.setImmediate(cb);\r\n return;\r\n }\r\n\r\n // Look for and cache the custom fallback version of setImmediate.\r\n if (!goog.async.nextTick.setImmediate_) {\r\n goog.async.nextTick.setImmediate_ =\r\n goog.async.nextTick.getSetImmediateEmulator_();\r\n }\r\n goog.async.nextTick.setImmediate_(cb);\r\n};\r\n\r\n\r\n/**\r\n * Returns whether should use setImmediate implementation currently on window.\r\n *\r\n * window.setImmediate was introduced and currently only supported by IE10+,\r\n * but due to a bug in the implementation it is not guaranteed that\r\n * setImmediate is faster than setTimeout nor that setImmediate N is before\r\n * setImmediate N+1. That is why we do not use the native version if\r\n * available. We do, however, call setImmediate if it is a non-native function\r\n * because that indicates that it has been replaced by goog.testing.MockClock\r\n * which we do want to support.\r\n * See\r\n * http://connect.microsoft.com/IE/feedback/details/801823/setimmediate-and-messagechannel-are-broken-in-ie10\r\n *\r\n * @return {boolean} Whether to use the implementation of setImmediate defined\r\n * on Window.\r\n * @private\r\n * @suppress {missingProperties} For \"Window.prototype.setImmediate\"\r\n */\r\ngoog.async.nextTick.useSetImmediate_ = function() {\r\n // Not a browser environment.\r\n if (!goog.global.Window || !goog.global.Window.prototype) {\r\n return true;\r\n }\r\n\r\n // MS Edge has window.setImmediate natively, but it's not on Window.prototype.\r\n // Also, there's no clean way to detect if the goog.global.setImmediate has\r\n // been replaced by mockClock as its replacement also shows up as \"[native\r\n // code]\" when using toString. Therefore, just always use\r\n // goog.global.setImmediate for Edge. It's unclear if it suffers the same\r\n // issues as IE10/11, but based on\r\n // https://dev.modern.ie/testdrive/demos/setimmediatesorting/\r\n // it seems they've been working to ensure it's WAI.\r\n if (goog.labs.userAgent.browser.isEdge() ||\r\n goog.global.Window.prototype.setImmediate != goog.global.setImmediate) {\r\n // Something redefined setImmediate in which case we decide to use it (This\r\n // is so that we use the mockClock setImmediate).\r\n return true;\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Cache for the setImmediate implementation.\r\n * @type {function(function())}\r\n * @private\r\n */\r\ngoog.async.nextTick.setImmediate_;\r\n\r\n\r\n/**\r\n * Determines the best possible implementation to run a function as soon as\r\n * the JS event loop is idle.\r\n * @return {function(function())} The \"setImmediate\" implementation.\r\n * @private\r\n */\r\ngoog.async.nextTick.getSetImmediateEmulator_ = function() {\r\n // Create a private message channel and use it to postMessage empty messages\r\n // to ourselves.\r\n /** @type {!Function|undefined} */\r\n var Channel = goog.global['MessageChannel'];\r\n // If MessageChannel is not available and we are in a browser, implement\r\n // an iframe based polyfill in browsers that have postMessage and\r\n // document.addEventListener. The latter excludes IE8 because it has a\r\n // synchronous postMessage implementation.\r\n if (typeof Channel === 'undefined' && typeof window !== 'undefined' &&\r\n window.postMessage && window.addEventListener &&\r\n // Presto (The old pre-blink Opera engine) has problems with iframes\r\n // and contentWindow.\r\n !goog.labs.userAgent.engine.isPresto()) {\r\n /** @constructor */\r\n Channel = function() {\r\n // Make an empty, invisible iframe.\r\n var iframe = /** @type {!HTMLIFrameElement} */ (\r\n document.createElement(String(goog.dom.TagName.IFRAME)));\r\n iframe.style.display = 'none';\r\n iframe.src = '';\r\n document.documentElement.appendChild(iframe);\r\n var win = iframe.contentWindow;\r\n var doc = win.document;\r\n doc.open();\r\n doc.write('');\r\n doc.close();\r\n // Do not post anything sensitive over this channel, as the workaround for\r\n // pages with file: origin could allow that information to be modified or\r\n // intercepted.\r\n var message = 'callImmediate' + Math.random();\r\n // The same origin policy rejects attempts to postMessage from file: urls\r\n // unless the origin is '*'.\r\n var origin = win.location.protocol == 'file:' ?\r\n '*' :\r\n win.location.protocol + '//' + win.location.host;\r\n var onmessage = goog.bind(function(e) {\r\n // Validate origin and message to make sure that this message was\r\n // intended for us. If the origin is set to '*' (see above) only the\r\n // message needs to match since, for example, '*' != 'file://'. Allowing\r\n // the wildcard is ok, as we are not concerned with security here.\r\n if ((origin != '*' && e.origin != origin) || e.data != message) {\r\n return;\r\n }\r\n this['port1'].onmessage();\r\n }, this);\r\n win.addEventListener('message', onmessage, false);\r\n this['port1'] = {};\r\n this['port2'] = {\r\n postMessage: function() { win.postMessage(message, origin); }\r\n };\r\n };\r\n }\r\n if (typeof Channel !== 'undefined' && !goog.labs.userAgent.browser.isIE()) {\r\n // Exclude all of IE due to\r\n // http://codeforhire.com/2013/09/21/setimmediate-and-messagechannel-broken-on-internet-explorer-10/\r\n // which allows starving postMessage with a busy setTimeout loop.\r\n // This currently affects IE10 and IE11 which would otherwise be able\r\n // to use the postMessage based fallbacks.\r\n var channel = new Channel();\r\n // Use a fifo linked list to call callbacks in the right order.\r\n var head = {};\r\n var tail = head;\r\n channel['port1'].onmessage = function() {\r\n if (goog.isDef(head.next)) {\r\n head = head.next;\r\n var cb = head.cb;\r\n head.cb = null;\r\n cb();\r\n }\r\n };\r\n return function(cb) {\r\n tail.next = {cb: cb};\r\n tail = tail.next;\r\n channel['port2'].postMessage(0);\r\n };\r\n }\r\n // Implementation for IE6 to IE10: Script elements fire an asynchronous\r\n // onreadystatechange event when inserted into the DOM.\r\n if (typeof document !== 'undefined' &&\r\n 'onreadystatechange' in\r\n document.createElement(String(goog.dom.TagName.SCRIPT))) {\r\n return function(cb) {\r\n var script = /** @type {!HTMLScriptElement} */ (\r\n document.createElement(String(goog.dom.TagName.SCRIPT)));\r\n script.onreadystatechange = function() {\r\n // Clean up and call the callback.\r\n script.onreadystatechange = null;\r\n script.parentNode.removeChild(script);\r\n script = null;\r\n cb();\r\n cb = null;\r\n };\r\n document.documentElement.appendChild(script);\r\n };\r\n }\r\n // Fall back to setTimeout with 0. In browsers this creates a delay of 5ms\r\n // or more.\r\n // NOTE(user): This fallback is used for IE11.\r\n return function(cb) {\r\n goog.global.setTimeout(/** @type {function()} */ (cb), 0);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Helper function that is overrided to protect callbacks with entry point\r\n * monitor if the application monitors entry points.\r\n * @param {function()} callback Callback function to fire as soon as possible.\r\n * @return {function()} The wrapped callback.\r\n * @private\r\n */\r\ngoog.async.nextTick.wrapCallback_ = goog.functions.identity;\r\n\r\n\r\n// Register the callback function as an entry point, so that it can be\r\n// monitored for exception handling, etc. This has to be done in this file\r\n// since it requires special code to handle all browsers.\r\ngoog.debug.entryPointRegistry.register(\r\n /**\r\n * @param {function(!Function): !Function} transformer The transforming\r\n * function.\r\n */\r\n function(transformer) { goog.async.nextTick.wrapCallback_ = transformer; });\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A timer class to which other classes and objects can listen on.\r\n * This is only an abstraction above `setInterval`.\r\n *\r\n * @see ../demos/timers.html\r\n */\r\n\r\ngoog.provide('goog.Timer');\r\n\r\ngoog.require('goog.Promise');\r\ngoog.require('goog.events.EventTarget');\r\n\r\n\r\n\r\n/**\r\n * Class for handling timing events.\r\n *\r\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\r\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\r\n * `setInterval`, `clearTimeout` and `clearInterval`\r\n * (e.g., `window`).\r\n * @constructor\r\n * @extends {goog.events.EventTarget}\r\n */\r\ngoog.Timer = function(opt_interval, opt_timerObject) {\r\n goog.events.EventTarget.call(this);\r\n\r\n /**\r\n * Number of ms between ticks\r\n * @private {number}\r\n */\r\n this.interval_ = opt_interval || 1;\r\n\r\n /**\r\n * An object that implements `setTimeout`, `setInterval`,\r\n * `clearTimeout` and `clearInterval`. We default to the window\r\n * object. Changing this on {@link goog.Timer.prototype} changes the object\r\n * for all timer instances which can be useful if your environment has some\r\n * other implementation of timers than the `window` object.\r\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\r\n */\r\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\r\n opt_timerObject || goog.Timer.defaultTimerObject);\r\n\r\n /**\r\n * Cached `tick_` bound to the object for later use in the timer.\r\n * @private {Function}\r\n * @const\r\n */\r\n this.boundTick_ = goog.bind(this.tick_, this);\r\n\r\n /**\r\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\r\n * than the requested timeout. So we compare the time to when the event was\r\n * last fired, and reschedule if appropriate. See also\r\n * {@link goog.Timer.intervalScale}.\r\n * @private {number}\r\n */\r\n this.last_ = goog.now();\r\n};\r\ngoog.inherits(goog.Timer, goog.events.EventTarget);\r\n\r\n\r\n/**\r\n * Maximum timeout value.\r\n *\r\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\r\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\r\n * immediately. It makes more sense simply not to schedule these timeouts, since\r\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\r\n *\r\n * @private {number}\r\n * @const\r\n */\r\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\r\n\r\n\r\n/**\r\n * A timer ID that cannot be returned by any known implementation of\r\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\r\n * should therefore be a no-op.\r\n *\r\n * @private {number}\r\n * @const\r\n */\r\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\r\n\r\n\r\n/**\r\n * Whether this timer is enabled\r\n * @type {boolean}\r\n */\r\ngoog.Timer.prototype.enabled = false;\r\n\r\n\r\n/**\r\n * An object that implements `setTimeout`, `setInterval`,\r\n * `clearTimeout` and `clearInterval`. We default to the global\r\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\r\n * all timer instances which can be useful if your environment has some other\r\n * implementation of timers you'd like to use.\r\n * @type {{setTimeout, clearTimeout}}\r\n */\r\ngoog.Timer.defaultTimerObject = goog.global;\r\n\r\n\r\n/**\r\n * Variable that controls the timer error correction. If the timer is called\r\n * before the requested interval times `intervalScale`, which often\r\n * happens on Mozilla, the timer is rescheduled.\r\n * @see {@link #last_}\r\n * @type {number}\r\n */\r\ngoog.Timer.intervalScale = 0.8;\r\n\r\n\r\n/**\r\n * Variable for storing the result of `setInterval`.\r\n * @private {?number}\r\n */\r\ngoog.Timer.prototype.timer_ = null;\r\n\r\n\r\n/**\r\n * Gets the interval of the timer.\r\n * @return {number} interval Number of ms between ticks.\r\n */\r\ngoog.Timer.prototype.getInterval = function() {\r\n return this.interval_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the interval of the timer.\r\n * @param {number} interval Number of ms between ticks.\r\n */\r\ngoog.Timer.prototype.setInterval = function(interval) {\r\n this.interval_ = interval;\r\n if (this.timer_ && this.enabled) {\r\n // Stop and then start the timer to reset the interval.\r\n this.stop();\r\n this.start();\r\n } else if (this.timer_) {\r\n this.stop();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Callback for the `setTimeout` used by the timer.\r\n * @private\r\n */\r\ngoog.Timer.prototype.tick_ = function() {\r\n if (this.enabled) {\r\n var elapsed = goog.now() - this.last_;\r\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\r\n this.timer_ = this.timerObject_.setTimeout(\r\n this.boundTick_, this.interval_ - elapsed);\r\n return;\r\n }\r\n\r\n // Prevents setInterval from registering a duplicate timeout when called\r\n // in the timer event handler.\r\n if (this.timer_) {\r\n this.timerObject_.clearTimeout(this.timer_);\r\n this.timer_ = null;\r\n }\r\n\r\n this.dispatchTick();\r\n // The timer could be stopped in the timer event handler.\r\n if (this.enabled) {\r\n // Stop and start to ensure there is always only one timeout even if\r\n // start is called in the timer event handler.\r\n this.stop();\r\n this.start();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Dispatches the TICK event. This is its own method so subclasses can override.\r\n */\r\ngoog.Timer.prototype.dispatchTick = function() {\r\n this.dispatchEvent(goog.Timer.TICK);\r\n};\r\n\r\n\r\n/**\r\n * Starts the timer.\r\n */\r\ngoog.Timer.prototype.start = function() {\r\n this.enabled = true;\r\n\r\n // If there is no interval already registered, start it now\r\n if (!this.timer_) {\r\n // IMPORTANT!\r\n // window.setInterval in FireFox has a bug - it fires based on\r\n // absolute time, rather than on relative time. What this means\r\n // is that if a computer is sleeping/hibernating for 24 hours\r\n // and the timer interval was configured to fire every 1000ms,\r\n // then after the PC wakes up the timer will fire, in rapid\r\n // succession, 3600*24 times.\r\n // This bug is described here and is already fixed, but it will\r\n // take time to propagate, so for now I am switching this over\r\n // to setTimeout logic.\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\r\n //\r\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\r\n this.last_ = goog.now();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Stops the timer.\r\n */\r\ngoog.Timer.prototype.stop = function() {\r\n this.enabled = false;\r\n if (this.timer_) {\r\n this.timerObject_.clearTimeout(this.timer_);\r\n this.timer_ = null;\r\n }\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.Timer.prototype.disposeInternal = function() {\r\n goog.Timer.superClass_.disposeInternal.call(this);\r\n this.stop();\r\n delete this.timerObject_;\r\n};\r\n\r\n\r\n/**\r\n * Constant for the timer's event type.\r\n * @const\r\n */\r\ngoog.Timer.TICK = 'tick';\r\n\r\n\r\n/**\r\n * Calls the given function once, after the optional pause.\r\n * <p>\r\n * The function is always called asynchronously, even if the delay is 0. This\r\n * is a common trick to schedule a function to run after a batch of browser\r\n * event processing.\r\n *\r\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\r\n * or object that has a handleEvent method.\r\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\r\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\r\n * @return {number} A handle to the timer ID.\r\n * @template SCOPE\r\n */\r\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\r\n if (goog.isFunction(listener)) {\r\n if (opt_handler) {\r\n listener = goog.bind(listener, opt_handler);\r\n }\r\n } else if (listener && typeof listener.handleEvent == 'function') {\r\n // using typeof to prevent strict js warning\r\n listener = goog.bind(listener.handleEvent, listener);\r\n } else {\r\n throw new Error('Invalid listener argument');\r\n }\r\n\r\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\r\n // Timeouts greater than MAX_INT return immediately due to integer\r\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\r\n // schedule anything at all.\r\n return goog.Timer.INVALID_TIMEOUT_ID_;\r\n } else {\r\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears a timeout initiated by {@link #callOnce}.\r\n * @param {?number} timerId A timer ID.\r\n */\r\ngoog.Timer.clear = function(timerId) {\r\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\r\n};\r\n\r\n\r\n/**\r\n * @param {number} delay Milliseconds to wait.\r\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\r\n * with which the promise will be resolved.\r\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\r\n * the specified delay, unless it is canceled first.\r\n * @template RESULT\r\n */\r\ngoog.Timer.promise = function(delay, opt_result) {\r\n var timerKey = null;\r\n return new goog\r\n .Promise(function(resolve, reject) {\r\n timerKey =\r\n goog.Timer.callOnce(function() { resolve(opt_result); }, delay);\r\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\r\n reject(new Error('Failed to schedule timer.'));\r\n }\r\n })\r\n .thenCatch(function(error) {\r\n // Clear the timer. The most likely reason is \"cancel\" signal.\r\n goog.Timer.clear(timerKey);\r\n throw error;\r\n });\r\n};\r\n","// Copyright 2007 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Definition of the goog.async.Throttle class.\r\n *\r\n * @see ../demos/timers.html\r\n */\r\n\r\ngoog.provide('goog.Throttle');\r\ngoog.provide('goog.async.Throttle');\r\n\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.Timer');\r\n\r\n\r\n\r\n/**\r\n * Throttle will perform an action that is passed in no more than once\r\n * per interval (specified in milliseconds). If it gets multiple signals\r\n * to perform the action while it is waiting, it will only perform the action\r\n * once at the end of the interval.\r\n * @param {function(this: T, ...?)} listener Function to callback when the\r\n * action is triggered.\r\n * @param {number} interval Interval over which to throttle. The listener can\r\n * only be called once per interval.\r\n * @param {T=} opt_handler Object in whose scope to call the listener.\r\n * @constructor\r\n * @struct\r\n * @extends {goog.Disposable}\r\n * @final\r\n * @template T\r\n */\r\ngoog.async.Throttle = function(listener, interval, opt_handler) {\r\n goog.async.Throttle.base(this, 'constructor');\r\n\r\n /**\r\n * Function to callback\r\n * @type {function(this: T, ...?)}\r\n * @private\r\n */\r\n this.listener_ =\r\n opt_handler != null ? goog.bind(listener, opt_handler) : listener;\r\n\r\n /**\r\n * Interval for the throttle time\r\n * @type {number}\r\n * @private\r\n */\r\n this.interval_ = interval;\r\n\r\n /**\r\n * Cached callback function invoked after the throttle timeout completes\r\n * @type {Function}\r\n * @private\r\n */\r\n this.callback_ = goog.bind(this.onTimer_, this);\r\n\r\n /**\r\n * The last arguments passed into `fire`.\r\n * @private {!IArrayLike}\r\n */\r\n this.args_ = [];\r\n};\r\ngoog.inherits(goog.async.Throttle, goog.Disposable);\r\n\r\n\r\n\r\n/**\r\n * A deprecated alias.\r\n * @deprecated Use goog.async.Throttle instead.\r\n * @constructor\r\n * @final\r\n */\r\ngoog.Throttle = goog.async.Throttle;\r\n\r\n\r\n/**\r\n * Indicates that the action is pending and needs to be fired.\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.shouldFire_ = false;\r\n\r\n\r\n/**\r\n * Indicates the count of nested pauses currently in effect on the throttle.\r\n * When this count is not zero, fired actions will be postponed until the\r\n * throttle is resumed enough times to drop the pause count to zero.\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.pauseCount_ = 0;\r\n\r\n\r\n/**\r\n * Timer for scheduling the next callback\r\n * @type {?number}\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.timer_ = null;\r\n\r\n\r\n/**\r\n * Notifies the throttle that the action has happened. It will throttle the call\r\n * so that the callback is not called too often according to the interval\r\n * parameter passed to the constructor, passing the arguments from the last call\r\n * of this function into the throttled function.\r\n * @param {...?} var_args Arguments to pass on to the throttled function.\r\n */\r\ngoog.async.Throttle.prototype.fire = function(var_args) {\r\n this.args_ = arguments;\r\n if (!this.timer_ && !this.pauseCount_) {\r\n this.doAction_();\r\n } else {\r\n this.shouldFire_ = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Cancels any pending action callback. The throttle can be restarted by\r\n * calling {@link #fire}.\r\n */\r\ngoog.async.Throttle.prototype.stop = function() {\r\n if (this.timer_) {\r\n goog.Timer.clear(this.timer_);\r\n this.timer_ = null;\r\n this.shouldFire_ = false;\r\n this.args_ = [];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Pauses the throttle. All pending and future action callbacks will be\r\n * delayed until the throttle is resumed. Pauses can be nested.\r\n */\r\ngoog.async.Throttle.prototype.pause = function() {\r\n this.pauseCount_++;\r\n};\r\n\r\n\r\n/**\r\n * Resumes the throttle. If doing so drops the pausing count to zero, pending\r\n * action callbacks will be executed as soon as possible, but still no sooner\r\n * than an interval's delay after the previous call. Future action callbacks\r\n * will be executed as normal.\r\n */\r\ngoog.async.Throttle.prototype.resume = function() {\r\n this.pauseCount_--;\r\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\r\n this.shouldFire_ = false;\r\n this.doAction_();\r\n }\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.async.Throttle.prototype.disposeInternal = function() {\r\n goog.async.Throttle.base(this, 'disposeInternal');\r\n this.stop();\r\n};\r\n\r\n\r\n/**\r\n * Handler for the timer to fire the throttle\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.onTimer_ = function() {\r\n this.timer_ = null;\r\n\r\n if (this.shouldFire_ && !this.pauseCount_) {\r\n this.shouldFire_ = false;\r\n this.doAction_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls the callback\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.doAction_ = function() {\r\n this.timer_ = goog.Timer.callOnce(this.callback_, this.interval_);\r\n this.listener_.apply(null, this.args_);\r\n};\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Class to create objects which want to handle multiple events\r\n * and have their listeners easily cleaned up via a dispose method.\r\n *\r\n * Example:\r\n * <pre>\r\n * function Something() {\r\n * Something.base(this);\r\n *\r\n * ... set up object ...\r\n *\r\n * // Add event listeners\r\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\r\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\r\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\r\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\r\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\r\n * }\r\n * goog.inherits(Something, goog.events.EventHandler);\r\n *\r\n * Something.prototype.disposeInternal = function() {\r\n * Something.base(this, 'disposeInternal');\r\n * goog.dom.removeNode(this.container);\r\n * };\r\n *\r\n *\r\n * // Then elsewhere:\r\n *\r\n * var activeSomething = null;\r\n * function openSomething() {\r\n * activeSomething = new Something();\r\n * }\r\n *\r\n * function closeSomething() {\r\n * if (activeSomething) {\r\n * activeSomething.dispose(); // Remove event listeners\r\n * activeSomething = null;\r\n * }\r\n * }\r\n * </pre>\r\n *\r\n */\r\n\r\ngoog.provide('goog.events.EventHandler');\r\n\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.events');\r\ngoog.require('goog.object');\r\n\r\ngoog.forwardDeclare('goog.events.EventWrapper');\r\n\r\n\r\n\r\n/**\r\n * Super class for objects that want to easily manage a number of event\r\n * listeners. It allows a short cut to listen and also provides a quick way\r\n * to remove all events listeners belonging to this object.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\r\n * @constructor\r\n * @extends {goog.Disposable}\r\n * @template SCOPE\r\n */\r\ngoog.events.EventHandler = function(opt_scope) {\r\n goog.Disposable.call(this);\r\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\r\n // that access this private variable. :(\r\n this.handler_ = opt_scope;\r\n\r\n /**\r\n * Keys for events that are being listened to.\r\n * @type {!Object<!goog.events.Key>}\r\n * @private\r\n */\r\n this.keys_ = {};\r\n};\r\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\r\n\r\n\r\n/**\r\n * Utility array used to unify the cases of listening for an array of types\r\n * and listening for a single event, without using recursion or allocating\r\n * an array each time.\r\n * @type {!Array<string>}\r\n * @const\r\n * @private\r\n */\r\ngoog.events.EventHandler.typeArray_ = [];\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted then the\r\n * EventHandler's handleEvent method will be used.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\r\n * opt_fn Optional callback function to be used as the listener or an object\r\n * with handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listen = function(\r\n src, type, opt_fn, opt_options) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n return self.listen_(src, type, opt_fn, opt_options);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted then the\r\n * EventHandler's handleEvent method will be used.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\r\n * null|undefined} fn Optional callback function to be used as the\r\n * listener or an object with handleEvent function.\r\n * @param {boolean|!AddEventListenerOptions|undefined} options\r\n * @param {T} scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template T, EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenWithScope = function(\r\n src, type, fn, options, scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Deprecate this function.\r\n return self.listen_(src, type, fn, options, scope);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted then the\r\n * EventHandler's handleEvent method will be used.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\r\n * Optional callback function to be used as the listener or an object with\r\n * handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {Object=} opt_scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n * @private\r\n */\r\ngoog.events.EventHandler.prototype.listen_ = function(\r\n src, type, opt_fn, opt_options, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n if (!goog.isArray(type)) {\r\n if (type) {\r\n goog.events.EventHandler.typeArray_[0] = type.toString();\r\n }\r\n type = goog.events.EventHandler.typeArray_;\r\n }\r\n for (var i = 0; i < type.length; i++) {\r\n var listenerObj = goog.events.listen(\r\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\r\n opt_scope || self.handler_ || self);\r\n\r\n if (!listenerObj) {\r\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\r\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\r\n // value.\r\n return self;\r\n }\r\n\r\n var key = listenerObj.key;\r\n self.keys_[key] = listenerObj;\r\n }\r\n\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted, then the\r\n * EventHandler's handleEvent method will be used. After the event has fired the\r\n * event listener is removed from the target. If an array of event types is\r\n * provided, each event type will be listened to once.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\r\n * opt_fn\r\n * Optional callback function to be used as the listener or an object with\r\n * handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenOnce = function(\r\n src, type, opt_fn, opt_options) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n return self.listenOnce_(src, type, opt_fn, opt_options);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted, then the\r\n * EventHandler's handleEvent method will be used. After the event has fired the\r\n * event listener is removed from the target. If an array of event types is\r\n * provided, each event type will be listened to once.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\r\n * null|undefined} fn Optional callback function to be used as the\r\n * listener or an object with handleEvent function.\r\n * @param {boolean|undefined} capture Optional whether to use capture phase.\r\n * @param {T} scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template T, EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\r\n src, type, fn, capture, scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Deprecate this function.\r\n return self.listenOnce_(src, type, fn, capture, scope);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted, then the\r\n * EventHandler's handleEvent method will be used. After the event has fired\r\n * the event listener is removed from the target. If an array of event types is\r\n * provided, each event type will be listened to once.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\r\n * Optional callback function to be used as the listener or an object with\r\n * handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {Object=} opt_scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n * @private\r\n */\r\ngoog.events.EventHandler.prototype.listenOnce_ = function(\r\n src, type, opt_fn, opt_options, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\r\n }\r\n } else {\r\n var listenerObj = goog.events.listenOnce(\r\n src, type, opt_fn || self.handleEvent, opt_options,\r\n opt_scope || self.handler_ || self);\r\n if (!listenerObj) {\r\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\r\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\r\n // value.\r\n return self;\r\n }\r\n\r\n var key = listenerObj.key;\r\n self.keys_[key] = listenerObj;\r\n }\r\n\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.EventTarget}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\r\n * events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener\r\n * Callback method, or an object with a handleEvent function.\r\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\r\n * false).\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\r\n src, wrapper, listener, opt_capt) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Remove the opt_scope from this function and then\r\n // templatize it.\r\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.EventTarget}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\r\n * events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\r\n * listener Optional callback function to be used as the\r\n * listener or an object with handleEvent function.\r\n * @param {boolean|undefined} capture Optional whether to use capture phase.\r\n * @param {T} scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template T, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\r\n src, wrapper, listener, capture, scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Deprecate this function.\r\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.EventTarget}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\r\n * events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\r\n * method, or an object with a handleEvent function.\r\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\r\n * false).\r\n * @param {Object=} opt_scope Element in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template THIS\r\n * @private\r\n */\r\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\r\n src, wrapper, listener, opt_capt, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n wrapper.listen(\r\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} Number of listeners registered by this handler.\r\n */\r\ngoog.events.EventHandler.prototype.getListenerCount = function() {\r\n var count = 0;\r\n for (var key in this.keys_) {\r\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Unlistens on an event.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types to unlisten to.\r\n * @param {function(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\r\n * opt_fn Optional callback function to be used as the listener or an object\r\n * with handleEvent function.\r\n * @param {(boolean|!EventListenerOptions)=} opt_options\r\n * @param {Object=} opt_scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.unlisten = function(\r\n src, type, opt_fn, opt_options, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\r\n }\r\n } else {\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n var listener = goog.events.getListener(\r\n src, type, opt_fn || self.handleEvent, capture,\r\n opt_scope || self.handler_ || self);\r\n\r\n if (listener) {\r\n goog.events.unlistenByKey(listener);\r\n delete self.keys_[listener.key];\r\n }\r\n }\r\n\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listenWithWrapper().\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The target to stop\r\n * listening to events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to remove.\r\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase of the\r\n * event.\r\n * @param {Object=} opt_scope Element in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template THIS\r\n */\r\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\r\n src, wrapper, listener, opt_capt, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n wrapper.unlisten(\r\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Unlistens to all events.\r\n */\r\ngoog.events.EventHandler.prototype.removeAll = function() {\r\n goog.object.forEach(this.keys_, function(listenerObj, key) {\r\n if (this.keys_.hasOwnProperty(key)) {\r\n goog.events.unlistenByKey(listenerObj);\r\n }\r\n }, this);\r\n\r\n this.keys_ = {};\r\n};\r\n\r\n\r\n/**\r\n * Disposes of this EventHandler and removes all listeners that it registered.\r\n * @override\r\n * @protected\r\n */\r\ngoog.events.EventHandler.prototype.disposeInternal = function() {\r\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\r\n this.removeAll();\r\n};\r\n\r\n\r\n/**\r\n * Default event handler\r\n * @param {goog.events.Event} e Event object.\r\n */\r\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\r\n throw new Error('EventHandler.handleEvent not implemented');\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Provides a utility for tracing and debugging WebChannel\r\n * requests.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\r\n\r\ngoog.require('goog.json');\r\ngoog.require('goog.log');\r\n\r\ngoog.forwardDeclare('goog.Uri');\r\ngoog.forwardDeclare('goog.net.XmlHttp.ReadyState');\r\n\r\n\r\n\r\n/**\r\n * Logs and keeps a buffer of debugging info for the Channel.\r\n *\r\n * @constructor\r\n * @struct\r\n * @final\r\n */\r\ngoog.labs.net.webChannel.WebChannelDebug = function() {\r\n /**\r\n * The logger instance.\r\n * @const\r\n * @private {?goog.log.Logger}\r\n */\r\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\r\n\r\n /**\r\n * Whether to enable redact. Defaults to true.\r\n * @private {boolean}\r\n */\r\n this.redactEnabled_ = true;\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\n\r\n\r\n/**\r\n * Turns off redact.\r\n */\r\nWebChannelDebug.prototype.disableRedact = function() {\r\n this.redactEnabled_ = false;\r\n};\r\n\r\n\r\n/**\r\n * Logs that the browser went offline during the lifetime of a request.\r\n * @param {goog.Uri} url The URL being requested.\r\n */\r\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\r\n this.info(function() {\r\n return 'BROWSER_OFFLINE: ' + url;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs an XmlHttp request..\r\n * @param {string} verb The request type (GET/POST).\r\n * @param {goog.Uri} uri The request destination.\r\n * @param {string|number|undefined} id The request id.\r\n * @param {number} attempt Which attempt # the request was.\r\n * @param {?string} postData The data posted in the request.\r\n */\r\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\r\n verb, uri, id, attempt, postData) {\r\n var self = this;\r\n this.info(function() {\r\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\r\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs the meta data received from an XmlHttp request.\r\n * @param {string} verb The request type (GET/POST).\r\n * @param {goog.Uri} uri The request destination.\r\n * @param {string|number|undefined} id The request id.\r\n * @param {number} attempt Which attempt # the request was.\r\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\r\n * @param {number} statusCode The HTTP status code.\r\n */\r\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\r\n verb, uri, id, attempt, readyState, statusCode) {\r\n this.info(function() {\r\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\r\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs the response data received from an XmlHttp request.\r\n * @param {string|number|undefined} id The request id.\r\n * @param {?string} responseText The response text.\r\n * @param {?string=} opt_desc Optional request description.\r\n */\r\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\r\n id, responseText, opt_desc) {\r\n var self = this;\r\n this.info(function() {\r\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\r\n (opt_desc ? ' ' + opt_desc : '');\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs a request timeout.\r\n * @param {goog.Uri} uri The uri that timed out.\r\n */\r\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\r\n this.info(function() {\r\n return 'TIMEOUT: ' + uri;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs a debug message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.debug = function(text) {\r\n goog.log.fine(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Logs an exception\r\n * @param {Error} e The error or error event.\r\n * @param {goog.debug.Loggable=} opt_msg The optional message,\r\n * defaults to 'Exception'.\r\n */\r\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\r\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\r\n};\r\n\r\n\r\n/**\r\n * Logs an info message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.info = function(text) {\r\n goog.log.info(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Logs a warning message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.warning = function(text) {\r\n goog.log.warning(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Logs a severe message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.severe = function(text) {\r\n goog.log.error(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Removes potentially private data from a response so that we don't\r\n * accidentally save private and personal data to the server logs.\r\n * @param {?string} responseText A JSON response to clean.\r\n * @return {?string} The cleaned response.\r\n * @private\r\n */\r\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\r\n if (!this.redactEnabled_) {\r\n return responseText;\r\n }\r\n\r\n if (!responseText) {\r\n return null;\r\n }\r\n\r\n try {\r\n var responseArray = JSON.parse(responseText);\r\n if (responseArray) {\r\n for (var i = 0; i < responseArray.length; i++) {\r\n if (goog.isArray(responseArray[i])) {\r\n this.maybeRedactArray_(responseArray[i]);\r\n }\r\n }\r\n }\r\n\r\n return goog.json.serialize(responseArray);\r\n } catch (e) {\r\n this.debug('Exception parsing expected JS array - probably was not JS');\r\n return responseText;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes data from a response array that may be sensitive.\r\n * @param {!Array<?>} array The array to clean.\r\n * @private\r\n */\r\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\r\n if (array.length < 2) {\r\n return;\r\n }\r\n var dataPart = array[1];\r\n if (!goog.isArray(dataPart)) {\r\n return;\r\n }\r\n if (dataPart.length < 1) {\r\n return;\r\n }\r\n\r\n var type = dataPart[0];\r\n if (type != 'noop' && type != 'stop' && type != 'close') {\r\n // redact all fields in the array\r\n for (var i = 1; i < dataPart.length; i++) {\r\n dataPart[i] = '';\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes potentially private data from a request POST body so that we don't\r\n * accidentally save private and personal data to the server logs.\r\n * @param {?string} data The data string to clean.\r\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\r\n * @private\r\n */\r\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\r\n if (!this.redactEnabled_) {\r\n return data;\r\n }\r\n\r\n if (!data) {\r\n return null;\r\n }\r\n var out = '';\r\n var params = data.split('&');\r\n for (var i = 0; i < params.length; i++) {\r\n var param = params[i];\r\n var keyValue = param.split('=');\r\n if (keyValue.length > 1) {\r\n var key = keyValue[0];\r\n var value = keyValue[1];\r\n\r\n var keyParts = key.split('_');\r\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\r\n out += key + '=' + value + '&';\r\n } else {\r\n out += key + '=' +\r\n 'redacted' +\r\n '&';\r\n }\r\n }\r\n }\r\n return out;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Static utilities for collecting stats associated with\r\n * ChannelRequest.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.requestStats');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\r\n\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.EventTarget');\r\n\r\n\r\ngoog.scope(function() {\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\n\r\n\r\n/**\r\n * Events fired.\r\n * @const\r\n */\r\nrequestStats.Event = {};\r\n\r\n\r\n/**\r\n * Singleton event target for firing stat events\r\n * @type {goog.events.EventTarget}\r\n * @private\r\n */\r\nrequestStats.statEventTarget_ = new goog.events.EventTarget();\r\n\r\n\r\n/**\r\n * The type of event that occurs every time some information about how reachable\r\n * the server is is discovered.\r\n */\r\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\r\n\r\n\r\n/**\r\n * Types of events which reveal information about the reachability of the\r\n * server.\r\n * @enum {number}\r\n */\r\nrequestStats.ServerReachability = {\r\n REQUEST_MADE: 1,\r\n REQUEST_SUCCEEDED: 2,\r\n REQUEST_FAILED: 3,\r\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\r\n};\r\n\r\n\r\n\r\n/**\r\n * Event class for SERVER_REACHABILITY_EVENT.\r\n *\r\n * @param {goog.events.EventTarget} target The stat event target for\r\n the channel.\r\n * @param {requestStats.ServerReachability} reachabilityType\r\n * The reachability event type.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\r\n goog.events.Event.call(\r\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\r\n\r\n /**\r\n * @type {requestStats.ServerReachability}\r\n */\r\n this.reachabilityType = reachabilityType;\r\n};\r\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Notify the channel that a particular fine grained network event has occurred.\r\n * Should be considered package-private.\r\n * @param {requestStats.ServerReachability} reachabilityType\r\n * The reachability event type.\r\n */\r\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\r\n var target = requestStats.statEventTarget_;\r\n target.dispatchEvent(\r\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\r\n};\r\n\r\n\r\n/**\r\n * Stat Event that fires when things of interest happen that may be useful for\r\n * applications to know about for stats or debugging purposes.\r\n */\r\nrequestStats.Event.STAT_EVENT = 'statevent';\r\n\r\n\r\n/**\r\n * Enum that identifies events for statistics that are interesting to track.\r\n * @enum {number}\r\n */\r\nrequestStats.Stat = {\r\n /** Event indicating a new connection attempt. */\r\n CONNECT_ATTEMPT: 0,\r\n\r\n /** Event indicating a connection error due to a general network problem. */\r\n ERROR_NETWORK: 1,\r\n\r\n /**\r\n * Event indicating a connection error that isn't due to a general network\r\n * problem.\r\n */\r\n ERROR_OTHER: 2,\r\n\r\n /** Event indicating the start of test stage one. */\r\n TEST_STAGE_ONE_START: 3,\r\n\r\n /** Event indicating the start of test stage two. */\r\n TEST_STAGE_TWO_START: 4,\r\n\r\n /** Event indicating the first piece of test data was received. */\r\n TEST_STAGE_TWO_DATA_ONE: 5,\r\n\r\n /**\r\n * Event indicating that the second piece of test data was received and it was\r\n * received separately from the first.\r\n */\r\n TEST_STAGE_TWO_DATA_TWO: 6,\r\n\r\n /** Event indicating both pieces of test data were received simultaneously. */\r\n TEST_STAGE_TWO_DATA_BOTH: 7,\r\n\r\n /** Event indicating stage one of the test request failed. */\r\n TEST_STAGE_ONE_FAILED: 8,\r\n\r\n /** Event indicating stage two of the test request failed. */\r\n TEST_STAGE_TWO_FAILED: 9,\r\n\r\n /**\r\n * Event indicating that a buffering proxy is likely between the client and\r\n * the server.\r\n */\r\n PROXY: 10,\r\n\r\n /**\r\n * Event indicating that no buffering proxy is likely between the client and\r\n * the server.\r\n */\r\n NOPROXY: 11,\r\n\r\n /** Event indicating an unknown SID error. */\r\n REQUEST_UNKNOWN_SESSION_ID: 12,\r\n\r\n /** Event indicating a bad status code was received. */\r\n REQUEST_BAD_STATUS: 13,\r\n\r\n /** Event indicating incomplete data was received */\r\n REQUEST_INCOMPLETE_DATA: 14,\r\n\r\n /** Event indicating bad data was received */\r\n REQUEST_BAD_DATA: 15,\r\n\r\n /** Event indicating no data was received when data was expected. */\r\n REQUEST_NO_DATA: 16,\r\n\r\n /** Event indicating a request timeout. */\r\n REQUEST_TIMEOUT: 17,\r\n\r\n /**\r\n * Event indicating that the server never received our hanging GET and so it\r\n * is being retried.\r\n */\r\n BACKCHANNEL_MISSING: 18,\r\n\r\n /**\r\n * Event indicating that we have determined that our hanging GET is not\r\n * receiving data when it should be. Thus it is dead dead and will be retried.\r\n */\r\n BACKCHANNEL_DEAD: 19,\r\n\r\n /**\r\n * The browser declared itself offline during the lifetime of a request, or\r\n * was offline when a request was initially made.\r\n */\r\n BROWSER_OFFLINE: 20\r\n};\r\n\r\n\r\n\r\n/**\r\n * Event class for STAT_EVENT.\r\n *\r\n * @param {goog.events.EventTarget} eventTarget The stat event target for\r\n the channel.\r\n * @param {requestStats.Stat} stat The stat.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\nrequestStats.StatEvent = function(eventTarget, stat) {\r\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\r\n\r\n /**\r\n * The stat\r\n * @type {requestStats.Stat}\r\n */\r\n this.stat = stat;\r\n\r\n};\r\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Returns the singleton event target for stat events.\r\n * @return {goog.events.EventTarget} The event target for stat events.\r\n */\r\nrequestStats.getStatEventTarget = function() {\r\n return requestStats.statEventTarget_;\r\n};\r\n\r\n\r\n/**\r\n * Helper function to call the stat event callback.\r\n * @param {requestStats.Stat} stat The stat.\r\n */\r\nrequestStats.notifyStatEvent = function(stat) {\r\n var target = requestStats.statEventTarget_;\r\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\r\n};\r\n\r\n\r\n/**\r\n * An event that fires when POST requests complete successfully, indicating\r\n * the size of the POST and the round trip time.\r\n */\r\nrequestStats.Event.TIMING_EVENT = 'timingevent';\r\n\r\n\r\n\r\n/**\r\n * Event class for requestStats.Event.TIMING_EVENT\r\n *\r\n * @param {goog.events.EventTarget} target The stat event target for\r\n the channel.\r\n * @param {number} size The number of characters in the POST data.\r\n * @param {number} rtt The total round trip time from POST to response in MS.\r\n * @param {number} retries The number of times the POST had to be retried.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\r\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.size = size;\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.rtt = rtt;\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.retries = retries;\r\n\r\n};\r\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Helper function to notify listeners about POST request performance.\r\n *\r\n * @param {number} size Number of characters in the POST data.\r\n * @param {number} rtt The amount of time from POST start to response.\r\n * @param {number} retries The number of times the POST had to be retried.\r\n */\r\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\r\n var target = requestStats.statEventTarget_;\r\n target.dispatchEvent(\r\n new requestStats.TimingEvent(target, size, rtt, retries));\r\n};\r\n\r\n\r\n/**\r\n * Allows the application to set an execution hooks for when a channel\r\n * starts processing requests. This is useful to track timing or logging\r\n * special information. The function takes no parameters and return void.\r\n * @param {Function} startHook The function for the start hook.\r\n */\r\nrequestStats.setStartThreadExecutionHook = function(startHook) {\r\n requestStats.startExecutionHook_ = startHook;\r\n};\r\n\r\n\r\n/**\r\n * Allows the application to set an execution hooks for when a channel\r\n * stops processing requests. This is useful to track timing or logging\r\n * special information. The function takes no parameters and return void.\r\n * @param {Function} endHook The function for the end hook.\r\n */\r\nrequestStats.setEndThreadExecutionHook = function(endHook) {\r\n requestStats.endExecutionHook_ = endHook;\r\n};\r\n\r\n\r\n/**\r\n * Application provided execution hook for the start hook.\r\n *\r\n * @type {Function}\r\n * @private\r\n */\r\nrequestStats.startExecutionHook_ = function() {};\r\n\r\n\r\n/**\r\n * Application provided execution hook for the end hook.\r\n *\r\n * @type {Function}\r\n * @private\r\n */\r\nrequestStats.endExecutionHook_ = function() {};\r\n\r\n\r\n/**\r\n * Helper function to call the start hook\r\n */\r\nrequestStats.onStartExecution = function() {\r\n requestStats.startExecutionHook_();\r\n};\r\n\r\n\r\n/**\r\n * Helper function to call the end hook\r\n */\r\nrequestStats.onEndExecution = function() {\r\n requestStats.endExecutionHook_();\r\n};\r\n\r\n\r\n/**\r\n * Wrapper around SafeTimeout which calls the start and end execution hooks\r\n * with a try...finally block.\r\n * @param {Function} fn The callback function.\r\n * @param {number} ms The time in MS for the timer.\r\n * @return {number} The ID of the timer.\r\n */\r\nrequestStats.setTimeout = function(fn, ms) {\r\n if (!goog.isFunction(fn)) {\r\n throw new Error('Fn must not be null and must be a function');\r\n }\r\n return goog.global.setTimeout(function() {\r\n requestStats.onStartExecution();\r\n try {\r\n fn();\r\n } finally {\r\n requestStats.onEndExecution();\r\n }\r\n }, ms);\r\n};\r\n}); // goog.scope\r\n","// Copyright 2007 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Error codes shared between goog.net.IframeIo and\r\n * goog.net.XhrIo.\r\n */\r\n\r\ngoog.provide('goog.net.ErrorCode');\r\n\r\n\r\n/**\r\n * Error codes\r\n * @enum {number}\r\n */\r\ngoog.net.ErrorCode = {\r\n\r\n /**\r\n * There is no error condition.\r\n */\r\n NO_ERROR: 0,\r\n\r\n /**\r\n * The most common error from iframeio, unfortunately, is that the browser\r\n * responded with an error page that is classed as a different domain. The\r\n * situations, are when a browser error page is shown -- 404, access denied,\r\n * DNS failure, connection reset etc.)\r\n *\r\n */\r\n ACCESS_DENIED: 1,\r\n\r\n /**\r\n * Currently the only case where file not found will be caused is when the\r\n * code is running on the local file system and a non-IE browser makes a\r\n * request to a file that doesn't exist.\r\n */\r\n FILE_NOT_FOUND: 2,\r\n\r\n /**\r\n * If Firefox shows a browser error page, such as a connection reset by\r\n * server or access denied, then it will fail silently without the error or\r\n * load handlers firing.\r\n */\r\n FF_SILENT_ERROR: 3,\r\n\r\n /**\r\n * Custom error provided by the client through the error check hook.\r\n */\r\n CUSTOM_ERROR: 4,\r\n\r\n /**\r\n * Exception was thrown while processing the request.\r\n */\r\n EXCEPTION: 5,\r\n\r\n /**\r\n * The Http response returned a non-successful http status code.\r\n */\r\n HTTP_ERROR: 6,\r\n\r\n /**\r\n * The request was aborted.\r\n */\r\n ABORT: 7,\r\n\r\n /**\r\n * The request timed out.\r\n */\r\n TIMEOUT: 8,\r\n\r\n /**\r\n * The resource is not available offline.\r\n */\r\n OFFLINE: 9\r\n};\r\n\r\n\r\n/**\r\n * Returns a friendly error message for an error code. These messages are for\r\n * debugging and are not localized.\r\n * @param {goog.net.ErrorCode} errorCode An error code.\r\n * @return {string} A message for debugging.\r\n */\r\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\r\n switch (errorCode) {\r\n case goog.net.ErrorCode.NO_ERROR:\r\n return 'No Error';\r\n\r\n case goog.net.ErrorCode.ACCESS_DENIED:\r\n return 'Access denied to content document';\r\n\r\n case goog.net.ErrorCode.FILE_NOT_FOUND:\r\n return 'File not found';\r\n\r\n case goog.net.ErrorCode.FF_SILENT_ERROR:\r\n return 'Firefox silently errored';\r\n\r\n case goog.net.ErrorCode.CUSTOM_ERROR:\r\n return 'Application custom error';\r\n\r\n case goog.net.ErrorCode.EXCEPTION:\r\n return 'An exception occurred';\r\n\r\n case goog.net.ErrorCode.HTTP_ERROR:\r\n return 'Http response at 400 or 500 level';\r\n\r\n case goog.net.ErrorCode.ABORT:\r\n return 'Request was aborted';\r\n\r\n case goog.net.ErrorCode.TIMEOUT:\r\n return 'Request timed out';\r\n\r\n case goog.net.ErrorCode.OFFLINE:\r\n return 'The resource is not available offline';\r\n\r\n default:\r\n return 'Unrecognized error code';\r\n }\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Common events for the network classes.\r\n */\r\n\r\n\r\ngoog.provide('goog.net.EventType');\r\n\r\n\r\n/**\r\n * Event names for network events\r\n * @enum {string}\r\n */\r\ngoog.net.EventType = {\r\n COMPLETE: 'complete',\r\n SUCCESS: 'success',\r\n ERROR: 'error',\r\n ABORT: 'abort',\r\n READY: 'ready',\r\n READY_STATE_CHANGE: 'readystatechange',\r\n TIMEOUT: 'timeout',\r\n INCREMENTAL_DATA: 'incrementaldata',\r\n PROGRESS: 'progress',\r\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\r\n // goog.net.XhrIo to allow binding listeners specific to each type of\r\n // progress.\r\n DOWNLOAD_PROGRESS: 'downloadprogress',\r\n UPLOAD_PROGRESS: 'uploadprogress'\r\n};\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\r\n * and metadata about them.\r\n * @author dbk@google.com (David Barrett-Kahn)\r\n */\r\n\r\ngoog.provide('goog.net.XmlHttpFactory');\r\n\r\n/** @suppress {extraRequire} Typedef. */\r\ngoog.require('goog.net.XhrLike');\r\n\r\n\r\n\r\n/**\r\n * Abstract base class for an XmlHttpRequest factory.\r\n * @constructor\r\n */\r\ngoog.net.XmlHttpFactory = function() {};\r\n\r\n\r\n/**\r\n * Cache of options - we only actually call internalGetOptions once.\r\n * @type {?Object}\r\n * @private\r\n */\r\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\r\n\r\n\r\n/**\r\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\r\n */\r\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @return {Object} Options describing how xhr objects obtained from this\r\n * factory should be used.\r\n */\r\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\r\n return this.cachedOptions_ ||\r\n (this.cachedOptions_ = this.internalGetOptions());\r\n};\r\n\r\n\r\n/**\r\n * Override this method in subclasses to preserve the caching offered by\r\n * getOptions().\r\n * @return {Object} Options describing how xhr objects obtained from this\r\n * factory should be used.\r\n * @protected\r\n */\r\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Low level handling of XMLHttpRequest.\r\n * @author arv@google.com (Erik Arvidsson)\r\n * @author dbk@google.com (David Barrett-Kahn)\r\n */\r\n\r\ngoog.provide('goog.net.DefaultXmlHttpFactory');\r\ngoog.provide('goog.net.XmlHttp');\r\ngoog.provide('goog.net.XmlHttp.OptionType');\r\ngoog.provide('goog.net.XmlHttp.ReadyState');\r\ngoog.provide('goog.net.XmlHttpDefines');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.net.WrapperXmlHttpFactory');\r\ngoog.require('goog.net.XmlHttpFactory');\r\n\r\n\r\n/**\r\n * Static class for creating XMLHttpRequest objects.\r\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\r\n */\r\ngoog.net.XmlHttp = function() {\r\n return goog.net.XmlHttp.factory_.createInstance();\r\n};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\r\n * true bypasses the ActiveX probing code.\r\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\r\n * out the ActiveX probing code from binaries. To achieve this, use\r\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\r\n * TODO(ruilopes): Collapse both defines.\r\n */\r\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\r\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\r\n\r\n\r\n/** @const */\r\ngoog.net.XmlHttpDefines = {};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\r\n * true eliminates the ActiveX probing code.\r\n */\r\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\r\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\r\n\r\n\r\n/**\r\n * Gets the options to use with the XMLHttpRequest objects obtained using\r\n * the static methods.\r\n * @return {Object} The options.\r\n */\r\ngoog.net.XmlHttp.getOptions = function() {\r\n return goog.net.XmlHttp.factory_.getOptions();\r\n};\r\n\r\n\r\n/**\r\n * Type of options that an XmlHttp object can have.\r\n * @enum {number}\r\n */\r\ngoog.net.XmlHttp.OptionType = {\r\n /**\r\n * Whether a goog.nullFunction should be used to clear the onreadystatechange\r\n * handler instead of null.\r\n */\r\n USE_NULL_FUNCTION: 0,\r\n\r\n /**\r\n * NOTE(user): In IE if send() errors on a *local* request the readystate\r\n * is still changed to COMPLETE. We need to ignore it and allow the\r\n * try/catch around send() to pick up the error.\r\n */\r\n LOCAL_REQUEST_ERROR: 1\r\n};\r\n\r\n\r\n/**\r\n * Status constants for XMLHTTP, matches:\r\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\r\n * @enum {number}\r\n */\r\ngoog.net.XmlHttp.ReadyState = {\r\n /**\r\n * Constant for when xmlhttprequest.readyState is uninitialized\r\n */\r\n UNINITIALIZED: 0,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is loading.\r\n */\r\n LOADING: 1,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is loaded.\r\n */\r\n LOADED: 2,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is in an interactive state.\r\n */\r\n INTERACTIVE: 3,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is completed\r\n */\r\n COMPLETE: 4\r\n};\r\n\r\n\r\n/**\r\n * The global factory instance for creating XMLHttpRequest objects.\r\n * @type {goog.net.XmlHttpFactory}\r\n * @private\r\n */\r\ngoog.net.XmlHttp.factory_;\r\n\r\n\r\n/**\r\n * Sets the factories for creating XMLHttpRequest objects and their options.\r\n * @param {Function} factory The factory for XMLHttpRequest objects.\r\n * @param {Function} optionsFactory The factory for options.\r\n * @deprecated Use setGlobalFactory instead.\r\n */\r\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\r\n goog.net.XmlHttp.setGlobalFactory(\r\n new goog.net.WrapperXmlHttpFactory(\r\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\r\n};\r\n\r\n\r\n/**\r\n * Sets the global factory object.\r\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\r\n */\r\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\r\n goog.net.XmlHttp.factory_ = factory;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Default factory to use when creating xhr objects. You probably shouldn't be\r\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\r\n * @extends {goog.net.XmlHttpFactory}\r\n * @constructor\r\n */\r\ngoog.net.DefaultXmlHttpFactory = function() {\r\n goog.net.XmlHttpFactory.call(this);\r\n};\r\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\r\n\r\n\r\n/** @override */\r\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\r\n var progId = this.getProgId_();\r\n if (progId) {\r\n return new ActiveXObject(progId);\r\n } else {\r\n return new XMLHttpRequest();\r\n }\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\r\n var progId = this.getProgId_();\r\n var options = {};\r\n if (progId) {\r\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\r\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\r\n }\r\n return options;\r\n};\r\n\r\n\r\n/**\r\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\r\n * @type {string|undefined}\r\n * @private\r\n */\r\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\r\n\r\n\r\n/**\r\n * Initialize the private state used by other functions.\r\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\r\n * @private\r\n */\r\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\r\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\r\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\r\n return '';\r\n }\r\n\r\n // The following blog post describes what PROG IDs to use to create the\r\n // XMLHTTP object in Internet Explorer:\r\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\r\n // However we do not (yet) fully trust that this will be OK for old versions\r\n // of IE on Win9x so we therefore keep the last 2.\r\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\r\n typeof ActiveXObject != 'undefined') {\r\n // Candidate Active X types.\r\n var ACTIVE_X_IDENTS = [\r\n 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP',\r\n 'Microsoft.XMLHTTP'\r\n ];\r\n for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) {\r\n var candidate = ACTIVE_X_IDENTS[i];\r\n\r\n try {\r\n new ActiveXObject(candidate);\r\n // NOTE(user): cannot assign progid and return candidate in one line\r\n // because JSCompiler complaings: BUG 658126\r\n this.ieProgId_ = candidate;\r\n return candidate;\r\n } catch (e) {\r\n // do nothing; try next choice\r\n }\r\n }\r\n\r\n // couldn't find any matches\r\n throw new Error(\r\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\r\n ' or MSXML might not be installed');\r\n }\r\n\r\n return /** @type {string} */ (this.ieProgId_);\r\n};\r\n\r\n\r\n// Set the global factory to an instance of the default factory.\r\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview The API spec for the WebChannel messaging library.\r\n *\r\n * Similar to HTML5 WebSocket and Closure BrowserChannel, WebChannel\r\n * offers an abstraction for point-to-point socket-like communication between\r\n * a browser client and a remote origin.\r\n *\r\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\r\n * may be multiplexed over the same WebChannelTransport, which represents\r\n * the underlying physical connectivity over standard wire protocols\r\n * such as HTTP and SPDY.\r\n *\r\n * A WebChannels in turn represents a logical communication channel between\r\n * the client and server end point. A WebChannel remains open for\r\n * as long as the client or server end-point allows.\r\n *\r\n * Messages may be delivered in-order or out-of-order, reliably or unreliably\r\n * over the same WebChannel. Message delivery guarantees of a WebChannel is\r\n * to be specified by the application code; and the choice of the\r\n * underlying wire protocols is completely transparent to the API users.\r\n *\r\n * Client-to-client messaging via WebRTC based transport may also be support\r\n * via the same WebChannel API in future.\r\n *\r\n * Note that we have no immediate plan to move this API out of labs. While\r\n * the implementation is production ready, the API is subject to change\r\n * (addition only):\r\n * 1. Adopt new Web APIs (mainly whatwg streams) and goog.net.streams.\r\n * 2. New programming models for cloud (on the server-side) may require\r\n * new APIs to be defined.\r\n * 3. WebRTC DataChannel alignment\r\n *\r\n */\r\n\r\ngoog.provide('goog.net.WebChannel');\r\n\r\ngoog.require('goog.events');\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.Listenable');\r\ngoog.require('goog.net.XmlHttpFactory');\r\n\r\n\r\n\r\n/**\r\n * A WebChannel represents a logical bi-directional channel over which the\r\n * client communicates with a remote server that holds the other endpoint\r\n * of the channel. A WebChannel is always created in the context of a shared\r\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\r\n * and server-side implementations to decide how or when multiplexing is\r\n * to be enabled.\r\n *\r\n * @interface\r\n * @extends {EventTarget}\r\n * @extends {goog.events.Listenable}\r\n */\r\ngoog.net.WebChannel = function() {};\r\n\r\n\r\n\r\n/**\r\n * This interface defines a pluggable API to allow WebChannel runtime to support\r\n * customized algorithms in order to recover from transient failures such as\r\n * those failures caused by network or proxies (intermediaries).\r\n *\r\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\r\n * offline mode.\r\n *\r\n * Extra measurements and logging could also be implemented in the custom\r\n * module, which has the full knowledge of all the state transitions\r\n * (due to failures).\r\n *\r\n * A default algorithm will be provided by the webchannel library itself. Custom\r\n * algorithms are expected to be tailored to specific client platforms or\r\n * networking environments, e.g. mobile, cellular network.\r\n *\r\n * @interface\r\n */\r\ngoog.net.WebChannel.FailureRecovery = function() {};\r\n\r\n\r\n/**\r\n * Configuration spec for newly created WebChannel instances.\r\n *\r\n * WebChannels are configured in the context of the containing\r\n * {@link WebChannelTransport}. The configuration parameters are specified\r\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\r\n *\r\n * messageHeaders: custom headers to be added to every message sent to the\r\n * server. This object is mutable, and custom headers may be changed, removed,\r\n * or added during the runtime after a channel has been opened.\r\n *\r\n * initMessageHeaders: similar to messageHeaders, but any custom headers will\r\n * be sent only once when the channel is opened. Typical usage is to send\r\n * an auth header to the server, which only checks the auth header at the time\r\n * when the channel is opened.\r\n *\r\n * messageContentType: sent as initMessageHeaders via X-WebChannel-Content-Type,\r\n * to inform the server the MIME type of WebChannel messages.\r\n *\r\n * messageUrlParams: custom url query parameters to be added to every message\r\n * sent to the server. This object is mutable, and custom parameters may be\r\n * changed, removed or added during the runtime after a channel has been opened.\r\n *\r\n * clientProtocolHeaderRequired: whether a special header should be added to\r\n * each message so that the server can dispatch webchannel messages without\r\n * knowing the URL path prefix. Defaults to false.\r\n *\r\n * concurrentRequestLimit: the maximum number of in-flight HTTP requests allowed\r\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\r\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\r\n * will have no effect.\r\n *\r\n * supportsCrossDomainXhr: setting this to true to allow the use of sub-domains\r\n * (as configured by the server) to send XHRs with the CORS withCredentials\r\n * bit set to true.\r\n *\r\n * testUrl: the test URL for detecting connectivity during the initial\r\n * handshake. This parameter defaults to \"/<channel_url>/test\".\r\n *\r\n * sendRawJson: whether to bypass v8 encoding of client-sent messages.\r\n * This defaults to false now due to legacy servers. New applications should\r\n * always configure this option to true.\r\n *\r\n * httpSessionIdParam: the URL parameter name that contains the session id (\r\n * for sticky routing of HTTP requests). When this param is specified, a server\r\n * that supports this option will respond with an opaque session id as part of\r\n * the initial handshake (via the X-HTTP-Session-Id header); and all the\r\n * subsequent requests will contain the httpSessionIdParam. This option will\r\n * take precedence over any duplicated parameter specified with\r\n * messageUrlParams, whose value will be ignored.\r\n *\r\n * httpHeadersOverwriteParam: the URL parameter name to allow custom HTTP\r\n * headers to be overwritten as a URL param to bypass CORS preflight.\r\n * goog.net.rpc.HttpCors is used to encode the HTTP headers.\r\n *\r\n * backgroundChannelTest: whether to run the channel test (detecting networking\r\n * conditions) as a background process so the OPEN event will be fired sooner\r\n * to reduce the initial handshake delay. This option defaults to true.\r\n * The actual background channel test is not fully implemented.\r\n *\r\n * forceLongPolling: whether to force long-polling from client to server.\r\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\r\n * is buffering data sent by the server.\r\n *\r\n * fastHandshake: enable true 0-RTT message delivery, including\r\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\r\n * defaults to false. Note it is allowed to send messages before Open event is\r\n * received, after a channel has been opened. In order to enable 0-RTT,\r\n * messages will be encoded as part of URL and therefore there needs be a size\r\n * limit for those initial messages that are sent immediately as part of the\r\n * GET handshake request. With sendRawJson=true, this limit is currently set\r\n * to 4K chars and data beyond this limit will be buffered till the handshake\r\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\r\n * to limit the amount of data that is sent as part of the handshake.\r\n *\r\n * disableRedact: whether to disable logging redact. By default, redact is\r\n * enabled to remove any message payload or user-provided info\r\n * from closure logs.\r\n *\r\n * clientProfile: inform the server about the client profile to enable\r\n * customized configs that are optimized for certain clients or environments.\r\n * Currently this information is sent via X-WebChannel-Client-Profile header.\r\n *\r\n * internalChannelParams: the internal channel parameter name to allow\r\n * experimental channel configurations. Supported options include fastfail,\r\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\r\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\r\n * change.\r\n *\r\n * xmlHttpFactory: allows the caller to override the factory used to create\r\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\r\n *\r\n * requestRefreshThresholds: client-side thresholds that decide when to refresh\r\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\r\n * or compression context. The client-side thresholds should be signficantly\r\n * smaller than the server-side thresholds. This allows the client to eliminate\r\n * any latency introduced by request refreshing, i.e. an RTT window during which\r\n * messages may be buffered on the server-side. Supported params include\r\n * totalBytesReceived, totalDurationMs.\r\n *\r\n * @typedef {{\r\n * messageHeaders: (!Object<string, string>|undefined),\r\n * initMessageHeaders: (!Object<string, string>|undefined),\r\n * messageContentType: (string|undefined),\r\n * messageUrlParams: (!Object<string, string>|undefined),\r\n * clientProtocolHeaderRequired: (boolean|undefined),\r\n * concurrentRequestLimit: (number|undefined),\r\n * supportsCrossDomainXhr: (boolean|undefined),\r\n * testUrl: (string|undefined),\r\n * sendRawJson: (boolean|undefined),\r\n * httpSessionIdParam: (string|undefined),\r\n * httpHeadersOverwriteParam: (string|undefined),\r\n * backgroundChannelTest: (boolean|undefined),\r\n * forceLongPolling: (boolean|undefined),\r\n * fastHandshake: (boolean|undefined),\r\n * disableRedact: (boolean|undefined),\r\n * clientProfile: (string|undefined),\r\n * internalChannelParams: (!Object<string, boolean|number>|undefined),\r\n * xmlHttpFactory: (!goog.net.XmlHttpFactory|undefined),\r\n * requestRefreshThresholds: (!Object<string, number>|undefined),\r\n * }}\r\n */\r\ngoog.net.WebChannel.Options;\r\n\r\n\r\n/**\r\n * Types that are allowed as message data.\r\n *\r\n * Note that JS objects (sent by the client) can only have string encoded\r\n * values due to the limitation of the current wire protocol.\r\n *\r\n * Unicode strings (sent by the server) may or may not need be escaped, as\r\n * decided by the server.\r\n *\r\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\r\n */\r\ngoog.net.WebChannel.MessageData;\r\n\r\n\r\n/**\r\n * Open the WebChannel against the URI specified in the constructor.\r\n */\r\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Close the WebChannel.\r\n *\r\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\r\n * to any in-flight messages sent to the server.\r\n *\r\n * If you need such a guarantee, see the Half the halfClose() method.\r\n */\r\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Half-close the WebChannel.\r\n *\r\n * Half-close semantics:\r\n * 1. delivered as a regular message in FIFO programming order\r\n * 2. the server is expected to return a half-close too (with or without\r\n * application involved), which will trigger a full close (shutdown)\r\n * on the client side\r\n * 3. for now, the half-close event defined for server-initiated\r\n * half-close is not exposed to the client application\r\n * 4. a client-side half-close may be triggered internally when the client\r\n * receives a half-close from the server; and the client is expected to\r\n * do a full close after the half-close is acked and delivered\r\n * on the server-side.\r\n * 5. Full close is always a forced one. See the close() method.\r\n *\r\n * New messages sent after halfClose() will be dropped.\r\n *\r\n * NOTE: This is not yet implemented, and will throw an exception if called.\r\n */\r\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Sends a message to the server that maintains the other end point of\r\n * the WebChannel.\r\n *\r\n * O-RTT behavior:\r\n * 1. messages sent before open() is called will always be delivered as\r\n * part of the handshake, i.e. with 0-RTT\r\n * 2. messages sent after open() is called but before the OPEN event\r\n * is received will be delivered as part of the handshake if\r\n * send() is called from the same execution context as open().\r\n * 3. otherwise, those messages will be buffered till the handshake\r\n * is completed (which will fire the OPEN event).\r\n *\r\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\r\n */\r\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Common events fired by WebChannels.\r\n * @enum {string}\r\n */\r\ngoog.net.WebChannel.EventType = {\r\n /** Dispatched when the channel is opened. */\r\n OPEN: goog.events.getUniqueId('open'),\r\n\r\n /** Dispatched when the channel is closed. */\r\n CLOSE: goog.events.getUniqueId('close'),\r\n\r\n /**\r\n * Dispatched when the channel is aborted due to errors.\r\n *\r\n * For backward compatibility reasons, a CLOSE event will also be\r\n * dispatched, following the ERROR event, which indicates that the channel\r\n * has been completely shutdown .\r\n */\r\n ERROR: goog.events.getUniqueId('error'),\r\n\r\n /** Dispatched when the channel has received a new message. */\r\n MESSAGE: goog.events.getUniqueId('message')\r\n};\r\n\r\n\r\n\r\n/**\r\n * The event interface for the MESSAGE event.\r\n *\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\ngoog.net.WebChannel.MessageEvent = function() {\r\n goog.net.WebChannel.MessageEvent.base(\r\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\r\n};\r\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * The content of the message received from the server.\r\n *\r\n * @type {!goog.net.WebChannel.MessageData}\r\n */\r\ngoog.net.WebChannel.MessageEvent.prototype.data;\r\n\r\n\r\n/**\r\n * The metadata key when the MESSAGE event represents a metadata message.\r\n *\r\n * @type {string|undefined}\r\n */\r\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\r\n\r\n\r\n/**\r\n * WebChannel level error conditions.\r\n *\r\n * Summary of error debugging and reporting in WebChannel:\r\n *\r\n * Network Error\r\n * 1. By default the webchannel library will set the error status to\r\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\r\n * may be recovered by the application by retrying and opening a new channel.\r\n * 2. There may be lost messages (not acked by the server) when a channel is\r\n * aborted. Currently we don't have a public API to retrieve messages that\r\n * are waiting to be acked on the client side. File a bug if you think it\r\n * is useful to expose such an API.\r\n * 3. Details of why a channel fails are available via closure debug logs,\r\n * and stats events (see webchannel/requeststats.js). Those are internal\r\n * stats and are subject to change. File a bug if you think it's useful to\r\n * version and expose such stats as part of the WebChannel API.\r\n *\r\n * Server Error\r\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\r\n * when auth fails.\r\n * 2. We don't currently generate any such errors, because most of the time\r\n * it's the responsibility of upper-layer frameworks or the application\r\n * itself to indicate to the client why a webchannel has been failed\r\n * by the server.\r\n * 3. When a channel is failed by the server explicitly, we still signal\r\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\r\n * server does a fail-over, or becomes overloaded, or conducts a forced\r\n * shutdown etc.\r\n * 4. We use some heuristic to decide if the network (aka cloud) is down\r\n * v.s. the actual server is down.\r\n *\r\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\r\n * the client to indicate the HTTP response status code of the last HTTP\r\n * request initiated by the WebChannel client library, for debugging\r\n * purposes only.\r\n *\r\n * See WebChannel.Options.backChannelFailureRecovery and\r\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\r\n *\r\n * @enum {number}\r\n */\r\ngoog.net.WebChannel.ErrorStatus = {\r\n /** No error has occurred. */\r\n OK: 0,\r\n\r\n /** Communication to the server has failed. */\r\n NETWORK_ERROR: 1,\r\n\r\n /** The server fails to accept or process the WebChannel. */\r\n SERVER_ERROR: 2\r\n};\r\n\r\n\r\n\r\n/**\r\n * The event interface for the ERROR event.\r\n *\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\ngoog.net.WebChannel.ErrorEvent = function() {\r\n goog.net.WebChannel.ErrorEvent.base(\r\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\r\n};\r\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * The error status.\r\n *\r\n * @type {!goog.net.WebChannel.ErrorStatus}\r\n */\r\ngoog.net.WebChannel.ErrorEvent.prototype.status;\r\n\r\n\r\n/**\r\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\r\n * of the WebChannel instance.\r\n */\r\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\r\n\r\n\r\n\r\n/**\r\n * The runtime properties of the WebChannel instance.\r\n *\r\n * This class is defined for debugging and monitoring purposes, as well as for\r\n * runtime functions that the application may choose to manage by itself.\r\n *\r\n * @interface\r\n */\r\ngoog.net.WebChannel.RuntimeProperties = function() {};\r\n\r\n\r\n/**\r\n * @return {number} The effective limit for the number of concurrent HTTP\r\n * requests that are allowed to be made for sending messages from the client\r\n * to the server. When SPDY is not enabled, this limit will be one.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * For applications that need support multiple channels (e.g. from\r\n * different tabs) to the same origin, use this method to decide if SPDY is\r\n * enabled and therefore it is safe to open multiple channels.\r\n *\r\n * If SPDY is disabled, the application may choose to limit the number of active\r\n * channels to one or use other means such as sub-domains to work around\r\n * the browser connection limit.\r\n *\r\n * @return {boolean} Whether SPDY is enabled for the origin against which\r\n * the channel is created.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @return {number} The number of requests (for sending messages to the server)\r\n * that are pending. If this number is approaching the value of\r\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\r\n * a higher latency.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * For applications to query the current HTTP session id, sent by the server\r\n * during the initial handshake.\r\n *\r\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Experimental API.\r\n *\r\n * This method generates an in-band commit request to the server, which will\r\n * ack the commit request as soon as all messages sent prior to this commit\r\n * request have been committed by the application.\r\n *\r\n * Committing a message has a stronger semantics than delivering a message\r\n * to the application. Detail spec:\r\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * Timeout or cancellation is not supported and the application is expected to\r\n * abort the channel if the commit-ack fails to arrive in time.\r\n *\r\n * ===\r\n *\r\n * This is currently implemented only in the client layer and the commit\r\n * callback will be invoked after all the pending client-sent messages have been\r\n * delivered by the server-side webchannel end-point. This semantics is\r\n * different and weaker than what's required for end-to-end ack which requires\r\n * the server application to ack the in-order delivery of messages that are sent\r\n * before the commit request is issued.\r\n *\r\n * Commit should only be called after the channel open event is received.\r\n * Duplicated commits are allowed and only the last callback is guaranteed.\r\n * Commit called after the channel has been closed will be ignored.\r\n *\r\n * @param {function()} callback The callback will be invoked once an\r\n * ack has been received for the current commit or any newly issued commit.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * This method may be used by the application to recover from a peer failure\r\n * or to enable sender-initiated flow-control.\r\n *\r\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @return {number} The total number of messages that have not received\r\n * commit-ack from the server; or if no commit has been issued, the number\r\n * of messages that have not been delivered to the server application.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * A low water-mark message count to notify the application when the\r\n * flow-control condition is cleared, that is, when the application is\r\n * able to send more messages.\r\n *\r\n * We expect the application to configure a high water-mark message count,\r\n * which is checked via getNonAckedMessageCount(). When the high water-mark\r\n * is exceeded, the application should install a callback via this method\r\n * to be notified when to start to send new messages.\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @param {number} count The low water-mark count. It is an error to pass\r\n * a non-positive value.\r\n * @param {function()} callback The call back to notify the application\r\n * when NonAckedMessageCount is below the specified low water-mark count.\r\n * Any previously registered callback is cleared. This new callback will\r\n * be cleared once it has been fired, or when the channel is closed or aborted.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Experimental API.\r\n *\r\n * This method registers a callback to handle the commit request sent\r\n * by the server. Commit protocol spec:\r\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @param {function(!Object)} callback The callback will take an opaque\r\n * commitId which needs be passed back to the server when an ack-commit\r\n * response is generated by the client application, via ackCommit().\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Experimental API.\r\n *\r\n * This method is used by the application to generate an ack-commit response\r\n * for the given commitId. Commit protocol spec:\r\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @param {!Object} commitId The commitId which denotes the commit request\r\n * from the server that needs be ack'ed.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @return {number} The last HTTP status code received by the channel.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Enum to indicate the current recovery state.\r\n *\r\n * @enum {string}\r\n */\r\ngoog.net.WebChannel.FailureRecovery.State = {\r\n /** Initial state. */\r\n INIT: 'init',\r\n\r\n /** Once a failure has been detected. */\r\n FAILED: 'failed',\r\n\r\n /**\r\n * Once a recovery operation has been issued, e.g. a new request to resume\r\n * communication.\r\n */\r\n RECOVERING: 'recovering',\r\n\r\n /** The channel has been closed. */\r\n CLOSED: 'closed'\r\n};\r\n\r\n\r\n/**\r\n * Enum to indicate different failure conditions as detected by the webchannel\r\n * runtime.\r\n *\r\n * This enum is to be used only between the runtime and FailureRecovery module,\r\n * and new states are expected to be introduced in future.\r\n *\r\n * @enum {string}\r\n */\r\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\r\n /**\r\n * The HTTP response returned a non-successful http status code.\r\n */\r\n HTTP_ERROR: 'http_error',\r\n\r\n /**\r\n * The request was aborted.\r\n */\r\n ABORT: 'abort',\r\n\r\n /**\r\n * The request timed out.\r\n */\r\n TIMEOUT: 'timeout',\r\n\r\n /**\r\n * Exception was thrown while processing the request/response.\r\n */\r\n EXCEPTION: 'exception'\r\n};\r\n\r\n\r\n/**\r\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\r\n * mainly for debugging use.\r\n */\r\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * This method is for WebChannel runtime to set the current failure condition\r\n * and to provide a callback for the algorithm to signal to the runtime\r\n * when it is time to issue a recovery operation, e.g. a new request to the\r\n * server.\r\n *\r\n * Supported transitions include:\r\n * INIT->FAILED\r\n * FAILED->FAILED (re-entry ok)\r\n * RECOVERY->FAILED.\r\n *\r\n * Ignored if state == CLOSED.\r\n *\r\n * Advanced implementations are expected to track all the state transitions\r\n * and their timestamps for monitoring purposes.\r\n *\r\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\r\n * new failure condition generated by the WebChannel runtime.\r\n * @param {!Function} operation The callback function to the WebChannel\r\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\r\n * recovery algorithm will issue timeout-based recovery operations.\r\n * Post-condition for the callback: state transition to RECOVERING.\r\n *\r\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\r\n * as decided by the failure recovery module. Upon a recoverable failure event,\r\n * the state is transitioned to RECOVERING; or the state is transitioned to\r\n * FAILED which indicates a fail-fast decision for the runtime to execute.\r\n */\r\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * The Webchannel runtime needs call this method when webchannel is closed or\r\n * aborted.\r\n *\r\n * Once the instance is closed, any access to the instance will be a no-op.\r\n */\r\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * A request header to indicate to the server the messaging protocol\r\n * each HTTP message is speaking.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\r\n\r\n\r\n/**\r\n * The value for x-client-protocol when the messaging protocol is WebChannel.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\r\n\r\n\r\n/**\r\n * A response header for the server to signal the wire-protocol that\r\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\r\n * \"quic\". This information avoids the need to use private APIs to decide if\r\n * HTTP requests are multiplexed etc.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\r\n\r\n\r\n/**\r\n * A response header for the server to send back the HTTP session id as part of\r\n * the initial handshake. The value of the HTTP session id is opaque to the\r\n * WebChannel protocol.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\r\n\r\n\r\n/**\r\n * A response header for the server to send back any initial response data as a\r\n * header to avoid any possible buffering by an intermediary, which may\r\n * be undesired during the handshake.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\r\n\r\n\r\n/**\r\n * A request header for specifying the content-type of WebChannel messages,\r\n * e.g. application-defined JSON encoding styles. Currently this header\r\n * is sent by the client via initMessageHeaders when the channel is opened.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\r\n\r\n\r\n/**\r\n * A request header for specifying the client profile in order to apply\r\n * customized config params on the server side, e.g. timeouts.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Definition of the ChannelRequest class. The request\r\n * object encapsulates the logic for making a single request, either for the\r\n * forward channel, back channel, or test channel, to the server. It contains\r\n * the logic for the two types of transports we use:\r\n * XMLHTTP and Image request. It provides timeout detection. More transports\r\n * to be added in future, such as Fetch, WebSocket.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\r\n\r\ngoog.require('goog.Timer');\r\ngoog.require('goog.async.Throttle');\r\ngoog.require('goog.events.EventHandler');\r\ngoog.require('goog.labs.net.webChannel.Channel');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\ngoog.require('goog.labs.net.webChannel.environment');\r\ngoog.require('goog.labs.net.webChannel.requestStats');\r\ngoog.require('goog.net.ErrorCode');\r\ngoog.require('goog.net.EventType');\r\ngoog.require('goog.net.WebChannel');\r\ngoog.require('goog.net.XmlHttp');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.userAgent');\r\n\r\ngoog.forwardDeclare('goog.Uri');\r\ngoog.forwardDeclare('goog.net.XhrIo');\r\n\r\n\r\n\r\n/**\r\n * A new ChannelRequest is created for each request to the server.\r\n *\r\n * @param {goog.labs.net.webChannel.Channel} channel\r\n * The channel that owns this request.\r\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\r\n * WebChannelDebug to use for logging.\r\n * @param {string=} opt_sessionId The session id for the channel.\r\n * @param {string|number=} opt_requestId The request id for this request.\r\n * @param {number=} opt_retryId The retry id for this request.\r\n * @constructor\r\n * @struct\r\n * @final\r\n */\r\ngoog.labs.net.webChannel.ChannelRequest = function(\r\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\r\n /**\r\n * The channel object that owns the request.\r\n * @private {goog.labs.net.webChannel.Channel}\r\n */\r\n this.channel_ = channel;\r\n\r\n /**\r\n * The channel debug to use for logging\r\n * @private {goog.labs.net.webChannel.WebChannelDebug}\r\n */\r\n this.channelDebug_ = channelDebug;\r\n\r\n /**\r\n * The Session ID for the channel.\r\n * @private {string|undefined}\r\n */\r\n this.sid_ = opt_sessionId;\r\n\r\n /**\r\n * The RID (request ID) for the request.\r\n * @private {string|number|undefined}\r\n */\r\n this.rid_ = opt_requestId;\r\n\r\n /**\r\n * The attempt number of the current request.\r\n * @private {number}\r\n */\r\n this.retryId_ = opt_retryId || 1;\r\n\r\n /**\r\n * An object to keep track of the channel request event listeners.\r\n * @private {!goog.events.EventHandler<\r\n * !goog.labs.net.webChannel.ChannelRequest>}\r\n */\r\n this.eventHandler_ = new goog.events.EventHandler(this);\r\n\r\n /**\r\n * The timeout in ms before failing the request.\r\n * @private {number}\r\n */\r\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\r\n\r\n /**\r\n * A timer for polling responseText in browsers that don't fire\r\n * onreadystatechange during incremental loading of responseText.\r\n * @private {goog.Timer}\r\n */\r\n this.pollingTimer_ =\r\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\r\n\r\n /**\r\n * Extra HTTP headers to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraHeaders_ = null;\r\n\r\n\r\n /**\r\n * Whether the request was successful. This is only set to true after the\r\n * request successfully completes.\r\n * @private {boolean}\r\n */\r\n this.successful_ = false;\r\n\r\n\r\n /**\r\n * The TimerID of the timer used to detect if the request has timed-out.\r\n * @type {?number}\r\n * @private\r\n */\r\n this.watchDogTimerId_ = null;\r\n\r\n /**\r\n * The time in the future when the request will timeout.\r\n * @private {?number}\r\n */\r\n this.watchDogTimeoutTime_ = null;\r\n\r\n /**\r\n * The time the request started.\r\n * @private {?number}\r\n */\r\n this.requestStartTime_ = null;\r\n\r\n /**\r\n * The type of request (XMLHTTP, IMG)\r\n * @private {?number}\r\n */\r\n this.type_ = null;\r\n\r\n /**\r\n * The base Uri for the request. The includes all the parameters except the\r\n * one that indicates the retry number.\r\n * @private {goog.Uri}\r\n */\r\n this.baseUri_ = null;\r\n\r\n /**\r\n * The request Uri that was actually used for the most recent request attempt.\r\n * @private {goog.Uri}\r\n */\r\n this.requestUri_ = null;\r\n\r\n /**\r\n * The post data, if the request is a post.\r\n * @private {?string}\r\n */\r\n this.postData_ = null;\r\n\r\n /**\r\n * An array of pending messages that we have either received a non-successful\r\n * response for, or no response at all, and which therefore may or may not\r\n * have been received by the server.\r\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\r\n */\r\n this.pendingMessages_ = [];\r\n\r\n /**\r\n * The XhrLte request if the request is using XMLHTTP\r\n * @private {goog.net.XhrIo}\r\n */\r\n this.xmlHttp_ = null;\r\n\r\n /**\r\n * The position of where the next unprocessed chunk starts in the response\r\n * text.\r\n * @private {number}\r\n */\r\n this.xmlHttpChunkStart_ = 0;\r\n\r\n /**\r\n * The verb (Get or Post) for the request.\r\n * @private {?string}\r\n */\r\n this.verb_ = null;\r\n\r\n /**\r\n * The last error if the request failed.\r\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\r\n */\r\n this.lastError_ = null;\r\n\r\n /**\r\n * The last status code received.\r\n * @private {number}\r\n */\r\n this.lastStatusCode_ = -1;\r\n\r\n /**\r\n * Whether the request has been cancelled due to a call to cancel.\r\n * @private {boolean}\r\n */\r\n this.cancelled_ = false;\r\n\r\n /**\r\n * A throttle time in ms for readystatechange events for the backchannel.\r\n * Useful for throttling when ready state is INTERACTIVE (partial data).\r\n * If set to zero no throttle is used.\r\n *\r\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\r\n *\r\n * @private {number}\r\n */\r\n this.readyStateChangeThrottleMs_ = 0;\r\n\r\n /**\r\n * The throttle for readystatechange events for the current request, or null\r\n * if there is none.\r\n * @private {goog.async.Throttle}\r\n */\r\n this.readyStateChangeThrottle_ = null;\r\n\r\n /**\r\n * Whether to the result is expected to be encoded for chunking and thus\r\n * requires decoding.\r\n * @private {boolean}\r\n */\r\n this.decodeChunks_ = false;\r\n\r\n /**\r\n * Whether to decode x-http-initial-response.\r\n * @private {boolean}\r\n */\r\n this.decodeInitialResponse_ = false;\r\n\r\n /**\r\n * Whether x-http-initial-response has been decoded (dispatched).\r\n * @private {boolean}\r\n */\r\n this.initialResponseDecoded_ = false;\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannel = goog.net.WebChannel;\r\nvar Channel = goog.labs.net.webChannel.Channel;\r\nvar ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\nvar environment = goog.labs.net.webChannel.environment;\r\n\r\n\r\n/**\r\n * Default timeout in MS for a request. The server must return data within this\r\n * time limit for the request to not timeout.\r\n * @private {number}\r\n */\r\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\r\n\r\n\r\n/**\r\n * Enum for channel requests type\r\n * @enum {number}\r\n * @private\r\n */\r\nChannelRequest.Type_ = {\r\n /**\r\n * XMLHTTP requests.\r\n */\r\n XML_HTTP: 1,\r\n\r\n /**\r\n * IMG requests.\r\n */\r\n CLOSE_REQUEST: 2\r\n};\r\n\r\n\r\n/**\r\n * Enum type for identifying an error.\r\n * @enum {number}\r\n */\r\nChannelRequest.Error = {\r\n /**\r\n * Errors due to a non-200 status code.\r\n */\r\n STATUS: 0,\r\n\r\n /**\r\n * Errors due to no data being returned.\r\n */\r\n NO_DATA: 1,\r\n\r\n /**\r\n * Errors due to a timeout.\r\n */\r\n TIMEOUT: 2,\r\n\r\n /**\r\n * Errors due to the server returning an unknown.\r\n */\r\n UNKNOWN_SESSION_ID: 3,\r\n\r\n /**\r\n * Errors due to bad data being received.\r\n */\r\n BAD_DATA: 4,\r\n\r\n /**\r\n * Errors due to the handler throwing an exception.\r\n */\r\n HANDLER_EXCEPTION: 5,\r\n\r\n /**\r\n * The browser declared itself offline during the request.\r\n */\r\n BROWSER_OFFLINE: 6\r\n};\r\n\r\n\r\n/**\r\n * Returns a useful error string for debugging based on the specified error\r\n * code.\r\n * @param {?ChannelRequest.Error} errorCode The error code.\r\n * @param {number} statusCode The HTTP status code.\r\n * @return {string} The error string for the given code combination.\r\n */\r\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\r\n switch (errorCode) {\r\n case ChannelRequest.Error.STATUS:\r\n return 'Non-200 return code (' + statusCode + ')';\r\n case ChannelRequest.Error.NO_DATA:\r\n return 'XMLHTTP failure (no data)';\r\n case ChannelRequest.Error.TIMEOUT:\r\n return 'HttpConnection timeout';\r\n default:\r\n return 'Unknown error';\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\r\n * @private {Object}\r\n */\r\nChannelRequest.INVALID_CHUNK_ = {};\r\n\r\n\r\n/**\r\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\r\n * response.\r\n * @private {Object}\r\n */\r\nChannelRequest.INCOMPLETE_CHUNK_ = {};\r\n\r\n\r\n/**\r\n * Returns whether XHR streaming is supported on this browser.\r\n *\r\n * @return {boolean} Whether XHR streaming is supported.\r\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\r\n */\r\nChannelRequest.supportsXhrStreaming = function() {\r\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\r\n};\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @param {Object} extraHeaders The HTTP headers.\r\n */\r\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\r\n this.extraHeaders_ = extraHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Overrides the default HTTP method.\r\n *\r\n * @param {string} verb The HTTP method\r\n */\r\nChannelRequest.prototype.setVerb = function(verb) {\r\n this.verb_ = verb;\r\n};\r\n\r\n\r\n/**\r\n * Sets the timeout for a request\r\n *\r\n * @param {number} timeout The timeout in MS for when we fail the request.\r\n */\r\nChannelRequest.prototype.setTimeout = function(timeout) {\r\n this.timeout_ = timeout;\r\n};\r\n\r\n\r\n/**\r\n * Sets the throttle for handling onreadystatechange events for the request.\r\n *\r\n * @param {number} throttle The throttle in ms. A value of zero indicates\r\n * no throttle.\r\n */\r\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\r\n this.readyStateChangeThrottleMs_ = throttle;\r\n};\r\n\r\n\r\n/**\r\n * Sets the pending messages that this request is handling.\r\n *\r\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\r\n * The pending messages for this request.\r\n */\r\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\r\n this.pendingMessages_ = pendingMessages;\r\n};\r\n\r\n\r\n/**\r\n * Gets the pending messages that this request is handling, in case of a retry.\r\n *\r\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\r\n * messages for this request.\r\n */\r\nChannelRequest.prototype.getPendingMessages = function() {\r\n return this.pendingMessages_;\r\n};\r\n\r\n\r\n/**\r\n * Uses XMLHTTP to send an HTTP POST to the server.\r\n *\r\n * @param {goog.Uri} uri The uri of the request.\r\n * @param {?string} postData The data for the post body.\r\n * @param {boolean} decodeChunks Whether to the result is expected to be\r\n * encoded for chunking and thus requires decoding.\r\n */\r\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\r\n this.type_ = ChannelRequest.Type_.XML_HTTP;\r\n this.baseUri_ = uri.clone().makeUnique();\r\n this.postData_ = postData;\r\n this.decodeChunks_ = decodeChunks;\r\n this.sendXmlHttp_(null /* hostPrefix */);\r\n};\r\n\r\n\r\n/**\r\n * Uses XMLHTTP to send an HTTP GET to the server.\r\n *\r\n * @param {goog.Uri} uri The uri of the request.\r\n * @param {boolean} decodeChunks Whether to the result is expected to be\r\n * encoded for chunking and thus requires decoding.\r\n * @param {?string} hostPrefix The host prefix, if we might be using a\r\n * secondary domain. Note that it should also be in the URL, adding this\r\n * won't cause it to be added to the URL.\r\n */\r\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\r\n this.type_ = ChannelRequest.Type_.XML_HTTP;\r\n this.baseUri_ = uri.clone().makeUnique();\r\n this.postData_ = null;\r\n this.decodeChunks_ = decodeChunks;\r\n\r\n this.sendXmlHttp_(hostPrefix);\r\n};\r\n\r\n\r\n/**\r\n * Sends a request via XMLHTTP according to the current state of the request\r\n * object.\r\n *\r\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\r\n * domain.\r\n * @private\r\n */\r\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\r\n this.requestStartTime_ = goog.now();\r\n this.ensureWatchDogTimer_();\r\n\r\n // clone the base URI to create the request URI. The request uri has the\r\n // attempt number as a parameter which helps in debugging.\r\n this.requestUri_ = this.baseUri_.clone();\r\n this.requestUri_.setParameterValues('t', this.retryId_);\r\n\r\n // send the request either as a POST or GET\r\n this.xmlHttpChunkStart_ = 0;\r\n var useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\r\n this.xmlHttp_ =\r\n this.channel_.createXhrIo(useSecondaryDomains ? hostPrefix : null);\r\n\r\n if (this.readyStateChangeThrottleMs_ > 0) {\r\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\r\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\r\n this.readyStateChangeThrottleMs_);\r\n }\r\n\r\n this.eventHandler_.listen(\r\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\r\n this.readyStateChangeHandler_);\r\n\r\n var headers = this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\r\n if (this.postData_) {\r\n if (!this.verb_) {\r\n this.verb_ = 'POST';\r\n }\r\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\r\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\r\n } else {\r\n this.verb_ = 'GET';\r\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\r\n }\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_MADE);\r\n this.channelDebug_.xmlHttpChannelRequest(\r\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\r\n};\r\n\r\n\r\n/**\r\n * Handles a readystatechange event.\r\n * @param {goog.events.Event} evt The event.\r\n * @private\r\n */\r\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\r\n var xhr = /** @type {goog.net.XhrIo} */ (evt.target);\r\n var throttle = this.readyStateChangeThrottle_;\r\n if (throttle &&\r\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\r\n // Only throttle in the partial data case.\r\n this.channelDebug_.debug('Throttling readystatechange.');\r\n throttle.fire();\r\n } else {\r\n // If we haven't throttled, just handle response directly.\r\n this.xmlHttpHandler_(xhr);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * XmlHttp handler\r\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\r\n * @private\r\n */\r\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\r\n requestStats.onStartExecution();\r\n\r\n\r\n try {\r\n if (xmlhttp == this.xmlHttp_) {\r\n this.onXmlHttpReadyStateChanged_();\r\n } else {\r\n this.channelDebug_.warning(\r\n 'Called back with an ' +\r\n 'unexpected xmlhttp');\r\n }\r\n } catch (ex) {\r\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\r\n if (this.xmlHttp_ && this.xmlHttp_.getResponseText()) {\r\n var channelRequest = this;\r\n this.channelDebug_.dumpException(ex, function() {\r\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\r\n });\r\n } else {\r\n this.channelDebug_.dumpException(ex, 'No response text');\r\n }\r\n } finally {\r\n requestStats.onEndExecution();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called by the readystate handler for XMLHTTP requests.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\r\n var readyState = this.xmlHttp_.getReadyState();\r\n var errorCode = this.xmlHttp_.getLastErrorCode();\r\n var statusCode = this.xmlHttp_.getStatus();\r\n\r\n // we get partial results in browsers that support ready state interactive.\r\n // We also make sure that getResponseText is not null in interactive mode\r\n // before we continue.\r\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\r\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\r\n !environment.isPollingRequired() && // otherwise, go on to startPolling\r\n !this.xmlHttp_.getResponseText())) {\r\n return; // not yet ready\r\n }\r\n\r\n // Dispatch any appropriate network events.\r\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\r\n errorCode != goog.net.ErrorCode.ABORT) {\r\n // Pretty conservative, these are the only known scenarios which we'd\r\n // consider indicative of a truly non-functional network connection.\r\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_FAILED);\r\n } else {\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\r\n }\r\n }\r\n\r\n // got some data so cancel the watchdog timer\r\n this.cancelWatchDogTimer_();\r\n\r\n var status = this.xmlHttp_.getStatus();\r\n this.lastStatusCode_ = status;\r\n var responseText = this.xmlHttp_.getResponseText();\r\n if (!responseText) {\r\n var channelRequest = this;\r\n this.channelDebug_.debug(function() {\r\n return 'No response text for uri ' + channelRequest.requestUri_ +\r\n ' status ' + status;\r\n });\r\n }\r\n this.successful_ = (status == 200);\r\n\r\n this.channelDebug_.xmlHttpChannelResponseMetaData(\r\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\r\n this.retryId_, readyState, status);\r\n\r\n if (!this.successful_) {\r\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\r\n // the server error string will include 'Unknown SID' which indicates the\r\n // server doesn't know about the session (maybe it got restarted, maybe\r\n // the user got moved to another server, etc.,). Handlers can special\r\n // case this error\r\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\r\n requestStats.notifyStatEvent(\r\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\r\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\r\n } else {\r\n this.lastError_ = ChannelRequest.Error.STATUS;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\r\n this.channelDebug_.warning(\r\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\r\n }\r\n this.cleanup_();\r\n this.dispatchFailure_();\r\n return;\r\n }\r\n\r\n if (this.shouldCheckInitialResponse_()) {\r\n var initialResponse = this.getInitialResponse_();\r\n if (initialResponse) {\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, initialResponse,\r\n 'Initial handshake response via ' +\r\n WebChannel.X_HTTP_INITIAL_RESPONSE);\r\n this.initialResponseDecoded_ = true;\r\n this.safeOnRequestData_(initialResponse);\r\n } else {\r\n this.successful_ = false;\r\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\r\n requestStats.notifyStatEvent(\r\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\r\n this.channelDebug_.warning(\r\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\r\n ' (' + this.rid_ + ')');\r\n this.cleanup_();\r\n this.dispatchFailure_();\r\n return;\r\n }\r\n }\r\n\r\n if (this.decodeChunks_) {\r\n this.decodeNextChunks_(readyState, responseText);\r\n if (environment.isPollingRequired() && this.successful_ &&\r\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\r\n this.startPolling_();\r\n }\r\n } else {\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, responseText, null);\r\n this.safeOnRequestData_(responseText);\r\n }\r\n\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n this.cleanup_();\r\n }\r\n\r\n if (!this.successful_) {\r\n return;\r\n }\r\n\r\n if (!this.cancelled_) {\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n this.channel_.onRequestComplete(this);\r\n } else {\r\n // The default is false, the result from this callback shouldn't carry\r\n // over to the next callback, otherwise the request looks successful if\r\n // the watchdog timer gets called\r\n this.successful_ = false;\r\n this.ensureWatchDogTimer_();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Whether we need check the initial-response header that is sent during the\r\n * fast handshake.\r\n *\r\n * @return {boolean} true if the initial-response header is yet to be processed.\r\n * @private\r\n */\r\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\r\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\r\n};\r\n\r\n\r\n/**\r\n * Queries the initial response header that is sent during the handshake.\r\n *\r\n * @return {?string} The non-empty header value or null.\r\n * @private\r\n */\r\nChannelRequest.prototype.getInitialResponse_ = function() {\r\n if (this.xmlHttp_) {\r\n var value = this.xmlHttp_.getStreamingResponseHeader(\r\n WebChannel.X_HTTP_INITIAL_RESPONSE);\r\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\r\n return value;\r\n }\r\n }\r\n\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Check if the initial response header has been handled.\r\n *\r\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\r\n */\r\nChannelRequest.prototype.isInitialResponseDecoded = function() {\r\n return this.initialResponseDecoded_;\r\n};\r\n\r\n\r\n/**\r\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\r\n */\r\nChannelRequest.prototype.setDecodeInitialResponse = function() {\r\n this.decodeInitialResponse_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Decodes the next set of available chunks in the response.\r\n * @param {number} readyState The value of readyState.\r\n * @param {string} responseText The value of responseText.\r\n * @private\r\n */\r\nChannelRequest.prototype.decodeNextChunks_ = function(\r\n readyState, responseText) {\r\n var decodeNextChunksSuccessful = true;\r\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\r\n var chunkText = this.getNextChunk_(responseText);\r\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n // should have consumed entire response when the request is done\r\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\r\n decodeNextChunksSuccessful = false;\r\n }\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, null, '[Incomplete Response]');\r\n break;\r\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\r\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, responseText, '[Invalid Chunk]');\r\n decodeNextChunksSuccessful = false;\r\n break;\r\n } else {\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, /** @type {string} */ (chunkText), null);\r\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\r\n }\r\n }\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\r\n responseText.length == 0) {\r\n // also an error if we didn't get any response\r\n this.lastError_ = ChannelRequest.Error.NO_DATA;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\r\n decodeNextChunksSuccessful = false;\r\n }\r\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\r\n if (!decodeNextChunksSuccessful) {\r\n // malformed response - we make this trigger retry logic\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, responseText, '[Invalid Chunked Response]');\r\n this.cleanup_();\r\n this.dispatchFailure_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Polls the response for new data.\r\n * @private\r\n */\r\nChannelRequest.prototype.pollResponse_ = function() {\r\n if (!this.xmlHttp_) {\r\n return; // already closed\r\n }\r\n var readyState = this.xmlHttp_.getReadyState();\r\n var responseText = this.xmlHttp_.getResponseText();\r\n if (this.xmlHttpChunkStart_ < responseText.length) {\r\n this.cancelWatchDogTimer_();\r\n this.decodeNextChunks_(readyState, responseText);\r\n if (this.successful_ &&\r\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n this.ensureWatchDogTimer_();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Starts a polling interval for changes to responseText of the\r\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\r\n * as data comes in incrementally. This timer is disabled in\r\n * cleanup_().\r\n * @private\r\n */\r\nChannelRequest.prototype.startPolling_ = function() {\r\n this.eventHandler_.listen(\r\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\r\n this.pollingTimer_.start();\r\n};\r\n\r\n\r\n/**\r\n * Returns the next chunk of a chunk-encoded response. This is not standard\r\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\r\n * the application through XMLHTTP. So we have an additional chunk encoding at\r\n * the application level that lets us tell where the beginning and end of\r\n * individual responses are so that we can only try to eval a complete JS array.\r\n *\r\n * The encoding is the size of the chunk encoded as a decimal string followed\r\n * by a newline followed by the data.\r\n *\r\n * @param {string} responseText The response text from the XMLHTTP response.\r\n * @return {string|Object} The next chunk string or a sentinel object\r\n * indicating a special condition.\r\n * @private\r\n */\r\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\r\n var sizeStartIndex = this.xmlHttpChunkStart_;\r\n var sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\r\n if (sizeEndIndex == -1) {\r\n return ChannelRequest.INCOMPLETE_CHUNK_;\r\n }\r\n\r\n var sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\r\n var size = Number(sizeAsString);\r\n if (isNaN(size)) {\r\n return ChannelRequest.INVALID_CHUNK_;\r\n }\r\n\r\n var chunkStartIndex = sizeEndIndex + 1;\r\n if (chunkStartIndex + size > responseText.length) {\r\n return ChannelRequest.INCOMPLETE_CHUNK_;\r\n }\r\n\r\n var chunkText = responseText.substr(chunkStartIndex, size);\r\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\r\n return chunkText;\r\n};\r\n\r\n\r\n/**\r\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\r\n *\r\n * This is only currently used to terminate the connection, as an IMG tag is\r\n * the most reliable way to send something to the server while the page\r\n * is getting torn down.\r\n *\r\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\r\n * solution to ensure delivery without blocking window close. See\r\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\r\n *\r\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\r\n * Policy (CSP) violation of using an IMG tag.\r\n *\r\n * For react-native, we use xhr to send the actual close request, and assume\r\n * there is no page-close issue with react-native.\r\n *\r\n * @param {goog.Uri} uri The uri to send a request to.\r\n */\r\nChannelRequest.prototype.sendCloseRequest = function(uri) {\r\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\r\n this.baseUri_ = uri.clone().makeUnique();\r\n\r\n var requestSent = false;\r\n\r\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\r\n // empty string body to avoid 413 error on chrome < 41\r\n requestSent =\r\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\r\n }\r\n\r\n if (!requestSent && goog.global.Image) {\r\n var eltImg = new Image();\r\n eltImg.src = this.baseUri_;\r\n requestSent = true;\r\n }\r\n\r\n if (!requestSent) {\r\n // no handler is set to match the sendBeacon/Image behavior\r\n this.xmlHttp_ = this.channel_.createXhrIo(null);\r\n this.xmlHttp_.send(this.baseUri_);\r\n }\r\n\r\n this.requestStartTime_ = goog.now();\r\n this.ensureWatchDogTimer_();\r\n};\r\n\r\n\r\n/**\r\n * Cancels the request no matter what the underlying transport is.\r\n */\r\nChannelRequest.prototype.cancel = function() {\r\n this.cancelled_ = true;\r\n this.cleanup_();\r\n};\r\n\r\n\r\n/**\r\n * Resets the timeout.\r\n *\r\n * @param {number=} opt_timeout The new timeout\r\n */\r\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\r\n if (opt_timeout) {\r\n this.setTimeout(opt_timeout);\r\n }\r\n // restart only if a timer is currently set\r\n if (this.watchDogTimerId_) {\r\n this.cancelWatchDogTimer_();\r\n this.ensureWatchDogTimer_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Ensures that there is watchdog timeout which is used to ensure that\r\n * the connection completes in time.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\r\n this.watchDogTimeoutTime_ = goog.now() + this.timeout_;\r\n this.startWatchDogTimer_(this.timeout_);\r\n};\r\n\r\n\r\n/**\r\n * Starts the watchdog timer which is used to ensure that the connection\r\n * completes in time.\r\n * @param {number} time The number of milliseconds to wait.\r\n * @private\r\n */\r\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\r\n if (this.watchDogTimerId_ != null) {\r\n // assertion\r\n throw new Error('WatchDog timer not null');\r\n }\r\n this.watchDogTimerId_ =\r\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\r\n};\r\n\r\n\r\n/**\r\n * Cancels the watchdog timer if it has been started.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\r\n if (this.watchDogTimerId_) {\r\n goog.global.clearTimeout(this.watchDogTimerId_);\r\n this.watchDogTimerId_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when the watchdog timer is triggered. It also handles a case where it\r\n * is called too early which we suspect may be happening sometimes\r\n * (not sure why)\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\r\n this.watchDogTimerId_ = null;\r\n var now = goog.now();\r\n if (now - this.watchDogTimeoutTime_ >= 0) {\r\n this.handleTimeout_();\r\n } else {\r\n // got called too early for some reason\r\n this.channelDebug_.warning('WatchDog timer called too early');\r\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when the request has actually timed out. Will cleanup and notify the\r\n * channel of the failure.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.handleTimeout_ = function() {\r\n if (this.successful_) {\r\n // Should never happen.\r\n this.channelDebug_.severe(\r\n 'Received watchdog timeout even though request loaded successfully');\r\n }\r\n\r\n this.channelDebug_.timeoutResponse(this.requestUri_);\r\n\r\n // IMG or SendBeacon requests never notice if they were successful,\r\n // and always 'time out'. This fact says nothing about reachability.\r\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_FAILED);\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\r\n }\r\n\r\n this.cleanup_();\r\n\r\n // Set error and dispatch failure.\r\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\r\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\r\n this.dispatchFailure_();\r\n};\r\n\r\n\r\n/**\r\n * Notifies the channel that this request failed.\r\n * @private\r\n */\r\nChannelRequest.prototype.dispatchFailure_ = function() {\r\n if (this.channel_.isClosed() || this.cancelled_) {\r\n return;\r\n }\r\n\r\n this.channel_.onRequestComplete(this);\r\n};\r\n\r\n\r\n/**\r\n * Cleans up the objects used to make the request. This function is\r\n * idempotent.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.cleanup_ = function() {\r\n this.cancelWatchDogTimer_();\r\n\r\n goog.dispose(this.readyStateChangeThrottle_);\r\n this.readyStateChangeThrottle_ = null;\r\n\r\n // Stop the polling timer, if necessary.\r\n this.pollingTimer_.stop();\r\n\r\n // Unhook all event handlers.\r\n this.eventHandler_.removeAll();\r\n\r\n if (this.xmlHttp_) {\r\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\r\n // inside abort\r\n var xmlhttp = this.xmlHttp_;\r\n this.xmlHttp_ = null;\r\n xmlhttp.abort();\r\n xmlhttp.dispose();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Indicates whether the request was successful. Only valid after the handler\r\n * is called to indicate completion of the request.\r\n *\r\n * @return {boolean} True if the request succeeded.\r\n */\r\nChannelRequest.prototype.getSuccess = function() {\r\n return this.successful_;\r\n};\r\n\r\n\r\n/**\r\n * If the request was not successful, returns the reason.\r\n *\r\n * @return {?ChannelRequest.Error} The last error.\r\n */\r\nChannelRequest.prototype.getLastError = function() {\r\n return this.lastError_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the status code of the last request.\r\n * @return {number} The status code of the last request.\r\n */\r\nChannelRequest.prototype.getLastStatusCode = function() {\r\n return this.lastStatusCode_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the session id for this channel.\r\n *\r\n * @return {string|undefined} The session ID.\r\n */\r\nChannelRequest.prototype.getSessionId = function() {\r\n return this.sid_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the request id for this request. Each request has a unique request\r\n * id and the request IDs are a sequential increasing count.\r\n *\r\n * @return {string|number|undefined} The request ID.\r\n */\r\nChannelRequest.prototype.getRequestId = function() {\r\n return this.rid_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the data for a post, if this request is a post.\r\n *\r\n * @return {?string} The POST data provided by the request initiator.\r\n */\r\nChannelRequest.prototype.getPostData = function() {\r\n return this.postData_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the XhrIo request object.\r\n *\r\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\r\n */\r\nChannelRequest.prototype.getXhr = function() {\r\n return this.xmlHttp_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the time that the request started, if it has started.\r\n *\r\n * @return {?number} The time the request started, as returned by goog.now().\r\n */\r\nChannelRequest.prototype.getRequestStartTime = function() {\r\n return this.requestStartTime_;\r\n};\r\n\r\n\r\n/**\r\n * Helper to call the callback's onRequestData, which catches any\r\n * exception.\r\n * @param {string} data The request data.\r\n * @private\r\n */\r\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\r\n try {\r\n this.channel_.onRequestData(this, data);\r\n var stats = requestStats.ServerReachability;\r\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\r\n } catch (e) {\r\n // Dump debug info, but keep going without closing the channel.\r\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Convenience factory method.\r\n *\r\n * @param {Channel} channel The channel object that owns this request.\r\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\r\n * @param {string=} opt_sessionId The session id for the channel.\r\n * @param {string|number=} opt_requestId The request id for this request.\r\n * @param {number=} opt_retryId The retry id for this request.\r\n * @return {!ChannelRequest} The created channel request.\r\n */\r\nChannelRequest.createChannelRequest = function(\r\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\r\n return new ChannelRequest(\r\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\r\n};\r\n}); // goog.scope\r\n","// Copyright 2018 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A single module to define user-agent specific environment\r\n * details.\r\n */\r\n\r\ngoog.module('goog.labs.net.webChannel.environment');\r\n\r\ngoog.module.declareLegacyNamespace();\r\n\r\nvar userAgent = goog.require('goog.userAgent');\r\n\r\n\r\n/**\r\n * The default polling interval in millis for Edge.\r\n *\r\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\r\n * chunk arrives within 50ms following the previous chunk. This may be fixed\r\n * in future, which requires changes to the whatwg spec too.\r\n *\r\n * @private @const {number}\r\n */\r\nvar EDGE_POLLING_INTERVAL_ = 125;\r\n\r\n\r\n/**\r\n * History:\r\n *\r\n * IE11 is still using Trident, the traditional engine for IE.\r\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\r\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\r\n *\r\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\r\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\r\n * and then to Blink (chrome).\r\n *\r\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\r\n * that may still be affected. For old Opera, double the polling interval\r\n * to 250ms.\r\n *\r\n * @return {boolean} True if polling is required with XHR.\r\n */\r\nexports.isPollingRequired = function() {\r\n return userAgent.EDGE_OR_IE;\r\n};\r\n\r\n\r\n/**\r\n * How often to poll (in MS) for changes to responseText in browsers that don't\r\n * fire onreadystatechange during incremental loading of the response body.\r\n *\r\n * @return {number|undefined} The polling interval (MS) for the current U-A;\r\n * or undefined if polling is not supposed to be enabled.\r\n */\r\nexports.getPollingInterval = function() {\r\n if (userAgent.EDGE_OR_IE) {\r\n return EDGE_POLLING_INTERVAL_;\r\n }\r\n\r\n return undefined;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Base WebChannel implementation.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\r\n\r\ngoog.require('goog.Uri');\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.async.run');\r\ngoog.require('goog.debug.TextFormatter');\r\ngoog.require('goog.json');\r\ngoog.require('goog.labs.net.webChannel.BaseTestChannel');\r\ngoog.require('goog.labs.net.webChannel.Channel');\r\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\r\ngoog.require('goog.labs.net.webChannel.ConnectionState');\r\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\ngoog.require('goog.labs.net.webChannel.Wire');\r\ngoog.require('goog.labs.net.webChannel.WireV8');\r\ngoog.require('goog.labs.net.webChannel.netUtils');\r\ngoog.require('goog.labs.net.webChannel.requestStats');\r\ngoog.require('goog.log');\r\ngoog.require('goog.net.WebChannel');\r\ngoog.require('goog.net.XhrIo');\r\ngoog.require('goog.net.XmlHttpFactory');\r\ngoog.require('goog.net.rpc.HttpCors');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.CircularBuffer');\r\n\r\ngoog.scope(function() {\r\nvar WebChannel = goog.net.WebChannel;\r\nvar BaseTestChannel = goog.labs.net.webChannel.BaseTestChannel;\r\nvar ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\r\nvar ConnectionState = goog.labs.net.webChannel.ConnectionState;\r\nvar ForwardChannelRequestPool =\r\n goog.labs.net.webChannel.ForwardChannelRequestPool;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\nvar WireV8 = goog.labs.net.webChannel.WireV8;\r\nvar netUtils = goog.labs.net.webChannel.netUtils;\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\n\r\nvar httpCors = goog.module.get('goog.net.rpc.HttpCors');\r\n\r\n\r\n/**\r\n * This WebChannel implementation is branched off goog.net.BrowserChannel\r\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\r\n * ported to this implementation as needed.\r\n *\r\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\r\n * WebChannel instance.\r\n * @param {number=} opt_clientVersion An application-specific version number\r\n * that is sent to the server when connected.\r\n * @param {!ConnectionState=} opt_conn Previously determined connection\r\n * conditions.\r\n * @constructor\r\n * @struct\r\n * @implements {goog.labs.net.webChannel.Channel}\r\n */\r\ngoog.labs.net.webChannel.WebChannelBase = function(\r\n opt_options, opt_clientVersion, opt_conn) {\r\n /**\r\n * The client library version (capabilities).\r\n * @private {number}\r\n */\r\n this.clientVersion_ = opt_clientVersion || 0;\r\n\r\n /**\r\n * The server library version (capabilities).\r\n * @private {number}\r\n */\r\n this.serverVersion_ = 0;\r\n\r\n\r\n /**\r\n * An array of queued maps that need to be sent to the server.\r\n * @private {!Array<Wire.QueuedMap>}\r\n */\r\n this.outgoingMaps_ = [];\r\n\r\n /**\r\n * The channel debug used for logging\r\n * @private {!WebChannelDebug}\r\n */\r\n this.channelDebug_ = new WebChannelDebug();\r\n\r\n /**\r\n * Previous connectivity test results.\r\n * @private {!ConnectionState}\r\n */\r\n this.connState_ = opt_conn || new ConnectionState();\r\n\r\n /**\r\n * Extra HTTP headers to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraHeaders_ = null;\r\n\r\n /**\r\n * Extra HTTP headers to add to the init request(s) sent to the server.\r\n * @private {Object}\r\n */\r\n this.initHeaders_ = null;\r\n\r\n /**\r\n * @private {?string} The URL param name to overwrite custom HTTP headers\r\n * to bypass CORS preflight.\r\n */\r\n this.httpHeadersOverwriteParam_ = null;\r\n\r\n /**\r\n * Extra parameters to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraParams_ = null;\r\n\r\n /**\r\n * Parameter name for the http session id.\r\n * @private {?string}\r\n */\r\n this.httpSessionIdParam_ = null;\r\n\r\n /**\r\n * The http session id, to be sent with httpSessionIdParam_ with each\r\n * request after the initial handshake.\r\n * @private {?string}\r\n */\r\n this.httpSessionId_ = null;\r\n\r\n /**\r\n * The ChannelRequest object for the backchannel.\r\n * @private {ChannelRequest}\r\n */\r\n this.backChannelRequest_ = null;\r\n\r\n /**\r\n * The relative path (in the context of the the page hosting the browser\r\n * channel) for making requests to the server.\r\n * @private {?string}\r\n */\r\n this.path_ = null;\r\n\r\n /**\r\n * The absolute URI for the forwardchannel request.\r\n * @private {goog.Uri}\r\n */\r\n this.forwardChannelUri_ = null;\r\n\r\n /**\r\n * The absolute URI for the backchannel request.\r\n * @private {goog.Uri}\r\n */\r\n this.backChannelUri_ = null;\r\n\r\n /**\r\n * A subdomain prefix for using a subdomain in IE for the backchannel\r\n * requests.\r\n * @private {?string}\r\n */\r\n this.hostPrefix_ = null;\r\n\r\n /**\r\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\r\n * @private {boolean}\r\n */\r\n this.allowHostPrefix_ = true;\r\n\r\n /**\r\n * The next id to use for the RID (request identifier) parameter. This\r\n * identifier uniquely identifies the forward channel request.\r\n * @private {number}\r\n */\r\n this.nextRid_ = 0;\r\n\r\n /**\r\n * The id to use for the next outgoing map. This identifier uniquely\r\n * identifies a sent map.\r\n * @private {number}\r\n */\r\n this.nextMapId_ = 0;\r\n\r\n /**\r\n * Whether to fail forward-channel requests after one try or a few tries.\r\n * @private {boolean}\r\n */\r\n this.failFast_ =\r\n !!goog.getObjectByName('internalChannelParams.failFast', opt_options);\r\n\r\n /**\r\n * The handler that receive callbacks for state changes and data.\r\n * @private {goog.labs.net.webChannel.WebChannelBase.Handler}\r\n */\r\n this.handler_ = null;\r\n\r\n /**\r\n * Timer identifier for asynchronously making a forward channel request.\r\n * This is set to true if the func is scheduled with async.run, which\r\n * is equivalent to setTimeout(0).\r\n * @private {?number|?boolean}\r\n */\r\n this.forwardChannelTimerId_ = null;\r\n\r\n /**\r\n * Timer identifier for asynchronously making a back channel request.\r\n * @private {?number}\r\n */\r\n this.backChannelTimerId_ = null;\r\n\r\n /**\r\n * Timer identifier for the timer that waits for us to retry the backchannel\r\n * in the case where it is dead and no longer receiving data.\r\n * @private {?number}\r\n */\r\n this.deadBackChannelTimerId_ = null;\r\n\r\n /**\r\n * The TestChannel object which encapsulates the logic for determining\r\n * interesting network conditions about the client.\r\n * @private {BaseTestChannel}\r\n */\r\n this.connectionTest_ = null;\r\n\r\n /**\r\n * Whether the client's network conditions can support chunked responses.\r\n * @private {?boolean}\r\n */\r\n this.useChunked_ = null;\r\n\r\n /**\r\n * Whether chunked mode is allowed. In certain debugging situations, it's\r\n * useful to disable this.\r\n * @private {boolean}\r\n */\r\n this.allowChunkedMode_ = true;\r\n\r\n /**\r\n * The array identifier of the last array received from the server for the\r\n * backchannel request.\r\n * @private {number}\r\n */\r\n this.lastArrayId_ = -1;\r\n\r\n /**\r\n * The array id of the last array sent by the server that we know about.\r\n * @private {number}\r\n */\r\n this.lastPostResponseArrayId_ = -1;\r\n\r\n /**\r\n * The last status code received.\r\n * @private {number}\r\n */\r\n this.lastStatusCode_ = -1;\r\n\r\n /**\r\n * Number of times we have retried the current forward channel request.\r\n * @private {number}\r\n */\r\n this.forwardChannelRetryCount_ = 0;\r\n\r\n /**\r\n * Number of times in a row that we have retried the current back channel\r\n * request and received no data.\r\n * @private {number}\r\n */\r\n this.backChannelRetryCount_ = 0;\r\n\r\n /**\r\n * The attempt id for the current back channel request. Starts at 1 and\r\n * increments for each reconnect. The server uses this to log if our\r\n * connection is flaky or not.\r\n * @private {number}\r\n */\r\n this.backChannelAttemptId_ = 0;\r\n\r\n /**\r\n * The base part of the time before firing next retry request. Default is 5\r\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\r\n * for all retries, and linear backoff is applied to the sum for subsequent\r\n * retries.\r\n * @private {number}\r\n */\r\n this.baseRetryDelayMs_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.baseRetryDelayMs', opt_options) ||\r\n 5 * 1000;\r\n\r\n /**\r\n * A random time between 0 and this number of MS is added to the\r\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\r\n * @private {number}\r\n */\r\n this.retryDelaySeedMs_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.retryDelaySeedMs', opt_options) ||\r\n 10 * 1000;\r\n\r\n /**\r\n * Maximum number of attempts to connect to the server for forward channel\r\n * requests. Defaults to 2.\r\n * @private {number}\r\n */\r\n this.forwardChannelMaxRetries_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.forwardChannelMaxRetries', opt_options) ||\r\n 2;\r\n\r\n /**\r\n * The timeout in milliseconds for a forward channel request. Defaults to 20\r\n * seconds. Note that part of this timeout can be randomized.\r\n * @private {number}\r\n */\r\n this.forwardChannelRequestTimeoutMs_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.forwardChannelRequestTimeoutMs',\r\n opt_options) ||\r\n 20 * 1000;\r\n\r\n /**\r\n * The custom factory used to create XMLHttpRequest objects.\r\n * @private {!goog.net.XmlHttpFactory | undefined}\r\n */\r\n this.xmlHttpFactory_ =\r\n (opt_options && opt_options.xmlHttpFactory) || undefined;\r\n\r\n /**\r\n * The timeout in milliseconds for a back channel request. Defaults to using\r\n * the timeout configured in ChannelRequest (45s). If server-side\r\n * keepaliveInterval is known to the client, set the backchannel request\r\n * timeout to 1.5 * keepaliveInterval (ms).\r\n *\r\n * @private {number|undefined}\r\n */\r\n this.backChannelRequestTimeoutMs_ = undefined;\r\n\r\n /**\r\n * A throttle time in ms for readystatechange events for the backchannel.\r\n * Useful for throttling when ready state is INTERACTIVE (partial data).\r\n *\r\n * This throttle is useful if the server sends large data chunks down the\r\n * backchannel. It prevents examining XHR partial data on every readystate\r\n * change event. This is useful because large chunks can trigger hundreds\r\n * of readystatechange events, each of which takes ~5ms or so to handle,\r\n * in turn making the UI unresponsive for a significant period.\r\n *\r\n * If set to zero no throttle is used.\r\n * @private {number}\r\n */\r\n this.readyStateChangeThrottleMs_ = 0;\r\n\r\n /**\r\n * Whether cross origin requests are supported for the channel.\r\n *\r\n * See {@link goog.net.XhrIo#setWithCredentials}.\r\n * @private {boolean}\r\n */\r\n this.supportsCrossDomainXhrs_ =\r\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\r\n\r\n /**\r\n * The current session id.\r\n * @private {string}\r\n */\r\n this.sid_ = '';\r\n\r\n /**\r\n * The current ChannelRequest pool for the forward channel.\r\n * @private {!ForwardChannelRequestPool}\r\n */\r\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\r\n opt_options && opt_options.concurrentRequestLimit);\r\n\r\n /**\r\n * The V8 codec.\r\n * @private {!WireV8}\r\n */\r\n this.wireCodec_ = new WireV8();\r\n\r\n /**\r\n * Whether to run the channel test as a background process to not block\r\n * the OPEN event.\r\n *\r\n * @private {boolean}\r\n */\r\n this.backgroundChannelTest_ =\r\n opt_options && goog.isDef(opt_options.backgroundChannelTest) ?\r\n opt_options.backgroundChannelTest :\r\n true;\r\n\r\n /**\r\n * Whether to turn on the fast handshake behavior.\r\n *\r\n * @private {boolean}\r\n */\r\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\r\n\r\n if (this.fastHandshake_ && !this.backgroundChannelTest_) {\r\n this.channelDebug_.warning(\r\n 'Force backgroundChannelTest when fastHandshake is enabled.');\r\n this.backgroundChannelTest_ = true;\r\n }\r\n\r\n if (opt_options && opt_options.disableRedact) {\r\n this.channelDebug_.disableRedact();\r\n }\r\n\r\n if (opt_options && opt_options.forceLongPolling) {\r\n this.allowChunkedMode_ = false;\r\n }\r\n\r\n /**\r\n * Callback when all the pending client-sent messages have been flushed.\r\n *\r\n * @private {function()|undefined}\r\n */\r\n this.forwardChannelFlushedCallback_ = undefined;\r\n};\r\n\r\nvar WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\r\n\r\n\r\n/**\r\n * The channel version that we negotiated with the server for this session.\r\n * Starts out as the version we request, and then is changed to the negotiated\r\n * version after the initial open.\r\n * @private {number}\r\n */\r\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\r\n\r\n\r\n/**\r\n * Enum type for the channel state machine.\r\n * @enum {number}\r\n */\r\nWebChannelBase.State = {\r\n /** The channel is closed. */\r\n CLOSED: 0,\r\n\r\n /** The channel has been initialized but hasn't yet initiated a connection. */\r\n INIT: 1,\r\n\r\n /** The channel is in the process of opening a connection to the server. */\r\n OPENING: 2,\r\n\r\n /** The channel is open. */\r\n OPENED: 3\r\n};\r\n\r\n\r\n/**\r\n * The current state of the WebChannel.\r\n * @private {!WebChannelBase.State}\r\n */\r\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\r\n\r\n\r\n/**\r\n * The timeout in milliseconds for a forward channel request.\r\n * @type {number}\r\n */\r\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\r\n\r\n\r\n/**\r\n * Maximum number of attempts to connect to the server for back channel\r\n * requests.\r\n * @type {number}\r\n */\r\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\r\n\r\n\r\n/**\r\n * A number in MS of how long we guess the maxmium amount of time a round trip\r\n * to the server should take. In the future this could be substituted with a\r\n * real measurement of the RTT.\r\n * @type {number}\r\n */\r\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\r\n\r\n\r\n/**\r\n * When retrying for an inactive channel, we will multiply the total delay by\r\n * this number.\r\n * @type {number}\r\n */\r\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\r\n\r\n\r\n/**\r\n * Enum type for identifying an error.\r\n * @enum {number}\r\n */\r\nWebChannelBase.Error = {\r\n /** Value that indicates no error has occurred. */\r\n OK: 0,\r\n\r\n /** An error due to a request failing. */\r\n REQUEST_FAILED: 2,\r\n\r\n /** An error due to the user being logged out. */\r\n LOGGED_OUT: 4,\r\n\r\n /** An error due to server response which contains no data. */\r\n NO_DATA: 5,\r\n\r\n /** An error due to a server response indicating an unknown session id */\r\n UNKNOWN_SESSION_ID: 6,\r\n\r\n /** An error due to a server response requesting to stop the channel. */\r\n STOP: 7,\r\n\r\n /** A general network error. */\r\n NETWORK: 8,\r\n\r\n /** An error due to bad data being returned from the server. */\r\n BAD_DATA: 10,\r\n\r\n /** An error due to a response that is not parsable. */\r\n BAD_RESPONSE: 11\r\n};\r\n\r\n\r\n/**\r\n * Internal enum type for the two channel types.\r\n * @enum {number}\r\n * @private\r\n */\r\nWebChannelBase.ChannelType_ = {\r\n FORWARD_CHANNEL: 1,\r\n\r\n BACK_CHANNEL: 2\r\n};\r\n\r\n\r\n/**\r\n * The maximum number of maps that can be sent in one POST. Should match\r\n * MAX_MAPS_PER_REQUEST on the server code.\r\n * @type {number}\r\n * @private\r\n */\r\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\r\n\r\n\r\n/**\r\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\r\n * handshake.\r\n *\r\n * @const @private {number}\r\n */\r\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\r\n\r\n\r\n/**\r\n * A guess at a cutoff at which to no longer assume the backchannel is dead\r\n * when we are slow to receive data. Number in bytes.\r\n *\r\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\r\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\r\n * @type {number}\r\n */\r\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\r\n\r\n\r\n/**\r\n * @return {number} The server version or 0 if undefined\r\n */\r\nWebChannelBase.prototype.getServerVersion = function() {\r\n return this.serverVersion_;\r\n};\r\n\r\n\r\n/**\r\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\r\n */\r\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\r\n return this.forwardChannelRequestPool_;\r\n};\r\n\r\n\r\n/**\r\n * @return {!Object} The codec object, to be used for the test channel.\r\n */\r\nWebChannelBase.prototype.getWireCodec = function() {\r\n return this.wireCodec_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the logger.\r\n *\r\n * @return {!WebChannelDebug} The channel debug object.\r\n */\r\nWebChannelBase.prototype.getChannelDebug = function() {\r\n return this.channelDebug_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the logger.\r\n *\r\n * @param {!WebChannelDebug} channelDebug The channel debug object.\r\n */\r\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\r\n this.channelDebug_ = channelDebug;\r\n};\r\n\r\n\r\n/**\r\n * Starts the channel. This initiates connections to the server.\r\n *\r\n * @param {string} testPath The path for the test connection.\r\n * @param {string} channelPath The path for the channel connection.\r\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\r\n * the requests.\r\n * @param {string=} opt_oldSessionId Session ID from a previous session.\r\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\r\n */\r\nWebChannelBase.prototype.connect = function(\r\n testPath, channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\r\n this.channelDebug_.debug('connect()');\r\n\r\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\r\n\r\n this.path_ = channelPath;\r\n this.extraParams_ = opt_extraParams || {};\r\n\r\n // Attach parameters about the previous session if reconnecting.\r\n if (opt_oldSessionId && goog.isDef(opt_oldArrayId)) {\r\n this.extraParams_['OSID'] = opt_oldSessionId;\r\n this.extraParams_['OAID'] = opt_oldArrayId;\r\n }\r\n\r\n if (this.backgroundChannelTest_) {\r\n this.channelDebug_.debug('connect() bypassed channel-test.');\r\n this.connState_.handshakeResult = [];\r\n this.connState_.bufferingProxyResult = false;\r\n\r\n // TODO(user): merge states with background channel test\r\n // requestStats.setTimeout(goog.bind(this.connectTest_, this, testPath), 0);\r\n // this.connectChannel_();\r\n }\r\n\r\n this.connectTest_(testPath);\r\n};\r\n\r\n\r\n/**\r\n * Disconnects and closes the channel.\r\n */\r\nWebChannelBase.prototype.disconnect = function() {\r\n this.channelDebug_.debug('disconnect()');\r\n\r\n this.cancelRequests_();\r\n\r\n if (this.state_ == WebChannelBase.State.OPENED) {\r\n var rid = this.nextRid_++;\r\n var uri = this.forwardChannelUri_.clone();\r\n uri.setParameterValue('SID', this.sid_);\r\n uri.setParameterValue('RID', rid);\r\n uri.setParameterValue('TYPE', 'terminate');\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n var request = ChannelRequest.createChannelRequest(\r\n this, this.channelDebug_, this.sid_, rid);\r\n request.sendCloseRequest(uri);\r\n }\r\n\r\n this.onClose_();\r\n};\r\n\r\n\r\n/**\r\n * Returns the session id of the channel. Only available after the\r\n * channel has been opened.\r\n * @return {string} Session ID.\r\n */\r\nWebChannelBase.prototype.getSessionId = function() {\r\n return this.sid_;\r\n};\r\n\r\n\r\n/**\r\n * Starts the test channel to determine network conditions.\r\n *\r\n * @param {string} testPath The relative PATH for the test connection.\r\n * @private\r\n */\r\nWebChannelBase.prototype.connectTest_ = function(testPath) {\r\n this.channelDebug_.debug('connectTest_()');\r\n if (!this.okToMakeRequest_()) {\r\n return; // channel is cancelled\r\n }\r\n this.connectionTest_ = new BaseTestChannel(this, this.channelDebug_);\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n this.connectionTest_.setExtraHeaders(this.extraHeaders_);\r\n }\r\n\r\n var urlPath = testPath;\r\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\r\n urlPath = httpCors.setHttpHeadersWithOverwriteParam(\r\n testPath, this.httpHeadersOverwriteParam_, this.extraHeaders_);\r\n }\r\n\r\n this.connectionTest_.connect(/** @type {string} */ (urlPath));\r\n};\r\n\r\n\r\n/**\r\n * Starts the regular channel which is run after the test channel is complete.\r\n * @private\r\n */\r\nWebChannelBase.prototype.connectChannel_ = function() {\r\n this.channelDebug_.debug('connectChannel_()');\r\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\r\n this.forwardChannelUri_ =\r\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\r\n this.ensureForwardChannel_();\r\n};\r\n\r\n\r\n/**\r\n * Cancels all outstanding requests.\r\n * @private\r\n */\r\nWebChannelBase.prototype.cancelRequests_ = function() {\r\n if (this.connectionTest_) {\r\n this.connectionTest_.abort();\r\n this.connectionTest_ = null;\r\n }\r\n\r\n if (this.backChannelRequest_) {\r\n this.backChannelRequest_.cancel();\r\n this.backChannelRequest_ = null;\r\n }\r\n\r\n if (this.backChannelTimerId_) {\r\n goog.global.clearTimeout(this.backChannelTimerId_);\r\n this.backChannelTimerId_ = null;\r\n }\r\n\r\n this.clearDeadBackchannelTimer_();\r\n\r\n this.forwardChannelRequestPool_.cancel();\r\n\r\n if (this.forwardChannelTimerId_) {\r\n this.clearForwardChannelTimer_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears the forward channel timer.\r\n * @private\r\n */\r\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\r\n if (goog.isNumber(this.forwardChannelTimerId_)) {\r\n goog.global.clearTimeout(this.forwardChannelTimerId_);\r\n }\r\n\r\n this.forwardChannelTimerId_ = null;\r\n};\r\n\r\n\r\n/**\r\n * Returns the extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @return {Object} The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.getExtraHeaders = function() {\r\n return this.extraHeaders_;\r\n};\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @param {Object} extraHeaders The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\r\n this.extraHeaders_ = extraHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Returns the extra HTTP headers to add to the init requests\r\n * sent to the server.\r\n *\r\n * @return {Object} The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.getInitHeaders = function() {\r\n return this.initHeaders_;\r\n};\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to the init requests sent to the server.\r\n *\r\n * @param {Object} initHeaders The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\r\n this.initHeaders_ = initHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Sets the URL param name to overwrite custom HTTP headers.\r\n *\r\n * @param {string} httpHeadersOverwriteParam The URL param name.\r\n */\r\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\r\n httpHeadersOverwriteParam) {\r\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\r\n this.httpSessionIdParam_ = httpSessionIdParam;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\r\n return this.httpSessionIdParam_;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\r\n this.httpSessionId_ = httpSessionId;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getHttpSessionId = function() {\r\n return this.httpSessionId_;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getBackgroundChannelTest = function() {\r\n return this.backgroundChannelTest_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the throttle for handling onreadystatechange events for the request.\r\n *\r\n * @param {number} throttle The throttle in ms. A value of zero indicates\r\n * no throttle.\r\n */\r\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\r\n this.readyStateChangeThrottleMs_ = throttle;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether cross origin requests are supported for the channel.\r\n *\r\n * Setting this allows the creation of requests to secondary domains and\r\n * sends XHRs with the CORS withCredentials bit set to true.\r\n *\r\n * In order for cross-origin requests to work, the server will also need to set\r\n * CORS response headers as per:\r\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\r\n *\r\n * See {@link goog.net.XhrIo#setWithCredentials}.\r\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\r\n */\r\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\r\n supportCrossDomain) {\r\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\r\n};\r\n\r\n\r\n/**\r\n * Returns the handler used for channel callback events.\r\n *\r\n * @return {WebChannelBase.Handler} The handler.\r\n */\r\nWebChannelBase.prototype.getHandler = function() {\r\n return this.handler_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the handler used for channel callback events.\r\n * @param {WebChannelBase.Handler} handler The handler to set.\r\n */\r\nWebChannelBase.prototype.setHandler = function(handler) {\r\n this.handler_ = handler;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the channel allows the use of a subdomain. There may be\r\n * cases where this isn't allowed.\r\n * @return {boolean} Whether a host prefix is allowed.\r\n */\r\nWebChannelBase.prototype.getAllowHostPrefix = function() {\r\n return this.allowHostPrefix_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether the channel allows the use of a subdomain. There may be cases\r\n * where this isn't allowed, for example, logging in with troutboard where\r\n * using a subdomain causes Apache to force the user to authenticate twice.\r\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\r\n */\r\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\r\n this.allowHostPrefix_ = allowHostPrefix;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the channel is buffered or not. This state is valid for\r\n * querying only after the test connection has completed. This may be\r\n * queried in the WebChannelBase.okToMakeRequest() callback.\r\n * A channel may be buffered if the test connection determines that\r\n * a chunked response could not be sent down within a suitable time.\r\n * @return {boolean} Whether the channel is buffered.\r\n */\r\nWebChannelBase.prototype.isBuffered = function() {\r\n return !this.useChunked_;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether chunked mode is allowed. In certain debugging situations,\r\n * it's useful for the application to have a way to disable chunked mode for a\r\n * user.\r\n\r\n * @return {boolean} Whether chunked mode is allowed.\r\n */\r\nWebChannelBase.prototype.getAllowChunkedMode = function() {\r\n return this.allowChunkedMode_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether chunked mode is allowed. In certain debugging situations, it's\r\n * useful for the application to have a way to disable chunked mode for a user.\r\n * @param {boolean} allowChunkedMode Whether chunked mode is allowed.\r\n */\r\nWebChannelBase.prototype.setAllowChunkedMode = function(allowChunkedMode) {\r\n this.allowChunkedMode_ = allowChunkedMode;\r\n};\r\n\r\n\r\n/**\r\n * Sends a request to the server. The format of the request is a Map data\r\n * structure of key/value pairs. These maps are then encoded in a format\r\n * suitable for the wire and then reconstituted as a Map data structure that\r\n * the server can process.\r\n * @param {!Object|!goog.structs.Map} map The map to send.\r\n * @param {!Object=} opt_context The context associated with the map.\r\n */\r\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\r\n goog.asserts.assert(\r\n this.state_ != WebChannelBase.State.CLOSED,\r\n 'Invalid operation: sending map when state is closed');\r\n\r\n // We can only send 1000 maps per POST, but typically we should never have\r\n // that much to send, so warn if we exceed that (we still send all the maps).\r\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\r\n // severe() is temporary so that we get these uploaded and can figure out\r\n // what's causing them. Afterwards can change to warning().\r\n this.channelDebug_.severe(function() {\r\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\r\n ' queued maps upon queueing ' + goog.json.serialize(map);\r\n });\r\n }\r\n\r\n this.outgoingMaps_.push(\r\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\r\n\r\n // Messages need be buffered during OPENING to avoid server-side race\r\n if (this.state_ == WebChannelBase.State.OPENED) {\r\n this.ensureForwardChannel_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * When set to true, this changes the behavior of the forward channel so it\r\n * will not retry requests; it will fail after one network failure, and if\r\n * there was already one network failure, the request will fail immediately.\r\n * @param {boolean} failFast Whether or not to fail fast.\r\n */\r\nWebChannelBase.prototype.setFailFast = function(failFast) {\r\n this.failFast_ = failFast;\r\n this.channelDebug_.info('setFailFast: ' + failFast);\r\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\r\n this.forwardChannelTimerId_) &&\r\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\r\n var self = this;\r\n this.channelDebug_.info(function() {\r\n return 'Retry count ' + self.forwardChannelRetryCount_ +\r\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\r\n '. Fail immediately!';\r\n });\r\n\r\n if (!this.forwardChannelRequestPool_.forceComplete(\r\n goog.bind(this.onRequestComplete, this))) {\r\n // i.e., this.forwardChannelTimerId_\r\n this.clearForwardChannelTimer_();\r\n // The error code from the last failed request is gone, so just use a\r\n // generic one.\r\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The max number of forward-channel retries, which will be 0\r\n * in fail-fast mode.\r\n */\r\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\r\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the maximum number of attempts to connect to the server for forward\r\n * channel requests.\r\n * @param {number} retries The maximum number of attempts.\r\n */\r\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\r\n this.forwardChannelMaxRetries_ = retries;\r\n};\r\n\r\n\r\n/**\r\n * Sets the timeout for a forward channel request.\r\n * @param {number} timeoutMs The timeout in milliseconds.\r\n */\r\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\r\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The max number of back-channel retries, which is a constant.\r\n */\r\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\r\n // Back-channel retries is a constant.\r\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.isClosed = function() {\r\n return this.state_ == WebChannelBase.State.CLOSED;\r\n};\r\n\r\n\r\n/**\r\n * Returns the channel state.\r\n * @return {WebChannelBase.State} The current state of the channel.\r\n */\r\nWebChannelBase.prototype.getState = function() {\r\n return this.state_;\r\n};\r\n\r\n\r\n/**\r\n * Return the last status code received for a request.\r\n * @return {number} The last status code received for a request.\r\n */\r\nWebChannelBase.prototype.getLastStatusCode = function() {\r\n return this.lastStatusCode_;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The last array id received.\r\n */\r\nWebChannelBase.prototype.getLastArrayId = function() {\r\n return this.lastArrayId_;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether there are outstanding requests servicing the channel.\r\n * @return {boolean} true if there are outstanding requests.\r\n */\r\nWebChannelBase.prototype.hasOutstandingRequests = function() {\r\n return this.getOutstandingRequests_() != 0;\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of outstanding requests.\r\n * @return {number} The number of outstanding requests to the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\r\n var count = 0;\r\n if (this.backChannelRequest_) {\r\n count++;\r\n }\r\n count += this.forwardChannelRequestPool_.getRequestCount();\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Ensures that a forward channel request is scheduled.\r\n * @private\r\n */\r\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\r\n if (this.forwardChannelRequestPool_.isFull()) {\r\n // enough connection in process - no need to start a new request\r\n return;\r\n }\r\n\r\n if (this.forwardChannelTimerId_) {\r\n // no need to start a new request - one is already scheduled\r\n return;\r\n }\r\n\r\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\r\n // from chrome/firefox background tabs\r\n this.forwardChannelTimerId_ = true;\r\n goog.async.run(this.onStartForwardChannelTimer_, this);\r\n\r\n this.forwardChannelRetryCount_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * Schedules a forward-channel retry for the specified request, unless the max\r\n * retries has been reached.\r\n * @param {!ChannelRequest} request The failed request to retry.\r\n * @return {boolean} true iff a retry was scheduled.\r\n * @private\r\n */\r\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\r\n if (this.forwardChannelRequestPool_.getRequestCount() >=\r\n this.forwardChannelRequestPool_.getMaxSize() -\r\n (this.forwardChannelTimerId_ ? 1 : 0)) {\r\n // Should be impossible to be called in this state.\r\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\r\n return false;\r\n }\r\n\r\n if (this.forwardChannelTimerId_) {\r\n this.channelDebug_.debug(\r\n 'Use the retry request that is already scheduled.');\r\n this.outgoingMaps_ =\r\n request.getPendingMessages().concat(this.outgoingMaps_);\r\n return true;\r\n }\r\n\r\n // No retry for open_() and fail-fast\r\n if (this.state_ == WebChannelBase.State.INIT ||\r\n this.state_ == WebChannelBase.State.OPENING ||\r\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\r\n return false;\r\n }\r\n\r\n this.channelDebug_.debug('Going to retry POST');\r\n\r\n this.forwardChannelTimerId_ = requestStats.setTimeout(\r\n goog.bind(this.onStartForwardChannelTimer_, this, request),\r\n this.getRetryTime_(this.forwardChannelRetryCount_));\r\n this.forwardChannelRetryCount_++;\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Timer callback for ensureForwardChannel\r\n * @param {ChannelRequest=} opt_retryRequest A failed request\r\n * to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\r\n opt_retryRequest) {\r\n // null is possible if scheduled with async.run\r\n if (this.forwardChannelTimerId_) {\r\n this.forwardChannelTimerId_ = null;\r\n this.startForwardChannel_(opt_retryRequest);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Begins a new forward channel operation to the server.\r\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\r\n this.channelDebug_.debug('startForwardChannel_');\r\n if (!this.okToMakeRequest_()) {\r\n return; // channel is cancelled\r\n } else if (this.state_ == WebChannelBase.State.INIT) {\r\n if (opt_retryRequest) {\r\n this.channelDebug_.severe('Not supposed to retry the open');\r\n return;\r\n }\r\n this.open_();\r\n this.state_ = WebChannelBase.State.OPENING;\r\n } else if (this.state_ == WebChannelBase.State.OPENED) {\r\n if (opt_retryRequest) {\r\n this.makeForwardChannelRequest_(opt_retryRequest);\r\n return;\r\n }\r\n\r\n if (this.outgoingMaps_.length == 0) {\r\n this.channelDebug_.debug(\r\n 'startForwardChannel_ returned: ' +\r\n 'nothing to send');\r\n // no need to start a new forward channel request\r\n return;\r\n }\r\n\r\n if (this.forwardChannelRequestPool_.isFull()) {\r\n // Should be impossible to be called in this state.\r\n this.channelDebug_.severe(\r\n 'startForwardChannel_ returned: ' +\r\n 'connection already in progress');\r\n return;\r\n }\r\n\r\n this.makeForwardChannelRequest_();\r\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Establishes a new channel session with the the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.open_ = function() {\r\n this.channelDebug_.debug('open_()');\r\n this.nextRid_ = Math.floor(Math.random() * 100000);\r\n\r\n var rid = this.nextRid_++;\r\n var request =\r\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\r\n\r\n // mix the init headers\r\n var extraHeaders = this.extraHeaders_;\r\n if (this.initHeaders_) {\r\n if (extraHeaders) {\r\n extraHeaders = goog.object.clone(extraHeaders);\r\n goog.object.extend(extraHeaders, this.initHeaders_);\r\n } else {\r\n extraHeaders = this.initHeaders_;\r\n }\r\n }\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n request.setExtraHeaders(extraHeaders);\r\n }\r\n\r\n var requestText = this.dequeueOutgoingMaps_(\r\n request,\r\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\r\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\r\n\r\n var uri = this.forwardChannelUri_.clone();\r\n uri.setParameterValue('RID', rid);\r\n\r\n if (this.clientVersion_ > 0) {\r\n uri.setParameterValue('CVER', this.clientVersion_);\r\n }\r\n\r\n // http-session-id to be generated as the response\r\n if (this.getBackgroundChannelTest() && this.getHttpSessionIdParam()) {\r\n uri.setParameterValue(\r\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\r\n }\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n if (this.httpHeadersOverwriteParam_ && extraHeaders) {\r\n httpCors.setHttpHeadersWithOverwriteParam(\r\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\r\n }\r\n\r\n this.forwardChannelRequestPool_.addRequest(request);\r\n\r\n // Check the option and use GET to enable QUIC 0-RTT\r\n if (this.fastHandshake_) {\r\n uri.setParameterValue('$req', requestText);\r\n\r\n // enable handshake upgrade\r\n uri.setParameterValue('SID', 'null');\r\n request.setDecodeInitialResponse();\r\n\r\n request.xmlHttpPost(uri, null, true); // Send as a GET\r\n } else {\r\n request.xmlHttpPost(uri, requestText, true);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of raw JSON messages to be encoded\r\n * with the fast-handshake (GET) request, including zero. If messages are not\r\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\r\n * @private\r\n */\r\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\r\n var total = 0;\r\n for (var i = 0; i < this.outgoingMaps_.length; i++) {\r\n var map = this.outgoingMaps_[i];\r\n var size = map.getRawDataSize();\r\n if (size === undefined) {\r\n break;\r\n }\r\n total += size;\r\n\r\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\r\n return i;\r\n }\r\n\r\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\r\n i === this.outgoingMaps_.length - 1) {\r\n return i + 1;\r\n }\r\n }\r\n\r\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Makes a forward channel request using XMLHTTP.\r\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\r\n opt_retryRequest) {\r\n var rid;\r\n if (opt_retryRequest) {\r\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\r\n } else {\r\n rid = this.nextRid_++;\r\n }\r\n\r\n var uri = this.forwardChannelUri_.clone();\r\n uri.setParameterValue('SID', this.sid_);\r\n uri.setParameterValue('RID', rid);\r\n uri.setParameterValue('AID', this.lastArrayId_);\r\n // Add the additional reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\r\n httpCors.setHttpHeadersWithOverwriteParam(\r\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\r\n }\r\n\r\n var request = ChannelRequest.createChannelRequest(\r\n this, this.channelDebug_, this.sid_, rid,\r\n this.forwardChannelRetryCount_ + 1);\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n request.setExtraHeaders(this.extraHeaders_);\r\n }\r\n\r\n var requestText;\r\n if (opt_retryRequest) {\r\n this.requeuePendingMaps_(opt_retryRequest);\r\n }\r\n requestText =\r\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\r\n\r\n // Randomize from 50%-100% of the forward channel timeout to avoid\r\n // a big hit if servers happen to die at once.\r\n request.setTimeout(\r\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\r\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\r\n this.forwardChannelRequestPool_.addRequest(request);\r\n request.xmlHttpPost(uri, requestText, true);\r\n};\r\n\r\n\r\n/**\r\n * Adds the additional parameters from the handler to the given URI.\r\n * @param {!goog.Uri} uri The URI to add the parameters to.\r\n * @private\r\n */\r\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\r\n // Add the additional reconnect parameters as needed.\r\n if (this.handler_) {\r\n var params = this.handler_.getAdditionalParams(this);\r\n if (params) {\r\n goog.structs.forEach(params, function(value, key, coll) {\r\n uri.setParameterValue(key, value);\r\n });\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns the request text from the outgoing maps and resets it.\r\n * @param {!ChannelRequest} request The new request for sending the messages.\r\n * @param {number} maxNum The maximum number of messages to be encoded\r\n * @return {string} The encoded request text created from all the currently\r\n * queued outgoing maps.\r\n * @private\r\n */\r\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\r\n var count = Math.min(this.outgoingMaps_.length, maxNum);\r\n\r\n var badMapHandler = this.handler_ ?\r\n goog.bind(this.handler_.badMapError, this.handler_, this) :\r\n null;\r\n var result = this.wireCodec_.encodeMessageQueue(\r\n this.outgoingMaps_, count, badMapHandler);\r\n\r\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Requeues unacknowledged sent arrays for retransmission in the next forward\r\n * channel request.\r\n * @param {!ChannelRequest} retryRequest A failed request to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\r\n this.outgoingMaps_ =\r\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\r\n};\r\n\r\n\r\n/**\r\n * Ensures there is a backchannel request for receiving data from the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.ensureBackChannel_ = function() {\r\n if (this.backChannelRequest_) {\r\n // already have one\r\n return;\r\n }\r\n\r\n if (this.backChannelTimerId_) {\r\n // no need to start a new request - one is already scheduled\r\n return;\r\n }\r\n\r\n this.backChannelAttemptId_ = 1;\r\n\r\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\r\n // from chrome/firefox background tabs\r\n // backChannelTimerId_ stays unset, as with setTimeout(0)\r\n goog.async.run(this.onStartBackChannelTimer_, this);\r\n\r\n this.backChannelRetryCount_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * Schedules a back-channel retry, unless the max retries has been reached.\r\n * @return {boolean} true iff a retry was scheduled.\r\n * @private\r\n */\r\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\r\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\r\n // Should be impossible to be called in this state.\r\n this.channelDebug_.severe('Request already in progress');\r\n return false;\r\n }\r\n\r\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\r\n return false;\r\n }\r\n\r\n this.channelDebug_.debug('Going to retry GET');\r\n\r\n this.backChannelAttemptId_++;\r\n this.backChannelTimerId_ = requestStats.setTimeout(\r\n goog.bind(this.onStartBackChannelTimer_, this),\r\n this.getRetryTime_(this.backChannelRetryCount_));\r\n this.backChannelRetryCount_++;\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Timer callback for ensureBackChannel_.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\r\n this.backChannelTimerId_ = null;\r\n this.startBackChannel_();\r\n};\r\n\r\n\r\n/**\r\n * Begins a new back channel operation to the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.startBackChannel_ = function() {\r\n if (!this.okToMakeRequest_()) {\r\n // channel is cancelled\r\n return;\r\n }\r\n\r\n this.channelDebug_.debug('Creating new HttpRequest');\r\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\r\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\r\n }\r\n\r\n this.backChannelRequest_.setReadyStateChangeThrottle(\r\n this.readyStateChangeThrottleMs_);\r\n var uri = this.backChannelUri_.clone();\r\n uri.setParameterValue('RID', 'rpc');\r\n uri.setParameterValue('SID', this.sid_);\r\n uri.setParameterValue('CI', this.useChunked_ ? '0' : '1');\r\n uri.setParameterValue('AID', this.lastArrayId_);\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n uri.setParameterValue('TYPE', 'xmlhttp');\r\n\r\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\r\n httpCors.setHttpHeadersWithOverwriteParam(\r\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\r\n }\r\n\r\n if (this.backChannelRequestTimeoutMs_) {\r\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\r\n }\r\n\r\n this.backChannelRequest_.xmlHttpGet(\r\n uri, true /* decodeChunks */, this.hostPrefix_);\r\n\r\n this.channelDebug_.debug('New Request created');\r\n};\r\n\r\n\r\n/**\r\n * Gives the handler a chance to return an error code and stop channel\r\n * execution. A handler might want to do this to check that the user is still\r\n * logged in, for example.\r\n * @private\r\n * @return {boolean} If it's OK to make a request.\r\n */\r\nWebChannelBase.prototype.okToMakeRequest_ = function() {\r\n if (this.handler_) {\r\n var result = this.handler_.okToMakeRequest(this);\r\n if (result != WebChannelBase.Error.OK) {\r\n this.channelDebug_.debug(\r\n 'Handler returned error code from okToMakeRequest');\r\n this.signalError_(result);\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.testConnectionFinished = function(\r\n testChannel, useChunked) {\r\n this.channelDebug_.debug('Test Connection Finished');\r\n\r\n // Forward channel will not be used prior to this method is called\r\n var clientProtocol = testChannel.getClientProtocol();\r\n if (clientProtocol) {\r\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\r\n }\r\n\r\n this.useChunked_ = this.allowChunkedMode_ && useChunked;\r\n this.lastStatusCode_ = testChannel.getLastStatusCode();\r\n\r\n this.connectChannel_();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.testConnectionFailure = function(\r\n testChannel, errorCode) {\r\n this.channelDebug_.debug('Test Connection Failed');\r\n this.lastStatusCode_ = testChannel.getLastStatusCode();\r\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\r\n if (this.state_ == WebChannelBase.State.CLOSED ||\r\n (this.backChannelRequest_ != request &&\r\n !this.forwardChannelRequestPool_.hasRequest(request))) {\r\n // either CLOSED or a request we don't know about (perhaps an old request)\r\n return;\r\n }\r\n this.lastStatusCode_ = request.getLastStatusCode();\r\n\r\n // first to check if request has been upgraded to backchannel\r\n if (!request.isInitialResponseDecoded() &&\r\n this.forwardChannelRequestPool_.hasRequest(request) &&\r\n this.state_ == WebChannelBase.State.OPENED) {\r\n var response;\r\n try {\r\n response = this.wireCodec_.decodeMessage(responseText);\r\n } catch (ex) {\r\n response = null;\r\n }\r\n if (goog.isArray(response) && response.length == 3) {\r\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\r\n this.onForwardChannelFlushed_();\r\n } else {\r\n this.channelDebug_.debug('Bad POST response data returned');\r\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\r\n }\r\n } else {\r\n if (request.isInitialResponseDecoded() ||\r\n this.backChannelRequest_ == request) {\r\n this.clearDeadBackchannelTimer_();\r\n }\r\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\r\n var response = this.wireCodec_.decodeMessage(responseText);\r\n this.onInput_(/** @type {!Array<?>} */ (response), request);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Checks if we need call the flush callback.\r\n *\r\n * @private\r\n */\r\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\r\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\r\n if (this.forwardChannelFlushedCallback_) {\r\n try {\r\n this.forwardChannelFlushedCallback_();\r\n } catch (ex) {\r\n this.channelDebug_.dumpException(\r\n ex, 'Exception from forwardChannelFlushedCallback_ ');\r\n }\r\n // reset\r\n this.forwardChannelFlushedCallback_ = undefined;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Handles a POST response from the server.\r\n * @param {Array<number>} responseValues The key value pairs in\r\n * the POST response.\r\n * @param {!ChannelRequest} forwardReq The forward channel request that\r\n * triggers this function call.\r\n * @private\r\n */\r\nWebChannelBase.prototype.handlePostResponse_ = function(\r\n responseValues, forwardReq) {\r\n // The first response value is set to 0 if server is missing backchannel.\r\n if (responseValues[0] == 0) {\r\n this.handleBackchannelMissing_(forwardReq);\r\n return;\r\n }\r\n this.lastPostResponseArrayId_ = responseValues[1];\r\n var outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\r\n if (0 < outstandingArrays) {\r\n var numOutstandingBackchannelBytes = responseValues[2];\r\n this.channelDebug_.debug(\r\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\r\n ' arrays) are outstanding on the BackChannel');\r\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\r\n return;\r\n }\r\n if (!this.deadBackChannelTimerId_) {\r\n // We expect to receive data within 2 RTTs or we retry the backchannel.\r\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\r\n goog.bind(this.onBackChannelDead_, this),\r\n 2 * WebChannelBase.RTT_ESTIMATE);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Handles a POST response from the server telling us that it has detected that\r\n * we have no hanging GET connection.\r\n * @param {!ChannelRequest} forwardReq The forward channel request that\r\n * triggers this function call.\r\n * @private\r\n */\r\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\r\n // As long as the back channel was started before the POST was sent,\r\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\r\n // so as not to excessively retry the backchannel\r\n this.channelDebug_.debug('Server claims our backchannel is missing.');\r\n if (this.backChannelTimerId_) {\r\n this.channelDebug_.debug('But we are currently starting the request.');\r\n return;\r\n } else if (!this.backChannelRequest_) {\r\n this.channelDebug_.warning('We do not have a BackChannel established');\r\n } else if (\r\n this.backChannelRequest_.getRequestStartTime() +\r\n WebChannelBase.RTT_ESTIMATE <\r\n forwardReq.getRequestStartTime()) {\r\n this.clearDeadBackchannelTimer_();\r\n this.backChannelRequest_.cancel();\r\n this.backChannelRequest_ = null;\r\n } else {\r\n return;\r\n }\r\n this.maybeRetryBackChannel_();\r\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\r\n};\r\n\r\n\r\n/**\r\n * Determines whether we should start the process of retrying a possibly\r\n * dead backchannel.\r\n * @param {number} outstandingBytes The number of bytes for which the server has\r\n * not yet received acknowledgement.\r\n * @return {boolean} Whether to start the backchannel retry timer.\r\n * @private\r\n */\r\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\r\n // Not too many outstanding bytes, not buffered and not after a retry.\r\n return outstandingBytes <\r\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\r\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\r\n};\r\n\r\n\r\n/**\r\n * Decides which host prefix should be used, if any. If there is a handler,\r\n * allows the handler to validate a host prefix provided by the server, and\r\n * optionally override it.\r\n * @param {?string} serverHostPrefix The host prefix provided by the server.\r\n * @return {?string} The host prefix to actually use, if any. Will return null\r\n * if the use of host prefixes was disabled via setAllowHostPrefix().\r\n * @override\r\n */\r\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\r\n if (this.allowHostPrefix_) {\r\n if (this.handler_) {\r\n return this.handler_.correctHostPrefix(serverHostPrefix);\r\n }\r\n return serverHostPrefix;\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Handles the timer that indicates that our backchannel is no longer able to\r\n * successfully receive data from the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onBackChannelDead_ = function() {\r\n if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) {\r\n this.deadBackChannelTimerId_ = null;\r\n this.backChannelRequest_.cancel();\r\n this.backChannelRequest_ = null;\r\n this.maybeRetryBackChannel_();\r\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears the timer that indicates that our backchannel is no longer able to\r\n * successfully receive data from the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\r\n if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) {\r\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\r\n this.deadBackChannelTimerId_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns whether or not the given error/status combination is fatal or not.\r\n * On fatal errors we immediately close the session rather than retrying the\r\n * failed request.\r\n * @param {?ChannelRequest.Error} error The error code for the\r\n * failed request.\r\n * @param {number} statusCode The last HTTP status code.\r\n * @return {boolean} Whether or not the error is fatal.\r\n * @private\r\n */\r\nWebChannelBase.isFatalError_ = function(error, statusCode) {\r\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\r\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.onRequestComplete = function(request) {\r\n this.channelDebug_.debug('Request complete');\r\n var type;\r\n var pendingMessages = null;\r\n if (this.backChannelRequest_ == request) {\r\n this.clearDeadBackchannelTimer_();\r\n this.backChannelRequest_ = null;\r\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\r\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\r\n pendingMessages = request.getPendingMessages();\r\n this.forwardChannelRequestPool_.removeRequest(request);\r\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\r\n } else {\r\n // return if it was an old request from a previous session\r\n return;\r\n }\r\n\r\n this.lastStatusCode_ = request.getLastStatusCode();\r\n\r\n if (this.state_ == WebChannelBase.State.CLOSED) {\r\n return;\r\n }\r\n\r\n if (request.getSuccess()) {\r\n // Yay!\r\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\r\n var size = request.getPostData() ? request.getPostData().length : 0;\r\n requestStats.notifyTimingEvent(\r\n size, goog.now() - request.getRequestStartTime(),\r\n this.forwardChannelRetryCount_);\r\n this.ensureForwardChannel_();\r\n this.onSuccess_(request);\r\n } else { // i.e., back-channel\r\n this.ensureBackChannel_();\r\n }\r\n return;\r\n }\r\n // Else unsuccessful. Fall through.\r\n\r\n var lastError = request.getLastError();\r\n if (!WebChannelBase.isFatalError_(lastError, this.lastStatusCode_)) {\r\n // Maybe retry.\r\n var self = this;\r\n this.channelDebug_.debug(function() {\r\n return 'Maybe retrying, last error: ' +\r\n ChannelRequest.errorStringFromCode(lastError, self.lastStatusCode_);\r\n });\r\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\r\n if (this.maybeRetryForwardChannel_(request)) {\r\n return;\r\n }\r\n }\r\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\r\n if (this.maybeRetryBackChannel_()) {\r\n return;\r\n }\r\n }\r\n // Else exceeded max retries. Fall through.\r\n this.channelDebug_.debug('Exceeded max number of retries');\r\n } else {\r\n // Else fatal error. Fall through and mark the pending maps as failed.\r\n this.channelDebug_.debug('Not retrying due to error type');\r\n }\r\n\r\n\r\n // Abort the channel now\r\n\r\n // Record pending messages from the failed request\r\n if (pendingMessages && pendingMessages.length > 0) {\r\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\r\n }\r\n\r\n this.channelDebug_.debug('Error: HTTP request failed');\r\n switch (lastError) {\r\n case ChannelRequest.Error.NO_DATA:\r\n this.signalError_(WebChannelBase.Error.NO_DATA);\r\n break;\r\n case ChannelRequest.Error.BAD_DATA:\r\n this.signalError_(WebChannelBase.Error.BAD_DATA);\r\n break;\r\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\r\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\r\n break;\r\n default:\r\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\r\n break;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {number} retryCount Number of retries so far.\r\n * @return {number} Time in ms before firing next retry request.\r\n * @private\r\n */\r\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\r\n var retryTime = this.baseRetryDelayMs_ +\r\n Math.floor(Math.random() * this.retryDelaySeedMs_);\r\n if (!this.isActive()) {\r\n this.channelDebug_.debug('Inactive channel');\r\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\r\n }\r\n // Backoff for subsequent retries\r\n retryTime *= retryCount;\r\n return retryTime;\r\n};\r\n\r\n\r\n/**\r\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\r\n * @param {number} delaySeedMs A random delay between 0 and this is added to\r\n * the base part.\r\n */\r\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\r\n this.baseRetryDelayMs_ = baseDelayMs;\r\n this.retryDelaySeedMs_ = delaySeedMs;\r\n};\r\n\r\n\r\n/**\r\n * Apply any handshake control headers.\r\n * @param {!ChannelRequest} request The underlying request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\r\n if (!this.backgroundChannelTest_) {\r\n return;\r\n }\r\n\r\n var xhr = request.getXhr();\r\n if (xhr) {\r\n var clientProtocol =\r\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\r\n if (clientProtocol) {\r\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\r\n }\r\n\r\n if (this.getHttpSessionIdParam()) {\r\n var httpSessionIdHeader =\r\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\r\n if (httpSessionIdHeader) {\r\n this.setHttpSessionId(httpSessionIdHeader);\r\n // update the cached uri\r\n var httpSessionIdParam = this.getHttpSessionIdParam();\r\n\r\n this.forwardChannelUri_.setParameterValue(\r\n /** @type {string} */ (httpSessionIdParam), // never null\r\n httpSessionIdHeader);\r\n } else {\r\n this.channelDebug_.warning(\r\n 'Missing X_HTTP_SESSION_ID in the handshake response');\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Processes the data returned by the server.\r\n * @param {!Array<!Array<?>>} respArray The response array returned\r\n * by the server.\r\n * @param {!ChannelRequest} request The underlying request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\r\n var batch =\r\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\r\n for (var i = 0; i < respArray.length; i++) {\r\n var nextArray = respArray[i];\r\n this.lastArrayId_ = nextArray[0];\r\n nextArray = nextArray[1];\r\n if (this.state_ == WebChannelBase.State.OPENING) {\r\n if (nextArray[0] == 'c') {\r\n this.sid_ = nextArray[1];\r\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\r\n\r\n var negotiatedVersion = nextArray[3];\r\n if (goog.isDefAndNotNull(negotiatedVersion)) {\r\n this.channelVersion_ = negotiatedVersion;\r\n this.channelDebug_.info('VER=' + this.channelVersion_);\r\n }\r\n\r\n var negotiatedServerVersion = nextArray[4];\r\n if (goog.isDefAndNotNull(negotiatedServerVersion)) {\r\n this.serverVersion_ = negotiatedServerVersion;\r\n this.channelDebug_.info('SVER=' + this.serverVersion_);\r\n }\r\n\r\n // CVER=22\r\n var serverKeepaliveMs = nextArray[5];\r\n if (goog.isDefAndNotNull(serverKeepaliveMs) &&\r\n goog.isNumber(serverKeepaliveMs) && serverKeepaliveMs > 0) {\r\n var timeout = 1.5 * serverKeepaliveMs;\r\n this.backChannelRequestTimeoutMs_ = timeout;\r\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\r\n }\r\n\r\n this.applyControlHeaders_(request);\r\n\r\n this.state_ = WebChannelBase.State.OPENED;\r\n if (this.handler_) {\r\n this.handler_.channelOpened(this);\r\n }\r\n\r\n this.startBackchannelAfterHandshake_(request);\r\n\r\n if (this.outgoingMaps_.length > 0) {\r\n this.ensureForwardChannel_();\r\n }\r\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\r\n // treat close also as an abort\r\n this.signalError_(WebChannelBase.Error.STOP);\r\n }\r\n } else if (this.state_ == WebChannelBase.State.OPENED) {\r\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\r\n if (batch && !goog.array.isEmpty(batch)) {\r\n this.handler_.channelHandleMultipleArrays(this, batch);\r\n batch.length = 0;\r\n }\r\n if (nextArray[0] == 'stop') {\r\n this.signalError_(WebChannelBase.Error.STOP);\r\n } else {\r\n this.disconnect();\r\n }\r\n } else if (nextArray[0] == 'noop') {\r\n // ignore - noop to keep connection happy\r\n } else {\r\n if (batch) {\r\n batch.push(nextArray);\r\n } else if (this.handler_) {\r\n this.handler_.channelHandleArray(this, nextArray);\r\n }\r\n }\r\n // We have received useful data on the back-channel, so clear its retry\r\n // count. We do this because back-channels by design do not complete\r\n // quickly, so on a flaky connection we could have many fail to complete\r\n // fully but still deliver a lot of data before they fail. We don't want\r\n // to count such failures towards the retry limit, because we don't want\r\n // to give up on a session if we can still receive data.\r\n this.backChannelRetryCount_ = 0;\r\n }\r\n }\r\n if (batch && !goog.array.isEmpty(batch)) {\r\n this.handler_.channelHandleMultipleArrays(this, batch);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Starts the backchannel after the handshake.\r\n *\r\n * @param {!ChannelRequest} request The underlying request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\r\n this.backChannelUri_ = this.getBackChannelUri(\r\n this.hostPrefix_, /** @type {string} */ (this.path_));\r\n\r\n if (request.isInitialResponseDecoded()) {\r\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\r\n this.forwardChannelRequestPool_.removeRequest(request);\r\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\r\n this.backChannelRequest_ = request;\r\n } else {\r\n // Open connection to receive data\r\n this.ensureBackChannel_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Helper to ensure the channel is in the expected state.\r\n * @param {...number} var_args The channel must be in one of the indicated\r\n * states.\r\n * @private\r\n */\r\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\r\n goog.asserts.assert(\r\n goog.array.contains(arguments, this.state_),\r\n 'Unexpected channel state: %s', this.state_);\r\n};\r\n\r\n\r\n/**\r\n * Signals an error has occurred.\r\n * @param {WebChannelBase.Error} error The error code for the failure.\r\n * @private\r\n */\r\nWebChannelBase.prototype.signalError_ = function(error) {\r\n this.channelDebug_.info('Error code ' + error);\r\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\r\n // Create a separate Internet connection to check\r\n // if it's a server error or user's network error.\r\n var imageUri = null;\r\n if (this.handler_) {\r\n imageUri = this.handler_.getNetworkTestImageUri(this);\r\n }\r\n netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);\r\n } else {\r\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\r\n }\r\n this.onError_(error);\r\n};\r\n\r\n\r\n/**\r\n * Callback for netUtils.testNetwork during error handling.\r\n * @param {boolean} networkUp Whether the network is up.\r\n * @private\r\n */\r\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\r\n if (networkUp) {\r\n this.channelDebug_.info('Successfully pinged google.com');\r\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\r\n } else {\r\n this.channelDebug_.info('Failed to ping google.com');\r\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\r\n // Do not call onError_ again to eliminate duplicated Error events.\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when messages have been successfully sent from the queue.\r\n * @param {!ChannelRequest} request The request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.onSuccess_ = function(request) {\r\n if (this.handler_) {\r\n this.handler_.channelSuccess(this, request);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when we've determined the final error for a channel. It closes the\r\n * notifiers the handler of the error and closes the channel.\r\n * @param {WebChannelBase.Error} error The error code for the failure.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onError_ = function(error) {\r\n this.channelDebug_.debug('HttpChannel: error - ' + error);\r\n this.state_ = WebChannelBase.State.CLOSED;\r\n if (this.handler_) {\r\n this.handler_.channelError(this, error);\r\n }\r\n this.onClose_();\r\n this.cancelRequests_();\r\n};\r\n\r\n\r\n/**\r\n * Called when the channel has been closed. It notifiers the handler of the\r\n * event, and reports any pending or undelivered maps.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onClose_ = function() {\r\n this.state_ = WebChannelBase.State.CLOSED;\r\n this.lastStatusCode_ = -1;\r\n if (this.handler_) {\r\n var pendingMessages = this.forwardChannelRequestPool_.getPendingMessages();\r\n\r\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\r\n this.handler_.channelClosed(this);\r\n } else {\r\n var self = this;\r\n this.channelDebug_.debug(function() {\r\n return 'Number of undelivered maps' +\r\n ', pending: ' + pendingMessages.length +\r\n ', outgoing: ' + self.outgoingMaps_.length;\r\n });\r\n\r\n this.forwardChannelRequestPool_.clearPendingMessages();\r\n\r\n var copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\r\n this.outgoingMaps_.length = 0;\r\n\r\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\r\n var uri = this.createDataUri(null, path);\r\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getConnectionState = function() {\r\n return this.connState_;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\r\n var uri = this.createDataUri(\r\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\r\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.createDataUri = function(\r\n hostPrefix, path, opt_overridePort) {\r\n var uri = goog.Uri.parse(path);\r\n var uriAbsolute = (uri.getDomain() != '');\r\n if (uriAbsolute) {\r\n if (hostPrefix) {\r\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\r\n }\r\n\r\n uri.setPort(opt_overridePort || uri.getPort());\r\n } else {\r\n var locationPage = goog.global.location;\r\n var hostName;\r\n if (hostPrefix) {\r\n hostName = hostPrefix + '.' + locationPage.hostname;\r\n } else {\r\n hostName = locationPage.hostname;\r\n }\r\n\r\n var port = opt_overridePort || +locationPage.port;\r\n\r\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\r\n }\r\n\r\n if (this.extraParams_) {\r\n goog.object.forEach(this.extraParams_, function(value, key) {\r\n uri.setParameterValue(key, value);\r\n });\r\n }\r\n\r\n var param = this.getHttpSessionIdParam();\r\n var value = this.getHttpSessionId();\r\n if (param && value) {\r\n uri.setParameterValue(param, value);\r\n }\r\n\r\n // Add the protocol version to the URI.\r\n uri.setParameterValue('VER', this.channelVersion_);\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.createXhrIo = function(hostPrefix) {\r\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\r\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\r\n }\r\n var xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\r\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\r\n return xhr;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.isActive = function() {\r\n return !!this.handler_ && this.handler_.isActive(this);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\r\n return this.supportsCrossDomainXhrs_;\r\n};\r\n\r\n\r\n/**\r\n * Sets (overwrites) the forward channel flush callback.\r\n *\r\n * @param {function()} callback The callback to be invoked.\r\n */\r\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\r\n this.forwardChannelFlushedCallback_ = callback;\r\n};\r\n\r\n\r\n/**\r\n * A LogSaver that can be used to accumulate all the debug logs so they\r\n * can be sent to the server when a problem is detected.\r\n * @const\r\n */\r\nWebChannelBase.LogSaver = {};\r\n\r\n\r\n/**\r\n * Buffer for accumulating the debug log\r\n * @type {goog.structs.CircularBuffer}\r\n * @private\r\n */\r\nWebChannelBase.LogSaver.buffer_ = new goog.structs.CircularBuffer(1000);\r\n\r\n\r\n/**\r\n * Whether we're currently accumulating the debug log.\r\n * @type {boolean}\r\n * @private\r\n */\r\nWebChannelBase.LogSaver.enabled_ = false;\r\n\r\n\r\n/**\r\n * Formatter for saving logs.\r\n * @type {goog.debug.Formatter}\r\n * @private\r\n */\r\nWebChannelBase.LogSaver.formatter_ = new goog.debug.TextFormatter();\r\n\r\n\r\n/**\r\n * Returns whether the LogSaver is enabled.\r\n * @return {boolean} Whether saving is enabled or disabled.\r\n */\r\nWebChannelBase.LogSaver.isEnabled = function() {\r\n return WebChannelBase.LogSaver.enabled_;\r\n};\r\n\r\n\r\n/**\r\n * Enables of disables the LogSaver.\r\n * @param {boolean} enable Whether to enable or disable saving.\r\n */\r\nWebChannelBase.LogSaver.setEnabled = function(enable) {\r\n if (enable == WebChannelBase.LogSaver.enabled_) {\r\n return;\r\n }\r\n\r\n var fn = WebChannelBase.LogSaver.addLogRecord;\r\n var logger = goog.log.getLogger('goog.net');\r\n if (enable) {\r\n goog.log.addHandler(logger, fn);\r\n } else {\r\n goog.log.removeHandler(logger, fn);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds a log record.\r\n * @param {goog.log.LogRecord} logRecord the LogRecord.\r\n */\r\nWebChannelBase.LogSaver.addLogRecord = function(logRecord) {\r\n WebChannelBase.LogSaver.buffer_.add(\r\n WebChannelBase.LogSaver.formatter_.formatRecord(logRecord));\r\n};\r\n\r\n\r\n/**\r\n * Returns the log as a single string.\r\n * @return {string} The log as a single string.\r\n */\r\nWebChannelBase.LogSaver.getBuffer = function() {\r\n return WebChannelBase.LogSaver.buffer_.getValues().join('');\r\n};\r\n\r\n\r\n/**\r\n * Clears the buffer\r\n */\r\nWebChannelBase.LogSaver.clearBuffer = function() {\r\n WebChannelBase.LogSaver.buffer_.clear();\r\n};\r\n\r\n\r\n\r\n/**\r\n * Abstract base class for the channel handler\r\n * @constructor\r\n * @struct\r\n */\r\nWebChannelBase.Handler = function() {};\r\n\r\n\r\n/**\r\n * Callback handler for when a batch of response arrays is received from the\r\n * server. When null, batched dispatching is disabled.\r\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\r\n */\r\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\r\n\r\n\r\n/**\r\n * Whether it's okay to make a request to the server. A handler can return\r\n * false if the channel should fail. For example, if the user has logged out,\r\n * the handler may want all requests to fail immediately.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {WebChannelBase.Error} An error code. The code should\r\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\r\n * error code will cause a failure.\r\n */\r\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\r\n return WebChannelBase.Error.OK;\r\n};\r\n\r\n\r\n/**\r\n * Indicates the WebChannel has successfully negotiated with the server\r\n * and can now send and receive data.\r\n * @param {WebChannelBase} channel The channel.\r\n */\r\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\r\n\r\n\r\n/**\r\n * New input is available for the application to process.\r\n *\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {Array<?>} array The data array.\r\n */\r\nWebChannelBase.Handler.prototype.channelHandleArray = function(\r\n channel, array) {};\r\n\r\n\r\n/**\r\n * Indicates messages that have been successfully sent on the channel.\r\n *\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {!ChannelRequest} request The request object that contains\r\n * the pending messages that have been successfully delivered to the server.\r\n */\r\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\r\n\r\n\r\n/**\r\n * Indicates an error occurred on the WebChannel.\r\n *\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {WebChannelBase.Error} error The error code.\r\n */\r\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\r\n\r\n\r\n/**\r\n * Indicates the WebChannel is closed. Also notifies about which maps,\r\n * if any, that may not have been delivered to the server.\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\r\n * array of pending maps, which may or may not have been delivered to the\r\n * server.\r\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\r\n * The array of undelivered maps, which have definitely not been delivered\r\n * to the server.\r\n */\r\nWebChannelBase.Handler.prototype.channelClosed = function(\r\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\r\n\r\n\r\n/**\r\n * Gets any parameters that should be added at the time another connection is\r\n * made to the server.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {!Object} Extra parameter keys and values to add to the requests.\r\n */\r\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\r\n return {};\r\n};\r\n\r\n\r\n/**\r\n * Gets the URI of an image that can be used to test network connectivity.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {goog.Uri?} A custom URI to load for the network test.\r\n */\r\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Gets whether this channel is currently active. This is used to determine the\r\n * length of time to wait before retrying.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {boolean} Whether the channel is currently active.\r\n */\r\nWebChannelBase.Handler.prototype.isActive = function(channel) {\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Called by the channel if enumeration of the map throws an exception.\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {Object} map The map that can't be enumerated.\r\n */\r\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\r\n\r\n\r\n/**\r\n * Allows the handler to override a host prefix provided by the server. Will\r\n * be called whenever the channel has received such a prefix and is considering\r\n * its use.\r\n * @param {?string} serverHostPrefix The host prefix provided by the server.\r\n * @return {?string} The host prefix the client should use.\r\n */\r\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\r\n serverHostPrefix) {\r\n return serverHostPrefix;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Generics method for collection-like classes and objects.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * This file contains functions to work with collections. It supports using\r\n * Map, Set, Array and Object and other classes that implement collection-like\r\n * methods.\r\n * @suppress {strictMissingProperties}\r\n */\r\n\r\n\r\ngoog.provide('goog.structs');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.object');\r\n\r\n\r\n// We treat an object as a dictionary if it has getKeys or it is an object that\r\n// isn't arrayLike.\r\n\r\n\r\n/**\r\n * Returns the number of values in the collection-like object.\r\n * @param {Object} col The collection-like object.\r\n * @return {number} The number of values in the collection-like object.\r\n */\r\ngoog.structs.getCount = function(col) {\r\n if (col.getCount && typeof col.getCount == 'function') {\r\n return col.getCount();\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return col.length;\r\n }\r\n return goog.object.getCount(col);\r\n};\r\n\r\n\r\n/**\r\n * Returns the values of the collection-like object.\r\n * @param {Object} col The collection-like object.\r\n * @return {!Array<?>} The values in the collection-like object.\r\n */\r\ngoog.structs.getValues = function(col) {\r\n if (col.getValues && typeof col.getValues == 'function') {\r\n return col.getValues();\r\n }\r\n if (goog.isString(col)) {\r\n return col.split('');\r\n }\r\n if (goog.isArrayLike(col)) {\r\n var rv = [];\r\n var l = col.length;\r\n for (var i = 0; i < l; i++) {\r\n rv.push(col[i]);\r\n }\r\n return rv;\r\n }\r\n return goog.object.getValues(col);\r\n};\r\n\r\n\r\n/**\r\n * Returns the keys of the collection. Some collections have no notion of\r\n * keys/indexes and this function will return undefined in those cases.\r\n * @param {Object} col The collection-like object.\r\n * @return {!Array|undefined} The keys in the collection.\r\n */\r\ngoog.structs.getKeys = function(col) {\r\n if (col.getKeys && typeof col.getKeys == 'function') {\r\n return col.getKeys();\r\n }\r\n // if we have getValues but no getKeys we know this is a key-less collection\r\n if (col.getValues && typeof col.getValues == 'function') {\r\n return undefined;\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n var rv = [];\r\n var l = col.length;\r\n for (var i = 0; i < l; i++) {\r\n rv.push(i);\r\n }\r\n return rv;\r\n }\r\n\r\n return goog.object.getKeys(col);\r\n};\r\n\r\n\r\n/**\r\n * Whether the collection contains the given value. This is O(n) and uses\r\n * equals (==) to test the existence.\r\n * @param {Object} col The collection-like object.\r\n * @param {*} val The value to check for.\r\n * @return {boolean} True if the map contains the value.\r\n */\r\ngoog.structs.contains = function(col, val) {\r\n if (col.contains && typeof col.contains == 'function') {\r\n return col.contains(val);\r\n }\r\n if (col.containsValue && typeof col.containsValue == 'function') {\r\n return col.containsValue(val);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\r\n }\r\n return goog.object.containsValue(col, val);\r\n};\r\n\r\n\r\n/**\r\n * Whether the collection is empty.\r\n * @param {Object} col The collection-like object.\r\n * @return {boolean} True if empty.\r\n */\r\ngoog.structs.isEmpty = function(col) {\r\n if (col.isEmpty && typeof col.isEmpty == 'function') {\r\n return col.isEmpty();\r\n }\r\n\r\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\r\n // string as\r\n // collection and as such even whitespace matters\r\n\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.isEmpty(/** @type {!Array<?>} */ (col));\r\n }\r\n return goog.object.isEmpty(col);\r\n};\r\n\r\n\r\n/**\r\n * Removes all the elements from the collection.\r\n * @param {Object} col The collection-like object.\r\n */\r\ngoog.structs.clear = function(col) {\r\n // NOTE(arv): This should not contain strings because strings are immutable\r\n if (col.clear && typeof col.clear == 'function') {\r\n col.clear();\r\n } else if (goog.isArrayLike(col)) {\r\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\r\n } else {\r\n goog.object.clear(col);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each value in a collection. The function takes\r\n * three arguments; the value, the key and the collection.\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\r\n * This function takes\r\n * 3 arguments (the value, the key or undefined if the collection has no\r\n * notion of keys, and the collection) and the return value is irrelevant.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @template T,S\r\n * @deprecated Use a more specific method, e.g. goog.array.forEach,\r\n * goog.object.forEach, or for-of.\r\n */\r\ngoog.structs.forEach = function(col, f, opt_obj) {\r\n if (col.forEach && typeof col.forEach == 'function') {\r\n col.forEach(f, opt_obj);\r\n } else if (goog.isArrayLike(col) || goog.isString(col)) {\r\n goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n } else {\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for every value in the collection. When a call returns true,\r\n * adds the value to a new collection (Array is returned by default).\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\r\n * value. This function takes\r\n * 3 arguments (the value, the key or undefined if the collection has no\r\n * notion of keys, and the collection) and should return a Boolean. If the\r\n * return value is true the value is added to the result collection. If it\r\n * is false the value is not included.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {!Object|!Array<?>} A new collection where the passed values are\r\n * present. If col is a key-less collection an array is returned. If col\r\n * has keys and values a plain old JS object is returned.\r\n * @template T,S\r\n */\r\ngoog.structs.filter = function(col, f, opt_obj) {\r\n if (typeof col.filter == 'function') {\r\n return col.filter(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n\r\n var rv;\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n if (keys) {\r\n rv = {};\r\n for (var i = 0; i < l; i++) {\r\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\r\n rv[keys[i]] = values[i];\r\n }\r\n }\r\n } else {\r\n // We should not use goog.array.filter here since we want to make sure that\r\n // the index is undefined as well as make sure that col is passed to the\r\n // function.\r\n rv = [];\r\n for (var i = 0; i < l; i++) {\r\n if (f.call(opt_obj, values[i], undefined, col)) {\r\n rv.push(values[i]);\r\n }\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for every value in the collection and adds the result into a\r\n * new collection (defaults to creating a new Array).\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\r\n * This function takes 3 arguments (the value, the key or undefined if the\r\n * collection has no notion of keys, and the collection) and should return\r\n * something. The result will be used as the value in the new collection.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\r\n * col is a key-less collection an array is returned. If col has keys and\r\n * values a plain old JS object is returned.\r\n * @template T,S,V\r\n */\r\ngoog.structs.map = function(col, f, opt_obj) {\r\n if (typeof col.map == 'function') {\r\n return col.map(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n\r\n var rv;\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n if (keys) {\r\n rv = {};\r\n for (var i = 0; i < l; i++) {\r\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\r\n }\r\n } else {\r\n // We should not use goog.array.map here since we want to make sure that\r\n // the index is undefined as well as make sure that col is passed to the\r\n // function.\r\n rv = [];\r\n for (var i = 0; i < l; i++) {\r\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Calls f for each value in a collection. If any call returns true this returns\r\n * true (without checking the rest). If all returns false this returns false.\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\r\n * value. This function takes 3 arguments (the value, the key or undefined\r\n * if the collection has no notion of keys, and the collection) and should\r\n * return a boolean.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {boolean} True if any value passes the test.\r\n * @template T,S\r\n */\r\ngoog.structs.some = function(col, f, opt_obj) {\r\n if (typeof col.some == 'function') {\r\n return col.some(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Calls f for each value in a collection. If all calls return true this return\r\n * true this returns true. If any returns false this returns false at this point\r\n * and does not continue to check the remaining values.\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\r\n * value. This function takes 3 arguments (the value, the key or\r\n * undefined if the collection has no notion of keys, and the collection)\r\n * and should return a boolean.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {boolean} True if all key-value pairs pass the test.\r\n * @template T,S\r\n */\r\ngoog.structs.every = function(col, f, opt_obj) {\r\n if (typeof col.every == 'function') {\r\n return col.every(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Datastructure: Hash Map.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * This file contains an implementation of a Map structure. It implements a lot\r\n * of the methods used in goog.structs so those functions work on hashes. This\r\n * is best suited for complex key types. For simple keys such as numbers and\r\n * strings consider using the lighter-weight utilities in goog.object.\r\n */\r\n\r\n\r\ngoog.provide('goog.structs.Map');\r\n\r\ngoog.require('goog.iter.Iterator');\r\ngoog.require('goog.iter.StopIteration');\r\n\r\n\r\n\r\n/**\r\n * Class for Hash Map datastructure.\r\n * @param {*=} opt_map Map or Object to initialize the map with.\r\n * @param {...*} var_args If 2 or more arguments are present then they\r\n * will be used as key-value pairs.\r\n * @constructor\r\n * @template K, V\r\n * @deprecated This type is misleading: use ES6 Map instead.\r\n */\r\ngoog.structs.Map = function(opt_map, var_args) {\r\n\r\n /**\r\n * Underlying JS object used to implement the map.\r\n * @private {!Object}\r\n */\r\n this.map_ = {};\r\n\r\n /**\r\n * An array of keys. This is necessary for two reasons:\r\n * 1. Iterating the keys using for (var key in this.map_) allocates an\r\n * object for every key in IE which is really bad for IE6 GC perf.\r\n * 2. Without a side data structure, we would need to escape all the keys\r\n * as that would be the only way we could tell during iteration if the\r\n * key was an internal key or a property of the object.\r\n *\r\n * This array can contain deleted keys so it's necessary to check the map\r\n * as well to see if the key is still in the map (this doesn't require a\r\n * memory allocation in IE).\r\n * @private {!Array<string>}\r\n */\r\n this.keys_ = [];\r\n\r\n /**\r\n * The number of key value pairs in the map.\r\n * @private {number}\r\n */\r\n this.count_ = 0;\r\n\r\n /**\r\n * Version used to detect changes while iterating.\r\n * @private {number}\r\n */\r\n this.version_ = 0;\r\n\r\n var argLength = arguments.length;\r\n\r\n if (argLength > 1) {\r\n if (argLength % 2) {\r\n throw new Error('Uneven number of arguments');\r\n }\r\n for (var i = 0; i < argLength; i += 2) {\r\n this.set(arguments[i], arguments[i + 1]);\r\n }\r\n } else if (opt_map) {\r\n this.addAll(/** @type {!Object} */ (opt_map));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of key-value pairs in the map.\r\n */\r\ngoog.structs.Map.prototype.getCount = function() {\r\n return this.count_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the values of the map.\r\n * @return {!Array<V>} The values in the map.\r\n */\r\ngoog.structs.Map.prototype.getValues = function() {\r\n this.cleanupKeysArray_();\r\n\r\n var rv = [];\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n rv.push(this.map_[key]);\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Returns the keys of the map.\r\n * @return {!Array<string>} Array of string values.\r\n */\r\ngoog.structs.Map.prototype.getKeys = function() {\r\n this.cleanupKeysArray_();\r\n return /** @type {!Array<string>} */ (this.keys_.concat());\r\n};\r\n\r\n\r\n/**\r\n * Whether the map contains the given key.\r\n * @param {*} key The key to check for.\r\n * @return {boolean} Whether the map contains the key.\r\n */\r\ngoog.structs.Map.prototype.containsKey = function(key) {\r\n return goog.structs.Map.hasKey_(this.map_, key);\r\n};\r\n\r\n\r\n/**\r\n * Whether the map contains the given value. This is O(n).\r\n * @param {V} val The value to check for.\r\n * @return {boolean} Whether the map contains the value.\r\n */\r\ngoog.structs.Map.prototype.containsValue = function(val) {\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Whether this map is equal to the argument map.\r\n * @param {goog.structs.Map} otherMap The map against which to test equality.\r\n * @param {function(V, V): boolean=} opt_equalityFn Optional equality function\r\n * to test equality of values. If not specified, this will test whether\r\n * the values contained in each map are identical objects.\r\n * @return {boolean} Whether the maps are equal.\r\n */\r\ngoog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) {\r\n if (this === otherMap) {\r\n return true;\r\n }\r\n\r\n if (this.count_ != otherMap.getCount()) {\r\n return false;\r\n }\r\n\r\n var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals;\r\n\r\n this.cleanupKeysArray_();\r\n for (var key, i = 0; key = this.keys_[i]; i++) {\r\n if (!equalityFn(this.get(key), otherMap.get(key))) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Default equality test for values.\r\n * @param {*} a The first value.\r\n * @param {*} b The second value.\r\n * @return {boolean} Whether a and b reference the same object.\r\n */\r\ngoog.structs.Map.defaultEquals = function(a, b) {\r\n return a === b;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the map is empty.\r\n */\r\ngoog.structs.Map.prototype.isEmpty = function() {\r\n return this.count_ == 0;\r\n};\r\n\r\n\r\n/**\r\n * Removes all key-value pairs from the map.\r\n */\r\ngoog.structs.Map.prototype.clear = function() {\r\n this.map_ = {};\r\n this.keys_.length = 0;\r\n this.count_ = 0;\r\n this.version_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * Removes a key-value pair based on the key. This is O(logN) amortized due to\r\n * updating the keys array whenever the count becomes half the size of the keys\r\n * in the keys array.\r\n * @param {*} key The key to remove.\r\n * @return {boolean} Whether object was removed.\r\n */\r\ngoog.structs.Map.prototype.remove = function(key) {\r\n if (goog.structs.Map.hasKey_(this.map_, key)) {\r\n delete this.map_[key];\r\n this.count_--;\r\n this.version_++;\r\n\r\n // clean up the keys array if the threshold is hit\r\n if (this.keys_.length > 2 * this.count_) {\r\n this.cleanupKeysArray_();\r\n }\r\n\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Cleans up the temp keys array by removing entries that are no longer in the\r\n * map.\r\n * @private\r\n */\r\ngoog.structs.Map.prototype.cleanupKeysArray_ = function() {\r\n if (this.count_ != this.keys_.length) {\r\n // First remove keys that are no longer in the map.\r\n var srcIndex = 0;\r\n var destIndex = 0;\r\n while (srcIndex < this.keys_.length) {\r\n var key = this.keys_[srcIndex];\r\n if (goog.structs.Map.hasKey_(this.map_, key)) {\r\n this.keys_[destIndex++] = key;\r\n }\r\n srcIndex++;\r\n }\r\n this.keys_.length = destIndex;\r\n }\r\n\r\n if (this.count_ != this.keys_.length) {\r\n // If the count still isn't correct, that means we have duplicates. This can\r\n // happen when the same key is added and removed multiple times. Now we have\r\n // to allocate one extra Object to remove the duplicates. This could have\r\n // been done in the first pass, but in the common case, we can avoid\r\n // allocating an extra object by only doing this when necessary.\r\n var seen = {};\r\n var srcIndex = 0;\r\n var destIndex = 0;\r\n while (srcIndex < this.keys_.length) {\r\n var key = this.keys_[srcIndex];\r\n if (!(goog.structs.Map.hasKey_(seen, key))) {\r\n this.keys_[destIndex++] = key;\r\n seen[key] = 1;\r\n }\r\n srcIndex++;\r\n }\r\n this.keys_.length = destIndex;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns the value for the given key. If the key is not found and the default\r\n * value is not given this will return `undefined`.\r\n * @param {*} key The key to get the value for.\r\n * @param {DEFAULT=} opt_val The value to return if no item is found for the\r\n * given key, defaults to undefined.\r\n * @return {V|DEFAULT} The value for the given key.\r\n * @template DEFAULT\r\n */\r\ngoog.structs.Map.prototype.get = function(key, opt_val) {\r\n if (goog.structs.Map.hasKey_(this.map_, key)) {\r\n return this.map_[key];\r\n }\r\n return opt_val;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the map.\r\n * @param {*} key The key.\r\n * @param {V} value The value to add.\r\n * @return {*} Some subclasses return a value.\r\n */\r\ngoog.structs.Map.prototype.set = function(key, value) {\r\n if (!(goog.structs.Map.hasKey_(this.map_, key))) {\r\n this.count_++;\r\n // TODO(johnlenz): This class lies, it claims to return an array of string\r\n // keys, but instead returns the original object used.\r\n this.keys_.push(/** @type {?} */ (key));\r\n // Only change the version if we add a new key.\r\n this.version_++;\r\n }\r\n this.map_[key] = value;\r\n};\r\n\r\n\r\n/**\r\n * Adds multiple key-value pairs from another goog.structs.Map or Object.\r\n * @param {?Object} map Object containing the data to add.\r\n */\r\ngoog.structs.Map.prototype.addAll = function(map) {\r\n if (map instanceof goog.structs.Map) {\r\n var keys = map.getKeys();\r\n for (var i = 0; i < keys.length; i++) {\r\n this.set(keys[i], map.get(keys[i]));\r\n }\r\n } else {\r\n for (var key in map) {\r\n this.set(key, map[key]);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls the given function on each entry in the map.\r\n * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f\r\n * @param {T=} opt_obj The value of \"this\" inside f.\r\n * @template T\r\n */\r\ngoog.structs.Map.prototype.forEach = function(f, opt_obj) {\r\n var keys = this.getKeys();\r\n for (var i = 0; i < keys.length; i++) {\r\n var key = keys[i];\r\n var value = this.get(key);\r\n f.call(opt_obj, value, key, this);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clones a map and returns a new map.\r\n * @return {!goog.structs.Map} A new map with the same key-value pairs.\r\n */\r\ngoog.structs.Map.prototype.clone = function() {\r\n return new goog.structs.Map(this);\r\n};\r\n\r\n\r\n/**\r\n * Returns a new map in which all the keys and values are interchanged\r\n * (keys become values and values become keys). If multiple keys map to the\r\n * same value, the chosen transposed value is implementation-dependent.\r\n *\r\n * It acts very similarly to {goog.object.transpose(Object)}.\r\n *\r\n * @return {!goog.structs.Map} The transposed map.\r\n */\r\ngoog.structs.Map.prototype.transpose = function() {\r\n var transposed = new goog.structs.Map();\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n var value = this.map_[key];\r\n transposed.set(value, key);\r\n }\r\n\r\n return transposed;\r\n};\r\n\r\n\r\n/**\r\n * @return {!Object} Object representation of the map.\r\n */\r\ngoog.structs.Map.prototype.toObject = function() {\r\n this.cleanupKeysArray_();\r\n var obj = {};\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n obj[key] = this.map_[key];\r\n }\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the keys in the map. Removal of keys\r\n * while iterating might have undesired side effects.\r\n * @return {!goog.iter.Iterator} An iterator over the keys in the map.\r\n */\r\ngoog.structs.Map.prototype.getKeyIterator = function() {\r\n return this.__iterator__(true);\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the values in the map. Removal of\r\n * keys while iterating might have undesired side effects.\r\n * @return {!goog.iter.Iterator} An iterator over the values in the map.\r\n */\r\ngoog.structs.Map.prototype.getValueIterator = function() {\r\n return this.__iterator__(false);\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the values or the keys in the map.\r\n * This throws an exception if the map was mutated since the iterator was\r\n * created.\r\n * @param {boolean=} opt_keys True to iterate over the keys. False to iterate\r\n * over the values. The default value is false.\r\n * @return {!goog.iter.Iterator} An iterator over the values or keys in the map.\r\n */\r\ngoog.structs.Map.prototype.__iterator__ = function(opt_keys) {\r\n // Clean up keys to minimize the risk of iterating over dead keys.\r\n this.cleanupKeysArray_();\r\n\r\n var i = 0;\r\n var version = this.version_;\r\n var selfObj = this;\r\n\r\n var newIter = new goog.iter.Iterator;\r\n newIter.next = function() {\r\n if (version != selfObj.version_) {\r\n throw new Error('The map has changed since the iterator was created');\r\n }\r\n if (i >= selfObj.keys_.length) {\r\n throw goog.iter.StopIteration;\r\n }\r\n var key = selfObj.keys_[i++];\r\n return opt_keys ? key : selfObj.map_[key];\r\n };\r\n return newIter;\r\n};\r\n\r\n\r\n/**\r\n * Safe way to test for hasOwnProperty. It even allows testing for\r\n * 'hasOwnProperty'.\r\n * @param {!Object} obj The object to test for presence of the given key.\r\n * @param {*} key The key to check for.\r\n * @return {boolean} Whether the object has the key.\r\n * @private\r\n */\r\ngoog.structs.Map.hasKey_ = function(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for string manipulation.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\n/**\r\n * Namespace for string utilities\r\n */\r\ngoog.provide('goog.string');\r\ngoog.provide('goog.string.Unicode');\r\n\r\ngoog.require('goog.string.internal');\r\n\r\n\r\n/**\r\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\r\n * with detection of double-escaping as this letter is frequently used.\r\n */\r\ngoog.string.DETECT_DOUBLE_ESCAPING =\r\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to force non-dom html unescaping.\r\n */\r\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\r\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\r\n\r\n\r\n/**\r\n * Common Unicode string characters.\r\n * @enum {string}\r\n */\r\ngoog.string.Unicode = {\r\n NBSP: '\\xa0'\r\n};\r\n\r\n\r\n/**\r\n * Fast prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the start of `str`.\r\n * @return {boolean} True if `str` begins with `prefix`.\r\n */\r\ngoog.string.startsWith = goog.string.internal.startsWith;\r\n\r\n\r\n/**\r\n * Fast suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix`.\r\n */\r\ngoog.string.endsWith = goog.string.internal.endsWith;\r\n\r\n\r\n/**\r\n * Case-insensitive prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` begins with `prefix` (ignoring\r\n * case).\r\n */\r\ngoog.string.caseInsensitiveStartsWith =\r\n goog.string.internal.caseInsensitiveStartsWith;\r\n\r\n\r\n/**\r\n * Case-insensitive suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix` (ignoring\r\n * case).\r\n */\r\ngoog.string.caseInsensitiveEndsWith =\r\n goog.string.internal.caseInsensitiveEndsWith;\r\n\r\n\r\n/**\r\n * Case-insensitive equality checker.\r\n * @param {string} str1 First string to check.\r\n * @param {string} str2 Second string to check.\r\n * @return {boolean} True if `str1` and `str2` are the same string,\r\n * ignoring case.\r\n */\r\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\r\n\r\n\r\n/**\r\n * Does simple python-style string substitution.\r\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\r\n * @param {string} str The string containing the pattern.\r\n * @param {...*} var_args The items to substitute into the pattern.\r\n * @return {string} A copy of `str` in which each occurrence of\r\n * {@code %s} has been replaced an argument from `var_args`.\r\n */\r\ngoog.string.subs = function(str, var_args) {\r\n var splitParts = str.split('%s');\r\n var returnString = '';\r\n\r\n var subsArguments = Array.prototype.slice.call(arguments, 1);\r\n while (subsArguments.length &&\r\n // Replace up to the last split part. We are inserting in the\r\n // positions between split parts.\r\n splitParts.length > 1) {\r\n returnString += splitParts.shift() + subsArguments.shift();\r\n }\r\n\r\n return returnString + splitParts.join('%s'); // Join unused '%s'\r\n};\r\n\r\n\r\n/**\r\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\r\n * and tabs) to a single space, and strips leading and trailing whitespace.\r\n * @param {string} str Input string.\r\n * @return {string} A copy of `str` with collapsed whitespace.\r\n */\r\ngoog.string.collapseWhitespace = function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is empty or contains only whitespaces.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty or whitespace only.\r\n */\r\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\r\n\r\n\r\n/**\r\n * Checks if a string is empty.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty.\r\n */\r\ngoog.string.isEmptyString = function(str) {\r\n return str.length == 0;\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is empty or contains only whitespaces.\r\n *\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty or whitespace only.\r\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\r\n */\r\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\r\n\r\n\r\n/**\r\n * Checks if a string is null, undefined, empty or contains only whitespaces.\r\n * @param {*} str The string to check.\r\n * @return {boolean} Whether `str` is null, undefined, empty, or\r\n * whitespace only.\r\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\r\n * instead.\r\n */\r\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\r\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is null, undefined, empty or contains only whitespaces.\r\n *\r\n * @param {*} str The string to check.\r\n * @return {boolean} Whether `str` is null, undefined, empty, or\r\n * whitespace only.\r\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\r\n */\r\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\r\n\r\n\r\n/**\r\n * Checks if a string is all breaking whitespace.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether the string is all breaking whitespace.\r\n */\r\ngoog.string.isBreakingWhitespace = function(str) {\r\n return !/[^\\t\\n\\r ]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string contains all letters.\r\n * @param {string} str string to check.\r\n * @return {boolean} True if `str` consists entirely of letters.\r\n */\r\ngoog.string.isAlpha = function(str) {\r\n return !/[^a-zA-Z]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string contains only numbers.\r\n * @param {*} str string to check. If not a string, it will be\r\n * casted to one.\r\n * @return {boolean} True if `str` is numeric.\r\n */\r\ngoog.string.isNumeric = function(str) {\r\n return !/[^0-9]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string contains only numbers or letters.\r\n * @param {string} str string to check.\r\n * @return {boolean} True if `str` is alphanumeric.\r\n */\r\ngoog.string.isAlphaNumeric = function(str) {\r\n return !/[^a-zA-Z0-9]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a character is a space character.\r\n * @param {string} ch Character to check.\r\n * @return {boolean} True if `ch` is a space.\r\n */\r\ngoog.string.isSpace = function(ch) {\r\n return ch == ' ';\r\n};\r\n\r\n\r\n/**\r\n * Checks if a character is a valid unicode character.\r\n * @param {string} ch Character to check.\r\n * @return {boolean} True if `ch` is a valid unicode character.\r\n */\r\ngoog.string.isUnicodeChar = function(ch) {\r\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\r\n ch >= '\\u0080' && ch <= '\\uFFFD';\r\n};\r\n\r\n\r\n/**\r\n * Takes a string and replaces newlines with a space. Multiple lines are\r\n * replaced with a single space.\r\n * @param {string} str The string from which to strip newlines.\r\n * @return {string} A copy of `str` stripped of newlines.\r\n */\r\ngoog.string.stripNewlines = function(str) {\r\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\r\n};\r\n\r\n\r\n/**\r\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\r\n * @param {string} str The string to in which to canonicalize newlines.\r\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\r\n */\r\ngoog.string.canonicalizeNewlines = function(str) {\r\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\r\n};\r\n\r\n\r\n/**\r\n * Normalizes whitespace in a string, replacing all whitespace chars with\r\n * a space.\r\n * @param {string} str The string in which to normalize whitespace.\r\n * @return {string} A copy of `str` with all whitespace normalized.\r\n */\r\ngoog.string.normalizeWhitespace = function(str) {\r\n return str.replace(/\\xa0|\\s/g, ' ');\r\n};\r\n\r\n\r\n/**\r\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\r\n * with a single space. Replaces non-breaking space with a space.\r\n * @param {string} str The string in which to normalize spaces.\r\n * @return {string} A copy of `str` with all consecutive spaces and tabs\r\n * replaced with a single space.\r\n */\r\ngoog.string.normalizeSpaces = function(str) {\r\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\r\n};\r\n\r\n\r\n/**\r\n * Removes the breaking spaces from the left and right of the string and\r\n * collapses the sequences of breaking spaces in the middle into single spaces.\r\n * The original and the result strings render the same way in HTML.\r\n * @param {string} str A string in which to collapse spaces.\r\n * @return {string} Copy of the string with normalized breaking spaces.\r\n */\r\ngoog.string.collapseBreakingSpaces = function(str) {\r\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\r\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\r\n};\r\n\r\n\r\n/**\r\n * Trims white spaces to the left and right of a string.\r\n * @param {string} str The string to trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.trim = goog.string.internal.trim;\r\n\r\n\r\n/**\r\n * Trims whitespaces at the left end of a string.\r\n * @param {string} str The string to left trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.trimLeft = function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return str.replace(/^[\\s\\xa0]+/, '');\r\n};\r\n\r\n\r\n/**\r\n * Trims whitespaces at the right end of a string.\r\n * @param {string} str The string to right trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.trimRight = function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return str.replace(/[\\s\\xa0]+$/, '');\r\n};\r\n\r\n\r\n/**\r\n * A string comparator that ignores case.\r\n * -1 = str1 less than str2\r\n * 0 = str1 equals str2\r\n * 1 = str1 greater than str2\r\n *\r\n * @param {string} str1 The string to compare.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} The comparator result, as described above.\r\n */\r\ngoog.string.caseInsensitiveCompare =\r\n goog.string.internal.caseInsensitiveCompare;\r\n\r\n\r\n/**\r\n * Compares two strings interpreting their numeric substrings as numbers.\r\n *\r\n * @param {string} str1 First string.\r\n * @param {string} str2 Second string.\r\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\r\n * non-negative integers, non-numeric characters and optionally fractional\r\n * numbers starting with a decimal point.\r\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\r\n * str1 > str2.\r\n * @private\r\n */\r\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\r\n if (str1 == str2) {\r\n return 0;\r\n }\r\n if (!str1) {\r\n return -1;\r\n }\r\n if (!str2) {\r\n return 1;\r\n }\r\n\r\n // Using match to split the entire string ahead of time turns out to be faster\r\n // for most inputs than using RegExp.exec or iterating over each character.\r\n var tokens1 = str1.toLowerCase().match(tokenizerRegExp);\r\n var tokens2 = str2.toLowerCase().match(tokenizerRegExp);\r\n\r\n var count = Math.min(tokens1.length, tokens2.length);\r\n\r\n for (var i = 0; i < count; i++) {\r\n var a = tokens1[i];\r\n var b = tokens2[i];\r\n\r\n // Compare pairs of tokens, returning if one token sorts before the other.\r\n if (a != b) {\r\n // Only if both tokens are integers is a special comparison required.\r\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\r\n var num1 = parseInt(a, 10);\r\n if (!isNaN(num1)) {\r\n var num2 = parseInt(b, 10);\r\n if (!isNaN(num2) && num1 - num2) {\r\n return num1 - num2;\r\n }\r\n }\r\n return a < b ? -1 : 1;\r\n }\r\n }\r\n\r\n // If one string is a substring of the other, the shorter string sorts first.\r\n if (tokens1.length != tokens2.length) {\r\n return tokens1.length - tokens2.length;\r\n }\r\n\r\n // The two strings must be equivalent except for case (perfect equality is\r\n // tested at the head of the function.) Revert to default ASCII string\r\n // comparison to stabilize the sort.\r\n return str1 < str2 ? -1 : 1;\r\n};\r\n\r\n\r\n/**\r\n * String comparison function that handles non-negative integer numbers in a\r\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\r\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\r\n * is mostly case-insensitive, though strings that are identical except for case\r\n * are sorted with the upper-case strings before lower-case.\r\n *\r\n * This comparison function is up to 50x slower than either the default or the\r\n * case-insensitive compare. It should not be used in time-critical code, but\r\n * should be fast enough to sort several hundred short strings (like filenames)\r\n * with a reasonable delay.\r\n *\r\n * @param {string} str1 The string to compare in a numerically sensitive way.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\r\n * 0 if str1 > str2.\r\n */\r\ngoog.string.intAwareCompare = function(str1, str2) {\r\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\r\n};\r\n\r\n\r\n/**\r\n * String comparison function that handles non-negative integer and fractional\r\n * numbers in a way humans might expect. Using this function, the string\r\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\r\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\r\n * dots.\r\n *\r\n * @param {string} str1 The string to compare in a numerically sensitive way.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\r\n * 0 if str1 > str2.\r\n */\r\ngoog.string.floatAwareCompare = function(str1, str2) {\r\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\r\n};\r\n\r\n\r\n/**\r\n * Alias for {@link goog.string.floatAwareCompare}.\r\n *\r\n * @param {string} str1\r\n * @param {string} str2\r\n * @return {number}\r\n */\r\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\r\n\r\n\r\n/**\r\n * URL-encodes a string\r\n * @param {*} str The string to url-encode.\r\n * @return {string} An encoded copy of `str` that is safe for urls.\r\n * Note that '#', ':', and other characters used to delimit portions\r\n * of URLs *will* be encoded.\r\n */\r\ngoog.string.urlEncode = function(str) {\r\n return encodeURIComponent(String(str));\r\n};\r\n\r\n\r\n/**\r\n * URL-decodes the string. We need to specially handle '+'s because\r\n * the javascript library doesn't convert them to spaces.\r\n * @param {string} str The string to url decode.\r\n * @return {string} The decoded `str`.\r\n */\r\ngoog.string.urlDecode = function(str) {\r\n return decodeURIComponent(str.replace(/\\+/g, ' '));\r\n};\r\n\r\n\r\n/**\r\n * Converts \\n to <br>s or <br />s.\r\n * @param {string} str The string in which to convert newlines.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} A copy of `str` with converted newlines.\r\n */\r\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\r\n\r\n\r\n/**\r\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\r\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\r\n * value within double or single quotes.\r\n *\r\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\r\n * be valid, but it has been decided to escape it for consistency with other\r\n * implementations.\r\n *\r\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\r\n * lowercase letter \"e\".\r\n *\r\n * NOTE(user):\r\n * HtmlEscape is often called during the generation of large blocks of HTML.\r\n * Using statics for the regular expressions and strings is an optimization\r\n * that can more than half the amount of time IE spends in this function for\r\n * large apps, since strings and regexes both contribute to GC allocations.\r\n *\r\n * Testing for the presence of a character before escaping increases the number\r\n * of function calls, but actually provides a speed increase for the average\r\n * case -- since the average case often doesn't require the escaping of all 4\r\n * characters and indexOf() is much cheaper than replace().\r\n * The worst case does suffer slightly from the additional calls, therefore the\r\n * opt_isLikelyToContainHtmlChars option has been included for situations\r\n * where all 4 HTML entities are very likely to be present and need escaping.\r\n *\r\n * Some benchmarks (times tended to fluctuate +-0.05ms):\r\n * FireFox IE6\r\n * (no chars / average (mix of cases) / all 4 chars)\r\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\r\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\r\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\r\n *\r\n * An additional advantage of checking if replace actually needs to be called\r\n * is a reduction in the number of object allocations, so as the size of the\r\n * application grows the difference between the various methods would increase.\r\n *\r\n * @param {string} str string to be escaped.\r\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\r\n * if the character needs replacing - use this option if you expect each of\r\n * the characters to appear often. Leave false if you expect few html\r\n * characters to occur in your strings, such as if you are escaping HTML.\r\n * @return {string} An escaped copy of `str`.\r\n */\r\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\r\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\r\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\r\n str = str.replace(goog.string.E_RE_, '&#101;');\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.E_RE_ = /e/g;\r\n\r\n\r\n/**\r\n * Unescapes an HTML string.\r\n *\r\n * @param {string} str The string to unescape.\r\n * @return {string} An unescaped copy of `str`.\r\n */\r\ngoog.string.unescapeEntities = function(str) {\r\n if (goog.string.contains(str, '&')) {\r\n // We are careful not to use a DOM if we do not have one or we explicitly\r\n // requested non-DOM html unescaping.\r\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\r\n 'document' in goog.global) {\r\n return goog.string.unescapeEntitiesUsingDom_(str);\r\n } else {\r\n // Fall back on pure XML entities\r\n return goog.string.unescapePureXmlEntities_(str);\r\n }\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Unescapes a HTML string using the provided document.\r\n *\r\n * @param {string} str The string to unescape.\r\n * @param {!Document} document A document to use in escaping the string.\r\n * @return {string} An unescaped copy of `str`.\r\n */\r\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\r\n if (goog.string.contains(str, '&')) {\r\n return goog.string.unescapeEntitiesUsingDom_(str, document);\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\r\n * entities. This function is XSS-safe and whitespace-preserving.\r\n * @private\r\n * @param {string} str The string to unescape.\r\n * @param {Document=} opt_document An optional document to use for creating\r\n * elements. If this is not specified then the default window.document\r\n * will be used.\r\n * @return {string} The unescaped `str` string.\r\n */\r\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\r\n /** @type {!Object<string, string>} */\r\n var seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"'};\r\n /** @type {!Element} */\r\n var div;\r\n if (opt_document) {\r\n div = opt_document.createElement('div');\r\n } else {\r\n div = goog.global.document.createElement('div');\r\n }\r\n // Match as many valid entity characters as possible. If the actual entity\r\n // happens to be shorter, it will still work as innerHTML will return the\r\n // trailing characters unchanged. Since the entity characters do not include\r\n // open angle bracket, there is no chance of XSS from the innerHTML use.\r\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\r\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\r\n // Check for cached entity.\r\n var value = seen[s];\r\n if (value) {\r\n return value;\r\n }\r\n // Check for numeric entity.\r\n if (entity.charAt(0) == '#') {\r\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers.\r\n var n = Number('0' + entity.substr(1));\r\n if (!isNaN(n)) {\r\n value = String.fromCharCode(n);\r\n }\r\n }\r\n // Fall back to innerHTML otherwise.\r\n if (!value) {\r\n // Append a non-entity character to avoid a bug in Webkit that parses\r\n // an invalid entity at the end of innerHTML text as the empty string.\r\n div.innerHTML = s + ' ';\r\n // Then remove the trailing character from the result.\r\n value = div.firstChild.nodeValue.slice(0, -1);\r\n }\r\n // Cache and return.\r\n return seen[s] = value;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Unescapes XML entities.\r\n * @private\r\n * @param {string} str The string to unescape.\r\n * @return {string} An unescaped copy of `str`.\r\n */\r\ngoog.string.unescapePureXmlEntities_ = function(str) {\r\n return str.replace(/&([^;]+);/g, function(s, entity) {\r\n switch (entity) {\r\n case 'amp':\r\n return '&';\r\n case 'lt':\r\n return '<';\r\n case 'gt':\r\n return '>';\r\n case 'quot':\r\n return '\"';\r\n default:\r\n if (entity.charAt(0) == '#') {\r\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex.\r\n var n = Number('0' + entity.substr(1));\r\n if (!isNaN(n)) {\r\n return String.fromCharCode(n);\r\n }\r\n }\r\n // For invalid entities we just return the entity\r\n return s;\r\n }\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Regular expression that matches an HTML entity.\r\n * See also HTML5: Tokenization / Tokenizing character references.\r\n * @private\r\n * @type {!RegExp}\r\n */\r\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\r\n\r\n\r\n/**\r\n * Do escaping of whitespace to preserve spatial formatting. We use character\r\n * entity #160 to make it safer for xml.\r\n * @param {string} str The string in which to escape whitespace.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} An escaped copy of `str`.\r\n */\r\ngoog.string.whitespaceEscape = function(str, opt_xml) {\r\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\r\n return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml);\r\n};\r\n\r\n\r\n/**\r\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\r\n * with non-breaking space Unicode characters.\r\n * @param {string} str The string in which to preserve whitespace.\r\n * @return {string} A copy of `str` with preserved whitespace.\r\n */\r\ngoog.string.preserveSpaces = function(str) {\r\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\r\n};\r\n\r\n\r\n/**\r\n * Strip quote characters around a string. The second argument is a string of\r\n * characters to treat as quotes. This can be a single character or a string of\r\n * multiple character and in that case each of those are treated as possible\r\n * quote characters. For example:\r\n *\r\n * <pre>\r\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\r\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\r\n * </pre>\r\n *\r\n * @param {string} str The string to strip.\r\n * @param {string} quoteChars The quote characters to strip.\r\n * @return {string} A copy of `str` without the quotes.\r\n */\r\ngoog.string.stripQuotes = function(str, quoteChars) {\r\n var length = quoteChars.length;\r\n for (var i = 0; i < length; i++) {\r\n var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\r\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\r\n return str.substring(1, str.length - 1);\r\n }\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Truncates a string to a certain length and adds '...' if necessary. The\r\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\r\n * 'Hello World!' produces 'Hello W...'.\r\n * @param {string} str The string to truncate.\r\n * @param {number} chars Max number of characters.\r\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\r\n * characters from being cut off in the middle.\r\n * @return {string} The truncated `str` string.\r\n */\r\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.unescapeEntities(str);\r\n }\r\n\r\n if (str.length > chars) {\r\n str = str.substring(0, chars - 3) + '...';\r\n }\r\n\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.htmlEscape(str);\r\n }\r\n\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Truncate a string in the middle, adding \"...\" if necessary,\r\n * and favoring the beginning of the string.\r\n * @param {string} str The string to truncate the middle of.\r\n * @param {number} chars Max number of characters.\r\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\r\n * characters from being cutoff in the middle.\r\n * @param {number=} opt_trailingChars Optional number of trailing characters to\r\n * leave at the end of the string, instead of truncating as close to the\r\n * middle as possible.\r\n * @return {string} A truncated copy of `str`.\r\n */\r\ngoog.string.truncateMiddle = function(\r\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.unescapeEntities(str);\r\n }\r\n\r\n if (opt_trailingChars && str.length > chars) {\r\n if (opt_trailingChars > chars) {\r\n opt_trailingChars = chars;\r\n }\r\n var endPoint = str.length - opt_trailingChars;\r\n var startPoint = chars - opt_trailingChars;\r\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\r\n } else if (str.length > chars) {\r\n // Favor the beginning of the string:\r\n var half = Math.floor(chars / 2);\r\n var endPos = str.length - half;\r\n half += chars % 2;\r\n str = str.substring(0, half) + '...' + str.substring(endPos);\r\n }\r\n\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.htmlEscape(str);\r\n }\r\n\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Special chars that need to be escaped for goog.string.quote.\r\n * @private {!Object<string, string>}\r\n */\r\ngoog.string.specialEscapeChars_ = {\r\n '\\0': '\\\\0',\r\n '\\b': '\\\\b',\r\n '\\f': '\\\\f',\r\n '\\n': '\\\\n',\r\n '\\r': '\\\\r',\r\n '\\t': '\\\\t',\r\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\r\n '\"': '\\\\\"',\r\n '\\\\': '\\\\\\\\',\r\n // To support the use case of embedding quoted strings inside of script\r\n // tags, we have to make sure HTML comments and opening/closing script tags do\r\n // not appear in the resulting string. The specific strings that must be\r\n // escaped are documented at:\r\n // http://www.w3.org/TR/html51/semantics.html#restrictions-for-contents-of-script-elements\r\n '<': '\\x3c'\r\n};\r\n\r\n\r\n/**\r\n * Character mappings used internally for goog.string.escapeChar.\r\n * @private {!Object<string, string>}\r\n */\r\ngoog.string.jsEscapeCache_ = {\r\n '\\'': '\\\\\\''\r\n};\r\n\r\n\r\n/**\r\n * Encloses a string in double quotes and escapes characters so that the\r\n * string is a valid JS string. The resulting string is safe to embed in\r\n * `<script>` tags as \"<\" is escaped.\r\n * @param {string} s The string to quote.\r\n * @return {string} A copy of `s` surrounded by double quotes.\r\n */\r\ngoog.string.quote = function(s) {\r\n s = String(s);\r\n var sb = ['\"'];\r\n for (var i = 0; i < s.length; i++) {\r\n var ch = s.charAt(i);\r\n var cc = ch.charCodeAt(0);\r\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\r\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\r\n }\r\n sb.push('\"');\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Takes a string and returns the escaped string for that input string.\r\n * @param {string} str The string to escape.\r\n * @return {string} An escaped string representing `str`.\r\n */\r\ngoog.string.escapeString = function(str) {\r\n var sb = [];\r\n for (var i = 0; i < str.length; i++) {\r\n sb[i] = goog.string.escapeChar(str.charAt(i));\r\n }\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Takes a character and returns the escaped string for that character. For\r\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\r\n * @param {string} c The character to escape.\r\n * @return {string} An escaped string representing `c`.\r\n */\r\ngoog.string.escapeChar = function(c) {\r\n if (c in goog.string.jsEscapeCache_) {\r\n return goog.string.jsEscapeCache_[c];\r\n }\r\n\r\n if (c in goog.string.specialEscapeChars_) {\r\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\r\n }\r\n\r\n var rv = c;\r\n var cc = c.charCodeAt(0);\r\n if (cc > 31 && cc < 127) {\r\n rv = c;\r\n } else {\r\n // tab is 9 but handled above\r\n if (cc < 256) {\r\n rv = '\\\\x';\r\n if (cc < 16 || cc > 256) {\r\n rv += '0';\r\n }\r\n } else {\r\n rv = '\\\\u';\r\n if (cc < 4096) { // \\u1000\r\n rv += '0';\r\n }\r\n }\r\n rv += cc.toString(16).toUpperCase();\r\n }\r\n\r\n return goog.string.jsEscapeCache_[c] = rv;\r\n};\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n */\r\ngoog.string.contains = goog.string.internal.contains;\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring, ignoring case.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n */\r\ngoog.string.caseInsensitiveContains =\r\n goog.string.internal.caseInsensitiveContains;\r\n\r\n\r\n/**\r\n * Returns the non-overlapping occurrences of ss in s.\r\n * If either s or ss evalutes to false, then returns zero.\r\n * @param {string} s The string to look in.\r\n * @param {string} ss The string to look for.\r\n * @return {number} Number of occurrences of ss in s.\r\n */\r\ngoog.string.countOf = function(s, ss) {\r\n return s && ss ? s.split(ss).length - 1 : 0;\r\n};\r\n\r\n\r\n/**\r\n * Removes a substring of a specified length at a specific\r\n * index in a string.\r\n * @param {string} s The base string from which to remove.\r\n * @param {number} index The index at which to remove the substring.\r\n * @param {number} stringLength The length of the substring to remove.\r\n * @return {string} A copy of `s` with the substring removed or the full\r\n * string if nothing is removed or the input is invalid.\r\n */\r\ngoog.string.removeAt = function(s, index, stringLength) {\r\n var resultStr = s;\r\n // If the index is greater or equal to 0 then remove substring\r\n if (index >= 0 && index < s.length && stringLength > 0) {\r\n resultStr = s.substr(0, index) +\r\n s.substr(index + stringLength, s.length - index - stringLength);\r\n }\r\n return resultStr;\r\n};\r\n\r\n\r\n/**\r\n * Removes the first occurrence of a substring from a string.\r\n * @param {string} str The base string from which to remove.\r\n * @param {string} substr The string to remove.\r\n * @return {string} A copy of `str` with `substr` removed or the\r\n * full string if nothing is removed.\r\n */\r\ngoog.string.remove = function(str, substr) {\r\n return str.replace(substr, '');\r\n};\r\n\r\n\r\n/**\r\n * Removes all occurrences of a substring from a string.\r\n * @param {string} s The base string from which to remove.\r\n * @param {string} ss The string to remove.\r\n * @return {string} A copy of `s` with `ss` removed or the full\r\n * string if nothing is removed.\r\n */\r\ngoog.string.removeAll = function(s, ss) {\r\n var re = new RegExp(goog.string.regExpEscape(ss), 'g');\r\n return s.replace(re, '');\r\n};\r\n\r\n\r\n/**\r\n * Replaces all occurrences of a substring of a string with a new substring.\r\n * @param {string} s The base string from which to remove.\r\n * @param {string} ss The string to replace.\r\n * @param {string} replacement The replacement string.\r\n * @return {string} A copy of `s` with `ss` replaced by\r\n * `replacement` or the original string if nothing is replaced.\r\n */\r\ngoog.string.replaceAll = function(s, ss, replacement) {\r\n var re = new RegExp(goog.string.regExpEscape(ss), 'g');\r\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\r\n};\r\n\r\n\r\n/**\r\n * Escapes characters in the string that are not safe to use in a RegExp.\r\n * @param {*} s The string to escape. If not a string, it will be casted\r\n * to one.\r\n * @return {string} A RegExp safe, escaped copy of `s`.\r\n */\r\ngoog.string.regExpEscape = function(s) {\r\n return String(s)\r\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\r\n .replace(/\\x08/g, '\\\\x08');\r\n};\r\n\r\n\r\n/**\r\n * Repeats a string n times.\r\n * @param {string} string The string to repeat.\r\n * @param {number} length The number of times to repeat.\r\n * @return {string} A string containing `length` repetitions of\r\n * `string`.\r\n */\r\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\r\n // The native method is over 100 times faster than the alternative.\r\n return string.repeat(length);\r\n} : function(string, length) {\r\n return new Array(length + 1).join(string);\r\n};\r\n\r\n\r\n/**\r\n * Pads number to given length and optionally rounds it to a given precision.\r\n * For example:\r\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\r\n * padNumber(1.25, 2) -> '01.25'\r\n * padNumber(1.25, 2, 1) -> '01.3'\r\n * padNumber(1.25, 0) -> '1.25'</pre>\r\n *\r\n * @param {number} num The number to pad.\r\n * @param {number} length The desired length.\r\n * @param {number=} opt_precision The desired precision.\r\n * @return {string} `num` as a string with the given options.\r\n */\r\ngoog.string.padNumber = function(num, length, opt_precision) {\r\n var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num);\r\n var index = s.indexOf('.');\r\n if (index == -1) {\r\n index = s.length;\r\n }\r\n return goog.string.repeat('0', Math.max(0, length - index)) + s;\r\n};\r\n\r\n\r\n/**\r\n * Returns a string representation of the given object, with\r\n * null and undefined being returned as the empty string.\r\n *\r\n * @param {*} obj The object to convert.\r\n * @return {string} A string representation of the `obj`.\r\n */\r\ngoog.string.makeSafe = function(obj) {\r\n return obj == null ? '' : String(obj);\r\n};\r\n\r\n\r\n/**\r\n * Concatenates string expressions. This is useful\r\n * since some browsers are very inefficient when it comes to using plus to\r\n * concat strings. Be careful when using null and undefined here since\r\n * these will not be included in the result. If you need to represent these\r\n * be sure to cast the argument to a String first.\r\n * For example:\r\n * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd'\r\n * buildString(null, undefined) -> ''\r\n * </pre>\r\n * @param {...*} var_args A list of strings to concatenate. If not a string,\r\n * it will be casted to one.\r\n * @return {string} The concatenation of `var_args`.\r\n */\r\ngoog.string.buildString = function(var_args) {\r\n return Array.prototype.join.call(arguments, '');\r\n};\r\n\r\n\r\n/**\r\n * Returns a string with at least 64-bits of randomness.\r\n *\r\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\r\n * random and current timestamp, and then encodes the string in base-36 to\r\n * make it shorter.\r\n *\r\n * @return {string} A random string, e.g. sn1s7vb4gcic.\r\n */\r\ngoog.string.getRandomString = function() {\r\n var x = 2147483648;\r\n return Math.floor(Math.random() * x).toString(36) +\r\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\r\n};\r\n\r\n\r\n/**\r\n * Compares two version numbers.\r\n *\r\n * @param {string|number} version1 Version of first item.\r\n * @param {string|number} version2 Version of second item.\r\n *\r\n * @return {number} 1 if `version1` is higher.\r\n * 0 if arguments are equal.\r\n * -1 if `version2` is higher.\r\n */\r\ngoog.string.compareVersions = goog.string.internal.compareVersions;\r\n\r\n\r\n/**\r\n * String hash function similar to java.lang.String.hashCode().\r\n * The hash code for a string is computed as\r\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\r\n * where s[i] is the ith character of the string and n is the length of\r\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\r\n * (exclusive).\r\n * @param {string} str A string.\r\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\r\n * (exclusive). The empty string returns 0.\r\n */\r\ngoog.string.hashCode = function(str) {\r\n var result = 0;\r\n for (var i = 0; i < str.length; ++i) {\r\n // Normalize to 4 byte range, 0 ... 2^32.\r\n result = (31 * result + str.charCodeAt(i)) >>> 0;\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\r\n\r\n\r\n/**\r\n * Generates and returns a string which is unique in the current document.\r\n * This is useful, for example, to create unique IDs for DOM elements.\r\n * @return {string} A unique id.\r\n */\r\ngoog.string.createUniqueString = function() {\r\n return 'goog_' + goog.string.uniqueStringCounter_++;\r\n};\r\n\r\n\r\n/**\r\n * Converts the supplied string to a number, which may be Infinity or NaN.\r\n * This function strips whitespace: (toNumber(' 123') === 123)\r\n * This function accepts scientific notation: (toNumber('1e1') === 10)\r\n *\r\n * This is better than JavaScript's built-in conversions because, sadly:\r\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\r\n *\r\n * @param {string} str The string to convert.\r\n * @return {number} The number the supplied string represents, or NaN.\r\n */\r\ngoog.string.toNumber = function(str) {\r\n var num = Number(str);\r\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\r\n return NaN;\r\n }\r\n return num;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\r\n *\r\n * Note that this assumes the string is entirely letters.\r\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\r\n *\r\n * @param {string} str String to test.\r\n * @return {boolean} Whether the string is lower camel case.\r\n */\r\ngoog.string.isLowerCamelCase = function(str) {\r\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\r\n *\r\n * Note that this assumes the string is entirely letters.\r\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\r\n *\r\n * @param {string} str String to test.\r\n * @return {boolean} Whether the string is upper camel case.\r\n */\r\ngoog.string.isUpperCamelCase = function(str) {\r\n return /^([A-Z][a-z]*)+$/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Converts a string from selector-case to camelCase (e.g. from\r\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\r\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\r\n * @param {string} str The string in selector-case form.\r\n * @return {string} The string in camelCase form.\r\n */\r\ngoog.string.toCamelCase = function(str) {\r\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\r\n return match.toUpperCase();\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Converts a string from camelCase to selector-case (e.g. from\r\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\r\n * style and dataset properties to equivalent CSS selectors and HTML keys.\r\n * @param {string} str The string in camelCase form.\r\n * @return {string} The string in selector-case form.\r\n */\r\ngoog.string.toSelectorCase = function(str) {\r\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\r\n};\r\n\r\n\r\n/**\r\n * Converts a string into TitleCase. First character of the string is always\r\n * capitalized in addition to the first letter of every subsequent word.\r\n * Words are delimited by one or more whitespaces by default. Custom delimiters\r\n * can optionally be specified to replace the default, which doesn't preserve\r\n * whitespace delimiters and instead must be explicitly included if needed.\r\n *\r\n * Default delimiter => \" \":\r\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\r\n * goog.string.toTitleCase('one two three') => 'One Two Three'\r\n * goog.string.toTitleCase(' one two ') => ' One Two '\r\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\r\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\r\n *\r\n * Custom delimiter => \"_-.\":\r\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\r\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\r\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\r\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\r\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\r\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\r\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\r\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\r\n *\r\n * @param {string} str String value in camelCase form.\r\n * @param {string=} opt_delimiters Custom delimiter character set used to\r\n * distinguish words in the string value. Each character represents a\r\n * single delimiter. When provided, default whitespace delimiter is\r\n * overridden and must be explicitly included if needed.\r\n * @return {string} String value in TitleCase form.\r\n */\r\ngoog.string.toTitleCase = function(str, opt_delimiters) {\r\n var delimiters = goog.isString(opt_delimiters) ?\r\n goog.string.regExpEscape(opt_delimiters) :\r\n '\\\\s';\r\n\r\n // For IE8, we need to prevent using an empty character set. Otherwise,\r\n // incorrect matching will occur.\r\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\r\n\r\n var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\r\n return str.replace(regexp, function(all, p1, p2) {\r\n return p1 + p2.toUpperCase();\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Capitalizes a string, i.e. converts the first letter to uppercase\r\n * and all other letters to lowercase, e.g.:\r\n *\r\n * goog.string.capitalize('one') => 'One'\r\n * goog.string.capitalize('ONE') => 'One'\r\n * goog.string.capitalize('one two') => 'One two'\r\n *\r\n * Note that this function does not trim initial whitespace.\r\n *\r\n * @param {string} str String value to capitalize.\r\n * @return {string} String value with first letter in uppercase.\r\n */\r\ngoog.string.capitalize = function(str) {\r\n return String(str.charAt(0)).toUpperCase() +\r\n String(str.substr(1)).toLowerCase();\r\n};\r\n\r\n\r\n/**\r\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\r\n *\r\n * To parse a particular radix, please use parseInt(string, radix) directly. See\r\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\r\n *\r\n * This is a wrapper for the built-in parseInt function that will only parse\r\n * numbers as base 10 or base 16. Some JS implementations assume strings\r\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\r\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\r\n *\r\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\r\n *\r\n * @param {string|number|null|undefined} value The value to be parsed.\r\n * @return {number} The number, parsed. If the string failed to parse, this\r\n * will be NaN.\r\n */\r\ngoog.string.parseInt = function(value) {\r\n // Force finite numbers to strings.\r\n if (isFinite(value)) {\r\n value = String(value);\r\n }\r\n\r\n if (goog.isString(value)) {\r\n // If the string starts with '0x' or '-0x', parse as hex.\r\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\r\n }\r\n\r\n return NaN;\r\n};\r\n\r\n\r\n/**\r\n * Splits a string on a separator a limited number of times.\r\n *\r\n * This implementation is more similar to Python or Java, where the limit\r\n * parameter specifies the maximum number of splits rather than truncating\r\n * the number of results.\r\n *\r\n * See http://docs.python.org/2/library/stdtypes.html#str.split\r\n * See JavaDoc: http://goo.gl/F2AsY\r\n * See Mozilla reference: http://goo.gl/dZdZs\r\n *\r\n * @param {string} str String to split.\r\n * @param {string} separator The separator.\r\n * @param {number} limit The limit to the number of splits. The resulting array\r\n * will have a maximum length of limit+1. Negative numbers are the same\r\n * as zero.\r\n * @return {!Array<string>} The string, split.\r\n */\r\ngoog.string.splitLimit = function(str, separator, limit) {\r\n var parts = str.split(separator);\r\n var returnVal = [];\r\n\r\n // Only continue doing this while we haven't hit the limit and we have\r\n // parts left.\r\n while (limit > 0 && parts.length) {\r\n returnVal.push(parts.shift());\r\n limit--;\r\n }\r\n\r\n // If there are remaining parts, append them to the end.\r\n if (parts.length) {\r\n returnVal.push(parts.join(separator));\r\n }\r\n\r\n return returnVal;\r\n};\r\n\r\n\r\n/**\r\n * Finds the characters to the right of the last instance of any separator\r\n *\r\n * This function is similar to goog.string.path.baseName, except it can take a\r\n * list of characters to split the string on. It will return the rightmost\r\n * grouping of characters to the right of any separator as a left-to-right\r\n * oriented string.\r\n *\r\n * @see goog.string.path.baseName\r\n * @param {string} str The string\r\n * @param {string|!Array<string>} separators A list of separator characters\r\n * @return {string} The last part of the string with respect to the separators\r\n */\r\ngoog.string.lastComponent = function(str, separators) {\r\n if (!separators) {\r\n return str;\r\n } else if (typeof separators == 'string') {\r\n separators = [separators];\r\n }\r\n\r\n var lastSeparatorIndex = -1;\r\n for (var i = 0; i < separators.length; i++) {\r\n if (separators[i] == '') {\r\n continue;\r\n }\r\n var currentSeparatorIndex = str.lastIndexOf(separators[i]);\r\n if (currentSeparatorIndex > lastSeparatorIndex) {\r\n lastSeparatorIndex = currentSeparatorIndex;\r\n }\r\n }\r\n if (lastSeparatorIndex == -1) {\r\n return str;\r\n }\r\n return str.slice(lastSeparatorIndex + 1);\r\n};\r\n\r\n\r\n/**\r\n * Computes the Levenshtein edit distance between two strings.\r\n * @param {string} a\r\n * @param {string} b\r\n * @return {number} The edit distance between the two strings.\r\n */\r\ngoog.string.editDistance = function(a, b) {\r\n var v0 = [];\r\n var v1 = [];\r\n\r\n if (a == b) {\r\n return 0;\r\n }\r\n\r\n if (!a.length || !b.length) {\r\n return Math.max(a.length, b.length);\r\n }\r\n\r\n for (var i = 0; i < b.length + 1; i++) {\r\n v0[i] = i;\r\n }\r\n\r\n for (var i = 0; i < a.length; i++) {\r\n v1[0] = i + 1;\r\n\r\n for (var j = 0; j < b.length; j++) {\r\n var cost = Number(a[i] != b[j]);\r\n // Cost for the substring is the minimum of adding one character, removing\r\n // one character, or a swap.\r\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\r\n }\r\n\r\n for (var j = 0; j < v0.length; j++) {\r\n v0[j] = v1[j];\r\n }\r\n }\r\n\r\n return v1[b.length];\r\n};\r\n","// Copyright 2008 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Simple utilities for dealing with URI strings.\r\n *\r\n * This is intended to be a lightweight alternative to constructing goog.Uri\r\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\r\n * of how much of its functionality you use, this is designed to be a set of\r\n * mostly-independent utilities so that the compiler includes only what is\r\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\r\n * 1.5k post-gzip. To ensure the savings remain, future developers should\r\n * avoid adding new functionality to existing functions, but instead create\r\n * new ones and factor out shared code.\r\n *\r\n * Many of these utilities have limited functionality, tailored to common\r\n * cases. The query parameter utilities assume that the parameter keys are\r\n * already encoded, since most keys are compile-time alphanumeric strings. The\r\n * query parameter mutation utilities also do not tolerate fragment identifiers.\r\n *\r\n * By design, these functions can be slower than goog.Uri equivalents.\r\n * Repeated calls to some of functions may be quadratic in behavior for IE,\r\n * although the effect is somewhat limited given the 2kb limit.\r\n *\r\n * One advantage of the limited functionality here is that this approach is\r\n * less sensitive to differences in URI encodings than goog.Uri, since these\r\n * functions operate on strings directly, rather than decoding them and\r\n * then re-encoding.\r\n *\r\n * Uses features of RFC 3986 for parsing/formatting URIs:\r\n * http://www.ietf.org/rfc/rfc3986.txt\r\n *\r\n * @author gboyer@google.com (Garrett Boyer) - The \"lightened\" design.\r\n * @author msamuel@google.com (Mike Samuel) - Domain knowledge and regexes.\r\n */\r\n\r\ngoog.provide('goog.uri.utils');\r\ngoog.provide('goog.uri.utils.ComponentIndex');\r\ngoog.provide('goog.uri.utils.QueryArray');\r\ngoog.provide('goog.uri.utils.QueryValue');\r\ngoog.provide('goog.uri.utils.StandardQueryParam');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * Character codes inlined to avoid object allocations due to charCode.\r\n * @enum {number}\r\n * @private\r\n */\r\ngoog.uri.utils.CharCode_ = {\r\n AMPERSAND: 38,\r\n EQUAL: 61,\r\n HASH: 35,\r\n QUESTION: 63\r\n};\r\n\r\n\r\n/**\r\n * Builds a URI string from already-encoded parts.\r\n *\r\n * No encoding is performed. Any component may be omitted as either null or\r\n * undefined.\r\n *\r\n * @param {?string=} opt_scheme The scheme such as 'http'.\r\n * @param {?string=} opt_userInfo The user name before the '@'.\r\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\r\n * URI-encoded.\r\n * @param {(string|number|null)=} opt_port The port number.\r\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\r\n * empty, it must begin with a slash.\r\n * @param {?string=} opt_queryData The URI-encoded query data.\r\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\r\n * @return {string} The fully combined URI.\r\n */\r\ngoog.uri.utils.buildFromEncodedParts = function(\r\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\r\n opt_fragment) {\r\n var out = '';\r\n\r\n if (opt_scheme) {\r\n out += opt_scheme + ':';\r\n }\r\n\r\n if (opt_domain) {\r\n out += '//';\r\n\r\n if (opt_userInfo) {\r\n out += opt_userInfo + '@';\r\n }\r\n\r\n out += opt_domain;\r\n\r\n if (opt_port) {\r\n out += ':' + opt_port;\r\n }\r\n }\r\n\r\n if (opt_path) {\r\n out += opt_path;\r\n }\r\n\r\n if (opt_queryData) {\r\n out += '?' + opt_queryData;\r\n }\r\n\r\n if (opt_fragment) {\r\n out += '#' + opt_fragment;\r\n }\r\n\r\n return out;\r\n};\r\n\r\n\r\n/**\r\n * A regular expression for breaking a URI into its component parts.\r\n *\r\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\r\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\r\n * disambiguation method used by POSIX regular expressions, it is natural and\r\n * commonplace to use a regular expression for parsing the potential five\r\n * components of a URI reference.\r\n *\r\n * The following line is the regular expression for breaking-down a\r\n * well-formed URI reference into its components.\r\n *\r\n * <pre>\r\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\r\n * 12 3 4 5 6 7 8 9\r\n * </pre>\r\n *\r\n * The numbers in the second line above are only to assist readability; they\r\n * indicate the reference points for each subexpression (i.e., each paired\r\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\r\n * For example, matching the above expression to\r\n * <pre>\r\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\r\n * </pre>\r\n * results in the following subexpression matches:\r\n * <pre>\r\n * $1 = http:\r\n * $2 = http\r\n * $3 = //www.ics.uci.edu\r\n * $4 = www.ics.uci.edu\r\n * $5 = /pub/ietf/uri/\r\n * $6 = <undefined>\r\n * $7 = <undefined>\r\n * $8 = #Related\r\n * $9 = Related\r\n * </pre>\r\n * where <undefined> indicates that the component is not present, as is the\r\n * case for the query component in the above example. Therefore, we can\r\n * determine the value of the five components as\r\n * <pre>\r\n * scheme = $2\r\n * authority = $4\r\n * path = $5\r\n * query = $7\r\n * fragment = $9\r\n * </pre>\r\n *\r\n * The regular expression has been modified slightly to expose the\r\n * userInfo, domain, and port separately from the authority.\r\n * The modified version yields\r\n * <pre>\r\n * $1 = http scheme\r\n * $2 = <undefined> userInfo -\\\r\n * $3 = www.ics.uci.edu domain | authority\r\n * $4 = <undefined> port -/\r\n * $5 = /pub/ietf/uri/ path\r\n * $6 = <undefined> query without ?\r\n * $7 = Related fragment without #\r\n * </pre>\r\n * @type {!RegExp}\r\n * @private\r\n */\r\ngoog.uri.utils.splitRe_ = new RegExp(\r\n '^' +\r\n '(?:' +\r\n '([^:/?#.]+)' + // scheme - ignore special characters\r\n // used by other URL parts such as :,\r\n // ?, /, #, and .\r\n ':)?' +\r\n '(?://' +\r\n '(?:([^/?#]*)@)?' + // userInfo\r\n '([^/#?]*?)' + // domain\r\n '(?::([0-9]+))?' + // port\r\n '(?=[/#?]|$)' + // authority-terminating character\r\n ')?' +\r\n '([^?#]+)?' + // path\r\n '(?:\\\\?([^#]*))?' + // query\r\n '(?:#([\\\\s\\\\S]*))?' + // fragment\r\n '$');\r\n\r\n\r\n/**\r\n * The index of each URI component in the return value of goog.uri.utils.split.\r\n * @enum {number}\r\n */\r\ngoog.uri.utils.ComponentIndex = {\r\n SCHEME: 1,\r\n USER_INFO: 2,\r\n DOMAIN: 3,\r\n PORT: 4,\r\n PATH: 5,\r\n QUERY_DATA: 6,\r\n FRAGMENT: 7\r\n};\r\n\r\n\r\n/**\r\n * Splits a URI into its component parts.\r\n *\r\n * Each component can be accessed via the component indices; for example:\r\n * <pre>\r\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\r\n * </pre>\r\n *\r\n * @param {string} uri The URI string to examine.\r\n * @return {!Array<string|undefined>} Each component still URI-encoded.\r\n * Each component that is present will contain the encoded value, whereas\r\n * components that are not present will be undefined or empty, depending\r\n * on the browser's regular expression implementation. Never null, since\r\n * arbitrary strings may still look like path names.\r\n */\r\ngoog.uri.utils.split = function(uri) {\r\n // See @return comment -- never null.\r\n return /** @type {!Array<string|undefined>} */ (\r\n uri.match(goog.uri.utils.splitRe_));\r\n};\r\n\r\n\r\n/**\r\n * @param {?string} uri A possibly null string.\r\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\r\n * reserved characters will not be removed.\r\n * @return {?string} The string URI-decoded, or null if uri is null.\r\n * @private\r\n */\r\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\r\n if (!uri) {\r\n return uri;\r\n }\r\n\r\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\r\n};\r\n\r\n\r\n/**\r\n * Gets a URI component by index.\r\n *\r\n * It is preferred to use the getPathEncoded() variety of functions ahead,\r\n * since they are more readable.\r\n *\r\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The still-encoded component, or null if the component\r\n * is not present.\r\n * @private\r\n */\r\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\r\n // Convert undefined, null, and empty string into null.\r\n return goog.uri.utils.split(uri)[componentIndex] || null;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The protocol or scheme, or null if none. Does not\r\n * include trailing colons or slashes.\r\n */\r\ngoog.uri.utils.getScheme = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.SCHEME, uri);\r\n};\r\n\r\n\r\n/**\r\n * Gets the effective scheme for the URL. If the URL is relative then the\r\n * scheme is derived from the page's location.\r\n * @param {string} uri The URI to examine.\r\n * @return {string} The protocol or scheme, always lower case.\r\n */\r\ngoog.uri.utils.getEffectiveScheme = function(uri) {\r\n var scheme = goog.uri.utils.getScheme(uri);\r\n if (!scheme && goog.global.self && goog.global.self.location) {\r\n var protocol = goog.global.self.location.protocol;\r\n scheme = protocol.substr(0, protocol.length - 1);\r\n }\r\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\r\n // All other browsers with web workers support self.location from the worker.\r\n return scheme ? scheme.toLowerCase() : '';\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The user name still encoded, or null if none.\r\n */\r\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded user info, or null if none.\r\n */\r\ngoog.uri.utils.getUserInfo = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getUserInfoEncoded(uri));\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The domain name still encoded, or null if none.\r\n */\r\ngoog.uri.utils.getDomainEncoded = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded domain, or null if none.\r\n */\r\ngoog.uri.utils.getDomain = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?number} The port number, or null if none.\r\n */\r\ngoog.uri.utils.getPort = function(uri) {\r\n // Coerce to a number. If the result of getComponentByIndex_ is null or\r\n // non-numeric, the number coersion yields NaN. This will then return\r\n // null for all non-numeric cases (though also zero, which isn't a relevant\r\n // port number).\r\n return Number(\r\n goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\r\n null;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The path still encoded, or null if none. Includes the\r\n * leading slash, if any.\r\n */\r\ngoog.uri.utils.getPathEncoded = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.PATH, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded path, or null if none. Includes the leading\r\n * slash, if any.\r\n */\r\ngoog.uri.utils.getPath = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The query data still encoded, or null if none. Does not\r\n * include the question mark itself.\r\n */\r\ngoog.uri.utils.getQueryData = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The fragment identifier, or null if none. Does not\r\n * include the hash mark itself.\r\n */\r\ngoog.uri.utils.getFragmentEncoded = function(uri) {\r\n // The hash mark may not appear in any other part of the URL.\r\n var hashIndex = uri.indexOf('#');\r\n return hashIndex < 0 ? null : uri.substr(hashIndex + 1);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @param {?string} fragment The encoded fragment identifier, or null if none.\r\n * Does not include the hash mark itself.\r\n * @return {string} The URI with the fragment set.\r\n */\r\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\r\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded fragment identifier, or null if none. Does\r\n * not include the hash mark.\r\n */\r\ngoog.uri.utils.getFragment = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getFragmentEncoded(uri));\r\n};\r\n\r\n\r\n/**\r\n * Extracts everything up to the port of the URI.\r\n * @param {string} uri The URI string.\r\n * @return {string} Everything up to and including the port.\r\n */\r\ngoog.uri.utils.getHost = function(uri) {\r\n var pieces = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\r\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\r\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\r\n pieces[goog.uri.utils.ComponentIndex.PORT]);\r\n};\r\n\r\n\r\n/**\r\n * Returns the origin for a given URL.\r\n * @param {string} uri The URI string.\r\n * @return {string} Everything up to and including the port.\r\n */\r\ngoog.uri.utils.getOrigin = function(uri) {\r\n var pieces = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\r\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\r\n pieces[goog.uri.utils.ComponentIndex.PORT]);\r\n};\r\n\r\n\r\n/**\r\n * Extracts the path of the URL and everything after.\r\n * @param {string} uri The URI string.\r\n * @return {string} The URI, starting at the path and including the query\r\n * parameters and fragment identifier.\r\n */\r\ngoog.uri.utils.getPathAndAfter = function(uri) {\r\n var pieces = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\r\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\r\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\r\n};\r\n\r\n\r\n/**\r\n * Gets the URI with the fragment identifier removed.\r\n * @param {string} uri The URI to examine.\r\n * @return {string} Everything preceding the hash mark.\r\n */\r\ngoog.uri.utils.removeFragment = function(uri) {\r\n // The hash mark may not appear in any other part of the URL.\r\n var hashIndex = uri.indexOf('#');\r\n return hashIndex < 0 ? uri : uri.substr(0, hashIndex);\r\n};\r\n\r\n\r\n/**\r\n * Ensures that two URI's have the exact same domain, scheme, and port.\r\n *\r\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\r\n * suitable for checking against the browser's same-origin policy.\r\n *\r\n * @param {string} uri1 The first URI.\r\n * @param {string} uri2 The second URI.\r\n * @return {boolean} Whether they have the same scheme, domain and port.\r\n */\r\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\r\n var pieces1 = goog.uri.utils.split(uri1);\r\n var pieces2 = goog.uri.utils.split(uri2);\r\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\r\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\r\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\r\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\r\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\r\n pieces2[goog.uri.utils.ComponentIndex.PORT];\r\n};\r\n\r\n\r\n/**\r\n * Asserts that there are no fragment or query identifiers, only in uncompiled\r\n * mode.\r\n * @param {string} uri The URI to examine.\r\n * @private\r\n */\r\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\r\n goog.asserts.assert(\r\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\r\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\r\n uri);\r\n};\r\n\r\n\r\n/**\r\n * Supported query parameter values by the parameter serializing utilities.\r\n *\r\n * If a value is null or undefined, the key-value pair is skipped, as an easy\r\n * way to omit parameters conditionally. Non-array parameters are converted\r\n * to a string and URI encoded. Array values are expanded into multiple\r\n * &key=value pairs, with each element stringized and URI-encoded.\r\n *\r\n * @typedef {*}\r\n */\r\ngoog.uri.utils.QueryValue;\r\n\r\n\r\n/**\r\n * An array representing a set of query parameters with alternating keys\r\n * and values.\r\n *\r\n * Keys are assumed to be URI encoded already and live at even indices. See\r\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\r\n *\r\n * Example:\r\n * <pre>\r\n * var data = [\r\n * // Simple param: ?name=BobBarker\r\n * 'name', 'BobBarker',\r\n * // Conditional param -- may be omitted entirely.\r\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\r\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\r\n * 'house', ['LosAngeles', 'NewYork', null]\r\n * ];\r\n * </pre>\r\n *\r\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\r\n */\r\ngoog.uri.utils.QueryArray;\r\n\r\n\r\n/**\r\n * Parses encoded query parameters and calls callback function for every\r\n * parameter found in the string.\r\n *\r\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\r\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\r\n * that “…&=&…” and “…&&…” will result in an empty key and value.\r\n *\r\n * @param {string} encodedQuery Encoded query string excluding question mark at\r\n * the beginning.\r\n * @param {function(string, string)} callback Function called for every\r\n * parameter found in query string. The first argument (name) will not be\r\n * urldecoded (so the function is consistent with buildQueryData), but the\r\n * second will. If the parameter has no value (i.e. “=” was not present)\r\n * the second argument (value) will be an empty string.\r\n */\r\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\r\n if (!encodedQuery) {\r\n return;\r\n }\r\n var pairs = encodedQuery.split('&');\r\n for (var i = 0; i < pairs.length; i++) {\r\n var indexOfEquals = pairs[i].indexOf('=');\r\n var name = null;\r\n var value = null;\r\n if (indexOfEquals >= 0) {\r\n name = pairs[i].substring(0, indexOfEquals);\r\n value = pairs[i].substring(indexOfEquals + 1);\r\n } else {\r\n name = pairs[i];\r\n }\r\n callback(name, value ? goog.string.urlDecode(value) : '');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Split the URI into 3 parts where the [1] is the queryData without a leading\r\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\r\n * ['http://foo.com/bar','a=b','#abc'].\r\n * @param {string} uri The URI to parse.\r\n * @return {!Array<string>} An array representation of uri of length 3 where the\r\n * middle value is the queryData without a leading '?'.\r\n * @private\r\n */\r\ngoog.uri.utils.splitQueryData_ = function(uri) {\r\n // Find the query data and hash.\r\n var hashIndex = uri.indexOf('#');\r\n if (hashIndex < 0) {\r\n hashIndex = uri.length;\r\n }\r\n var questionIndex = uri.indexOf('?');\r\n var queryData;\r\n if (questionIndex < 0 || questionIndex > hashIndex) {\r\n questionIndex = hashIndex;\r\n queryData = '';\r\n } else {\r\n queryData = uri.substring(questionIndex + 1, hashIndex);\r\n }\r\n return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];\r\n};\r\n\r\n\r\n/**\r\n * Join an array created by splitQueryData_ back into a URI.\r\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\r\n * @return {string} The joined URI.\r\n * @private\r\n */\r\ngoog.uri.utils.joinQueryData_ = function(parts) {\r\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\r\n};\r\n\r\n\r\n/**\r\n * @param {string} queryData\r\n * @param {string} newData\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\r\n if (!newData) {\r\n return queryData;\r\n }\r\n return queryData ? queryData + '&' + newData : newData;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri\r\n * @param {string} queryData\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\r\n if (!queryData) {\r\n return uri;\r\n }\r\n var parts = goog.uri.utils.splitQueryData_(uri);\r\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\r\n return goog.uri.utils.joinQueryData_(parts);\r\n};\r\n\r\n\r\n/**\r\n * Appends key=value pairs to an array, supporting multi-valued objects.\r\n * @param {*} key The key prefix.\r\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\r\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\r\n * should be appended.\r\n * @private\r\n */\r\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\r\n goog.asserts.assertString(key);\r\n if (goog.isArray(value)) {\r\n // Convince the compiler it's an array.\r\n goog.asserts.assertArray(value);\r\n for (var j = 0; j < value.length; j++) {\r\n // Convert to string explicitly, to short circuit the null and array\r\n // logic in this function -- this ensures that null and undefined get\r\n // written as literal 'null' and 'undefined', and arrays don't get\r\n // expanded out but instead encoded in the default way.\r\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\r\n }\r\n } else if (value != null) {\r\n // Skip a top-level null or undefined entirely.\r\n pairs.push(\r\n key +\r\n // Check for empty string. Zero gets encoded into the url as literal\r\n // strings. For empty string, skip the equal sign, to be consistent\r\n // with UriBuilder.java.\r\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Builds a query data string from a sequence of alternating keys and values.\r\n * Currently generates \"&key&\" for empty args.\r\n *\r\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\r\n * Alternating keys and values. See the QueryArray typedef.\r\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\r\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\r\n */\r\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\r\n goog.asserts.assert(\r\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\r\n 'goog.uri.utils: Key/value lists must be even in length.');\r\n\r\n var params = [];\r\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\r\n var key = /** @type {string} */ (keysAndValues[i]);\r\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\r\n }\r\n return params.join('&');\r\n};\r\n\r\n\r\n/**\r\n * Builds a query data string from a map.\r\n * Currently generates \"&key&\" for empty args.\r\n *\r\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\r\n * are URI-encoded parameter keys, and the values are arbitrary types\r\n * or arrays. Keys with a null value are dropped.\r\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\r\n */\r\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\r\n var params = [];\r\n for (var key in map) {\r\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\r\n }\r\n return params.join('&');\r\n};\r\n\r\n\r\n/**\r\n * Appends URI parameters to an existing URI.\r\n *\r\n * The variable arguments may contain alternating keys and values. Keys are\r\n * assumed to be already URI encoded. The values should not be URI-encoded,\r\n * and will instead be encoded by this function.\r\n * <pre>\r\n * appendParams('http://www.foo.com?existing=true',\r\n * 'key1', 'value1',\r\n * 'key2', 'value?willBeEncoded',\r\n * 'key3', ['valueA', 'valueB', 'valueC'],\r\n * 'key4', null);\r\n * result: 'http://www.foo.com?existing=true&' +\r\n * 'key1=value1&' +\r\n * 'key2=value%3FwillBeEncoded&' +\r\n * 'key3=valueA&key3=valueB&key3=valueC'\r\n * </pre>\r\n *\r\n * A single call to this function will not exhibit quadratic behavior in IE,\r\n * whereas multiple repeated calls may, although the effect is limited by\r\n * fact that URL's generally can't exceed 2kb.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\r\n * var_args\r\n * An array or argument list conforming to goog.uri.utils.QueryArray.\r\n * @return {string} The URI with all query parameters added.\r\n */\r\ngoog.uri.utils.appendParams = function(uri, var_args) {\r\n var queryData = arguments.length == 2 ?\r\n goog.uri.utils.buildQueryData(arguments[1], 0) :\r\n goog.uri.utils.buildQueryData(arguments, 1);\r\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\r\n};\r\n\r\n\r\n/**\r\n * Appends query parameters from a map.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\r\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\r\n * Keys with a null value are dropped.\r\n * @return {string} The new parameters.\r\n */\r\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\r\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\r\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\r\n};\r\n\r\n\r\n/**\r\n * Appends a single URI parameter.\r\n *\r\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\r\n * way string append works, though it should be limited given the 2kb limit.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {string} key The key, which must already be URI encoded.\r\n * @param {*=} opt_value The value, which will be stringized and encoded\r\n * (assumed not already to be encoded). If omitted, undefined, or null, the\r\n * key will be added as a valueless parameter.\r\n * @return {string} The URI with the query parameter added.\r\n */\r\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\r\n var value = goog.isDefAndNotNull(opt_value) ?\r\n '=' + goog.string.urlEncode(opt_value) :\r\n '';\r\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\r\n};\r\n\r\n\r\n/**\r\n * Finds the next instance of a query parameter with the specified name.\r\n *\r\n * Does not instantiate any objects.\r\n *\r\n * @param {string} uri The URI to search. May contain a fragment identifier\r\n * if opt_hashIndex is specified.\r\n * @param {number} startIndex The index to begin searching for the key at. A\r\n * match may be found even if this is one character after the ampersand.\r\n * @param {string} keyEncoded The URI-encoded key.\r\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\r\n * mark is present, it should be its index, otherwise it should be the\r\n * length of the string.\r\n * @return {number} The position of the first character in the key's name,\r\n * immediately after either a question mark or a dot.\r\n * @private\r\n */\r\ngoog.uri.utils.findParam_ = function(\r\n uri, startIndex, keyEncoded, hashOrEndIndex) {\r\n var index = startIndex;\r\n var keyLength = keyEncoded.length;\r\n\r\n // Search for the key itself and post-filter for surronuding punctuation,\r\n // rather than expensively building a regexp.\r\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\r\n index < hashOrEndIndex) {\r\n var precedingChar = uri.charCodeAt(index - 1);\r\n // Ensure that the preceding character is '&' or '?'.\r\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\r\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\r\n // Ensure the following character is '&', '=', '#', or NaN\r\n // (end of string).\r\n var followingChar = uri.charCodeAt(index + keyLength);\r\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\r\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\r\n followingChar == goog.uri.utils.CharCode_.HASH) {\r\n return index;\r\n }\r\n }\r\n index += keyLength + 1;\r\n }\r\n\r\n return -1;\r\n};\r\n\r\n\r\n/**\r\n * Regular expression for finding a hash mark or end of string.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\r\n\r\n\r\n/**\r\n * Determines if the URI contains a specific key.\r\n *\r\n * Performs no object instantiations.\r\n *\r\n * @param {string} uri The URI to process. May contain a fragment\r\n * identifier.\r\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\r\n * @return {boolean} Whether the key is present.\r\n */\r\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\r\n return goog.uri.utils.findParam_(\r\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * Gets the first value of a query parameter.\r\n * @param {string} uri The URI to process. May contain a fragment.\r\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\r\n * @return {?string} The first value of the parameter (URI-decoded), or null\r\n * if the parameter is not found.\r\n */\r\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\r\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\r\n var foundIndex =\r\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\r\n\r\n if (foundIndex < 0) {\r\n return null;\r\n } else {\r\n var endPosition = uri.indexOf('&', foundIndex);\r\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\r\n endPosition = hashOrEndIndex;\r\n }\r\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\r\n foundIndex += keyEncoded.length + 1;\r\n // Use substr, because it (unlike substring) will return empty string\r\n // if foundIndex > endPosition.\r\n return goog.string.urlDecode(\r\n uri.substr(foundIndex, endPosition - foundIndex));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Gets all values of a query parameter.\r\n * @param {string} uri The URI to process. May contain a fragment.\r\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\r\n * @return {!Array<string>} All URI-decoded values with the given key.\r\n * If the key is not found, this will have length 0, but never be null.\r\n */\r\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\r\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\r\n var position = 0;\r\n var foundIndex;\r\n var result = [];\r\n\r\n while ((foundIndex = goog.uri.utils.findParam_(\r\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\r\n // Find where this parameter ends, either the '&' or the end of the\r\n // query parameters.\r\n position = uri.indexOf('&', foundIndex);\r\n if (position < 0 || position > hashOrEndIndex) {\r\n position = hashOrEndIndex;\r\n }\r\n\r\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\r\n foundIndex += keyEncoded.length + 1;\r\n // Use substr, because it (unlike substring) will return empty string\r\n // if foundIndex > position.\r\n result.push(\r\n goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));\r\n }\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Regexp to find trailing question marks and ampersands.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\r\n\r\n\r\n/**\r\n * Removes all instances of a query parameter.\r\n * @param {string} uri The URI to process. Must not contain a fragment.\r\n * @param {string} keyEncoded The URI-encoded key.\r\n * @return {string} The URI with all instances of the parameter removed.\r\n */\r\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\r\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\r\n var position = 0;\r\n var foundIndex;\r\n var buffer = [];\r\n\r\n // Look for a query parameter.\r\n while ((foundIndex = goog.uri.utils.findParam_(\r\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\r\n // Get the portion of the query string up to, but not including, the ?\r\n // or & starting the parameter.\r\n buffer.push(uri.substring(position, foundIndex));\r\n // Progress to immediately after the '&'. If not found, go to the end.\r\n // Avoid including the hash mark.\r\n position = Math.min(\r\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\r\n }\r\n\r\n // Append everything that is remaining.\r\n buffer.push(uri.substr(position));\r\n\r\n // Join the buffer, and remove trailing punctuation that remains.\r\n return buffer.join('').replace(\r\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\r\n};\r\n\r\n\r\n/**\r\n * Replaces all existing definitions of a parameter with a single definition.\r\n *\r\n * Repeated calls to this can exhibit quadratic behavior due to the need to\r\n * find existing instances and reconstruct the string, though it should be\r\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\r\n * to update multiple parameters in bulk.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {string} keyEncoded The key, which must already be URI encoded.\r\n * @param {*} value The value, which will be stringized and encoded (assumed\r\n * not already to be encoded).\r\n * @return {string} The URI with the query parameter added.\r\n */\r\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\r\n return goog.uri.utils.appendParam(\r\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\r\n};\r\n\r\n\r\n/**\r\n * Effeciently set or remove multiple query parameters in a URI. Order of\r\n * unchanged parameters will not be modified, all updated parameters will be\r\n * appended to the end of the query. Params with values of null or undefined are\r\n * removed.\r\n *\r\n * @param {string} uri The URI to process.\r\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\r\n * parameters to update. If null or undefined, the param will be removed.\r\n * @return {string} An updated URI where the query data has been updated with\r\n * the params.\r\n */\r\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\r\n var parts = goog.uri.utils.splitQueryData_(uri);\r\n var queryData = parts[1];\r\n var buffer = [];\r\n if (queryData) {\r\n goog.array.forEach(queryData.split('&'), function(pair) {\r\n var indexOfEquals = pair.indexOf('=');\r\n var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;\r\n if (!params.hasOwnProperty(name)) {\r\n buffer.push(pair);\r\n }\r\n });\r\n }\r\n parts[1] = goog.uri.utils.appendQueryData_(\r\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\r\n return goog.uri.utils.joinQueryData_(parts);\r\n};\r\n\r\n\r\n/**\r\n * Generates a URI path using a given URI and a path with checks to\r\n * prevent consecutive \"//\". The baseUri passed in must not contain\r\n * query or fragment identifiers. The path to append may not contain query or\r\n * fragment identifiers.\r\n *\r\n * @param {string} baseUri URI to use as the base.\r\n * @param {string} path Path to append.\r\n * @return {string} Updated URI.\r\n */\r\ngoog.uri.utils.appendPath = function(baseUri, path) {\r\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\r\n\r\n // Remove any trailing '/'\r\n if (goog.string.endsWith(baseUri, '/')) {\r\n baseUri = baseUri.substr(0, baseUri.length - 1);\r\n }\r\n // Remove any leading '/'\r\n if (goog.string.startsWith(path, '/')) {\r\n path = path.substr(1);\r\n }\r\n return goog.string.buildString(baseUri, '/', path);\r\n};\r\n\r\n\r\n/**\r\n * Replaces the path.\r\n * @param {string} uri URI to use as the base.\r\n * @param {string} path New path.\r\n * @return {string} Updated URI.\r\n */\r\ngoog.uri.utils.setPath = function(uri, path) {\r\n // Add any missing '/'.\r\n if (!goog.string.startsWith(path, '/')) {\r\n path = '/' + path;\r\n }\r\n var parts = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n parts[goog.uri.utils.ComponentIndex.SCHEME],\r\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\r\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\r\n parts[goog.uri.utils.ComponentIndex.PORT], path,\r\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\r\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\r\n};\r\n\r\n\r\n/**\r\n * Standard supported query parameters.\r\n * @enum {string}\r\n */\r\ngoog.uri.utils.StandardQueryParam = {\r\n\r\n /** Unused parameter for unique-ifying. */\r\n RANDOM: 'zx'\r\n};\r\n\r\n\r\n/**\r\n * Sets the zx parameter of a URI to a random value.\r\n * @param {string} uri Any URI.\r\n * @return {string} That URI with the \"zx\" parameter added or replaced to\r\n * contain a random string.\r\n */\r\ngoog.uri.utils.makeUnique = function(uri) {\r\n return goog.uri.utils.setParam(\r\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\r\n goog.string.getRandomString());\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Class for parsing and formatting URIs.\r\n *\r\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\r\n * create a new instance of the goog.Uri object from Uri parts.\r\n *\r\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\r\n *\r\n * Implements RFC 3986 for parsing/formatting URIs.\r\n * http://www.ietf.org/rfc/rfc3986.txt\r\n *\r\n * Some changes have been made to the interface (more like .NETs), though the\r\n * internal representation is now of un-encoded parts, this will change the\r\n * behavior slightly.\r\n *\r\n * @author msamuel@google.com (Mike Samuel)\r\n */\r\n\r\ngoog.provide('goog.Uri');\r\ngoog.provide('goog.Uri.QueryData');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.string');\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.Map');\r\ngoog.require('goog.uri.utils');\r\ngoog.require('goog.uri.utils.ComponentIndex');\r\ngoog.require('goog.uri.utils.StandardQueryParam');\r\n\r\n\r\n\r\n/**\r\n * This class contains setters and getters for the parts of the URI.\r\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\r\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\r\n * decoded path, <code>/foo bar</code>.\r\n *\r\n * Reserved characters (see RFC 3986 section 2.2) can be present in\r\n * their percent-encoded form in scheme, domain, and path URI components and\r\n * will not be auto-decoded. For example:\r\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\r\n * return <code>relative/path%2fto/resource</code>.\r\n *\r\n * The constructor accepts an optional unparsed, raw URI string. The parser\r\n * is relaxed, so special characters that aren't escaped but don't cause\r\n * ambiguities will not cause parse failures.\r\n *\r\n * All setters return <code>this</code> and so may be chained, a la\r\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\r\n *\r\n * @param {*=} opt_uri Optional string URI to parse\r\n * (use goog.Uri.create() to create a URI from parts), or if\r\n * a goog.Uri is passed, a clone is created.\r\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\r\n * the case of the parameter name.\r\n *\r\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\r\n * if decodeURIComponent fails on any of the URI components).\r\n * @constructor\r\n * @struct\r\n */\r\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\r\n /**\r\n * Scheme such as \"http\".\r\n * @private {string}\r\n */\r\n this.scheme_ = '';\r\n\r\n /**\r\n * User credentials in the form \"username:password\".\r\n * @private {string}\r\n */\r\n this.userInfo_ = '';\r\n\r\n /**\r\n * Domain part, e.g. \"www.google.com\".\r\n * @private {string}\r\n */\r\n this.domain_ = '';\r\n\r\n /**\r\n * Port, e.g. 8080.\r\n * @private {?number}\r\n */\r\n this.port_ = null;\r\n\r\n /**\r\n * Path, e.g. \"/tests/img.png\".\r\n * @private {string}\r\n */\r\n this.path_ = '';\r\n\r\n /**\r\n * The fragment without the #.\r\n * @private {string}\r\n */\r\n this.fragment_ = '';\r\n\r\n /**\r\n * Whether or not this Uri should be treated as Read Only.\r\n * @private {boolean}\r\n */\r\n this.isReadOnly_ = false;\r\n\r\n /**\r\n * Whether or not to ignore case when comparing query params.\r\n * @private {boolean}\r\n */\r\n this.ignoreCase_ = false;\r\n\r\n /**\r\n * Object representing query data.\r\n * @private {!goog.Uri.QueryData}\r\n */\r\n this.queryData_;\r\n\r\n // Parse in the uri string\r\n var m;\r\n if (opt_uri instanceof goog.Uri) {\r\n this.ignoreCase_ =\r\n goog.isDef(opt_ignoreCase) ? opt_ignoreCase : opt_uri.getIgnoreCase();\r\n this.setScheme(opt_uri.getScheme());\r\n this.setUserInfo(opt_uri.getUserInfo());\r\n this.setDomain(opt_uri.getDomain());\r\n this.setPort(opt_uri.getPort());\r\n this.setPath(opt_uri.getPath());\r\n this.setQueryData(opt_uri.getQueryData().clone());\r\n this.setFragment(opt_uri.getFragment());\r\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\r\n this.ignoreCase_ = !!opt_ignoreCase;\r\n\r\n // Set the parts -- decoding as we do so.\r\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\r\n // whereas in other browsers they will be undefined.\r\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\r\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\r\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\r\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\r\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\r\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\r\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\r\n\r\n } else {\r\n this.ignoreCase_ = !!opt_ignoreCase;\r\n this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Parameter name added to stop caching.\r\n * @type {string}\r\n */\r\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\r\n\r\n\r\n/**\r\n * @return {string} The string form of the url.\r\n * @override\r\n */\r\ngoog.Uri.prototype.toString = function() {\r\n var out = [];\r\n\r\n var scheme = this.getScheme();\r\n if (scheme) {\r\n out.push(\r\n goog.Uri.encodeSpecialChars_(\r\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\r\n ':');\r\n }\r\n\r\n var domain = this.getDomain();\r\n if (domain || scheme == 'file') {\r\n out.push('//');\r\n\r\n var userInfo = this.getUserInfo();\r\n if (userInfo) {\r\n out.push(\r\n goog.Uri.encodeSpecialChars_(\r\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\r\n '@');\r\n }\r\n\r\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\r\n\r\n var port = this.getPort();\r\n if (port != null) {\r\n out.push(':', String(port));\r\n }\r\n }\r\n\r\n var path = this.getPath();\r\n if (path) {\r\n if (this.hasDomain() && path.charAt(0) != '/') {\r\n out.push('/');\r\n }\r\n out.push(\r\n goog.Uri.encodeSpecialChars_(\r\n path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\r\n goog.Uri.reDisallowedInRelativePath_,\r\n true));\r\n }\r\n\r\n var query = this.getEncodedQuery();\r\n if (query) {\r\n out.push('?', query);\r\n }\r\n\r\n var fragment = this.getFragment();\r\n if (fragment) {\r\n out.push(\r\n '#', goog.Uri.encodeSpecialChars_(\r\n fragment, goog.Uri.reDisallowedInFragment_));\r\n }\r\n return out.join('');\r\n};\r\n\r\n\r\n/**\r\n * Resolves the given relative URI (a goog.Uri object), using the URI\r\n * represented by this instance as the base URI.\r\n *\r\n * There are several kinds of relative URIs:<br>\r\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\r\n * 2. /foo - replaces the path, the query and fragment<br>\r\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\r\n * 4. ?foo - replace the query and fragment<br>\r\n * 5. #foo - replace the fragment only\r\n *\r\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\r\n * segments will be resolved, as described in RFC 3986.\r\n *\r\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\r\n * @return {!goog.Uri} The resolved URI.\r\n */\r\ngoog.Uri.prototype.resolve = function(relativeUri) {\r\n\r\n var absoluteUri = this.clone();\r\n\r\n // we satisfy these conditions by looking for the first part of relativeUri\r\n // that is not blank and applying defaults to the rest\r\n\r\n var overridden = relativeUri.hasScheme();\r\n\r\n if (overridden) {\r\n absoluteUri.setScheme(relativeUri.getScheme());\r\n } else {\r\n overridden = relativeUri.hasUserInfo();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\r\n } else {\r\n overridden = relativeUri.hasDomain();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setDomain(relativeUri.getDomain());\r\n } else {\r\n overridden = relativeUri.hasPort();\r\n }\r\n\r\n var path = relativeUri.getPath();\r\n if (overridden) {\r\n absoluteUri.setPort(relativeUri.getPort());\r\n } else {\r\n overridden = relativeUri.hasPath();\r\n if (overridden) {\r\n // resolve path properly\r\n if (path.charAt(0) != '/') {\r\n // path is relative\r\n if (this.hasDomain() && !this.hasPath()) {\r\n // RFC 3986, section 5.2.3, case 1\r\n path = '/' + path;\r\n } else {\r\n // RFC 3986, section 5.2.3, case 2\r\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\r\n if (lastSlashIndex != -1) {\r\n path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;\r\n }\r\n }\r\n }\r\n path = goog.Uri.removeDotSegments(path);\r\n }\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setPath(path);\r\n } else {\r\n overridden = relativeUri.hasQuery();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\r\n } else {\r\n overridden = relativeUri.hasFragment();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setFragment(relativeUri.getFragment());\r\n }\r\n\r\n return absoluteUri;\r\n};\r\n\r\n\r\n/**\r\n * Clones the URI instance.\r\n * @return {!goog.Uri} New instance of the URI object.\r\n */\r\ngoog.Uri.prototype.clone = function() {\r\n return new goog.Uri(this);\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The encoded scheme/protocol for the URI.\r\n */\r\ngoog.Uri.prototype.getScheme = function() {\r\n return this.scheme_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the scheme/protocol.\r\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newScheme New scheme value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\r\n this.enforceReadOnly();\r\n this.scheme_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\r\n\r\n // remove an : at the end of the scheme so somebody can pass in\r\n // window.location.protocol\r\n if (this.scheme_) {\r\n this.scheme_ = this.scheme_.replace(/:$/, '');\r\n }\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the scheme has been set.\r\n */\r\ngoog.Uri.prototype.hasScheme = function() {\r\n return !!this.scheme_;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded user info.\r\n */\r\ngoog.Uri.prototype.getUserInfo = function() {\r\n return this.userInfo_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the userInfo.\r\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newUserInfo New userInfo value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\r\n this.enforceReadOnly();\r\n this.userInfo_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user info has been set.\r\n */\r\ngoog.Uri.prototype.hasUserInfo = function() {\r\n return !!this.userInfo_;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded domain.\r\n */\r\ngoog.Uri.prototype.getDomain = function() {\r\n return this.domain_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the domain.\r\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newDomain New domain value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\r\n this.enforceReadOnly();\r\n this.domain_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the domain has been set.\r\n */\r\ngoog.Uri.prototype.hasDomain = function() {\r\n return !!this.domain_;\r\n};\r\n\r\n\r\n/**\r\n * @return {?number} The port number.\r\n */\r\ngoog.Uri.prototype.getPort = function() {\r\n return this.port_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the port number.\r\n * @param {*} newPort Port number. Will be explicitly casted to a number.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setPort = function(newPort) {\r\n this.enforceReadOnly();\r\n\r\n if (newPort) {\r\n newPort = Number(newPort);\r\n if (isNaN(newPort) || newPort < 0) {\r\n throw new Error('Bad port number ' + newPort);\r\n }\r\n this.port_ = newPort;\r\n } else {\r\n this.port_ = null;\r\n }\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the port has been set.\r\n */\r\ngoog.Uri.prototype.hasPort = function() {\r\n return this.port_ != null;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded path.\r\n */\r\ngoog.Uri.prototype.getPath = function() {\r\n return this.path_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the path.\r\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newPath New path value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\r\n this.enforceReadOnly();\r\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the path has been set.\r\n */\r\ngoog.Uri.prototype.hasPath = function() {\r\n return !!this.path_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the query string has been set.\r\n */\r\ngoog.Uri.prototype.hasQuery = function() {\r\n return this.queryData_.toString() !== '';\r\n};\r\n\r\n\r\n/**\r\n * Sets the query data.\r\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * Applies only if queryData is a string.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\r\n this.enforceReadOnly();\r\n\r\n if (queryData instanceof goog.Uri.QueryData) {\r\n this.queryData_ = queryData;\r\n this.queryData_.setIgnoreCase(this.ignoreCase_);\r\n } else {\r\n if (!opt_decode) {\r\n // QueryData accepts encoded query string, so encode it if\r\n // opt_decode flag is not true.\r\n queryData = goog.Uri.encodeSpecialChars_(\r\n queryData, goog.Uri.reDisallowedInQuery_);\r\n }\r\n this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);\r\n }\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Sets the URI query.\r\n * @param {string} newQuery New query value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\r\n return this.setQueryData(newQuery, opt_decode);\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The encoded URI query, not including the ?.\r\n */\r\ngoog.Uri.prototype.getEncodedQuery = function() {\r\n return this.queryData_.toString();\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded URI query, not including the ?.\r\n */\r\ngoog.Uri.prototype.getDecodedQuery = function() {\r\n return this.queryData_.toDecodedString();\r\n};\r\n\r\n\r\n/**\r\n * Returns the query data.\r\n * @return {!goog.Uri.QueryData} QueryData object.\r\n */\r\ngoog.Uri.prototype.getQueryData = function() {\r\n return this.queryData_;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The encoded URI query, not including the ?.\r\n *\r\n * Warning: This method, unlike other getter methods, returns encoded\r\n * value, instead of decoded one.\r\n */\r\ngoog.Uri.prototype.getQuery = function() {\r\n return this.getEncodedQuery();\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the named query parameters, clearing previous values for\r\n * that key.\r\n *\r\n * @param {string} key The parameter to set.\r\n * @param {*} value The new value. Value does not need to be encoded.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setParameterValue = function(key, value) {\r\n this.enforceReadOnly();\r\n this.queryData_.set(key, value);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Sets the values of the named query parameters, clearing previous values for\r\n * that key. Not new values will currently be moved to the end of the query\r\n * string.\r\n *\r\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\r\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\r\n *\r\n * @param {string} key The parameter to set.\r\n * @param {*} values The new values. If values is a single\r\n * string then it will be treated as the sole value. Values do not need to\r\n * be encoded.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setParameterValues = function(key, values) {\r\n this.enforceReadOnly();\r\n\r\n if (!goog.isArray(values)) {\r\n values = [String(values)];\r\n }\r\n\r\n this.queryData_.setValues(key, values);\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\r\n * query parameter values.\r\n * @param {string} name The parameter to get values for.\r\n * @return {!Array<?>} The values for a given cgi parameter as a list of\r\n * decoded query parameter values.\r\n */\r\ngoog.Uri.prototype.getParameterValues = function(name) {\r\n return this.queryData_.getValues(name);\r\n};\r\n\r\n\r\n/**\r\n * Returns the first value for a given cgi parameter or undefined if the given\r\n * parameter name does not appear in the query string.\r\n * @param {string} paramName Unescaped parameter name.\r\n * @return {string|undefined} The first value for a given cgi parameter or\r\n * undefined if the given parameter name does not appear in the query\r\n * string.\r\n */\r\ngoog.Uri.prototype.getParameterValue = function(paramName) {\r\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The URI fragment, not including the #.\r\n */\r\ngoog.Uri.prototype.getFragment = function() {\r\n return this.fragment_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the URI fragment.\r\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newFragment New fragment value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\r\n this.enforceReadOnly();\r\n this.fragment_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the URI has a fragment set.\r\n */\r\ngoog.Uri.prototype.hasFragment = function() {\r\n return !!this.fragment_;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if this has the same domain as that of uri2.\r\n * @param {!goog.Uri} uri2 The URI object to compare to.\r\n * @return {boolean} true if same domain; false otherwise.\r\n */\r\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\r\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\r\n this.getDomain() == uri2.getDomain()) &&\r\n ((!this.hasPort() && !uri2.hasPort()) ||\r\n this.getPort() == uri2.getPort());\r\n};\r\n\r\n\r\n/**\r\n * Adds a random parameter to the Uri.\r\n * @return {!goog.Uri} Reference to this Uri object.\r\n */\r\ngoog.Uri.prototype.makeUnique = function() {\r\n this.enforceReadOnly();\r\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Removes the named query parameter.\r\n *\r\n * @param {string} key The parameter to remove.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.removeParameter = function(key) {\r\n this.enforceReadOnly();\r\n this.queryData_.remove(key);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether Uri is read only. If this goog.Uri is read-only,\r\n * enforceReadOnly_ will be called at the start of any function that may modify\r\n * this Uri.\r\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\r\n * @return {!goog.Uri} Reference to this Uri object.\r\n */\r\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\r\n this.isReadOnly_ = isReadOnly;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the URI is read only.\r\n */\r\ngoog.Uri.prototype.isReadOnly = function() {\r\n return this.isReadOnly_;\r\n};\r\n\r\n\r\n/**\r\n * Checks if this Uri has been marked as read only, and if so, throws an error.\r\n * This should be called whenever any modifying function is called.\r\n */\r\ngoog.Uri.prototype.enforceReadOnly = function() {\r\n if (this.isReadOnly_) {\r\n throw new Error('Tried to modify a read-only Uri');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sets whether to ignore case.\r\n * NOTE: If there are already key/value pairs in the QueryData, and\r\n * ignoreCase_ is set to false, the keys will all be lower-cased.\r\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\r\n * @return {!goog.Uri} Reference to this Uri object.\r\n */\r\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\r\n this.ignoreCase_ = ignoreCase;\r\n if (this.queryData_) {\r\n this.queryData_.setIgnoreCase(ignoreCase);\r\n }\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether to ignore case.\r\n */\r\ngoog.Uri.prototype.getIgnoreCase = function() {\r\n return this.ignoreCase_;\r\n};\r\n\r\n\r\n//==============================================================================\r\n// Static members\r\n//==============================================================================\r\n\r\n\r\n/**\r\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\r\n * If a Uri object is passed to parse then it will return a clone of the object.\r\n *\r\n * @throws URIError If parsing the URI is malformed. The passed URI components\r\n * should all be parseable by decodeURIComponent.\r\n * @param {*} uri Raw URI string or instance of Uri\r\n * object.\r\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\r\n * names in #getParameterValue.\r\n * @return {!goog.Uri} The new URI object.\r\n */\r\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\r\n return uri instanceof goog.Uri ? uri.clone() :\r\n new goog.Uri(uri, opt_ignoreCase);\r\n};\r\n\r\n\r\n/**\r\n * Creates a new goog.Uri object from unencoded parts.\r\n *\r\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\r\n * @param {?string=} opt_userInfo username:password.\r\n * @param {?string=} opt_domain www.google.com.\r\n * @param {?number=} opt_port 9830.\r\n * @param {?string=} opt_path /some/path/to/a/file.html.\r\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\r\n * @param {?string=} opt_fragment The fragment without the #.\r\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\r\n * #getParameterValue.\r\n *\r\n * @return {!goog.Uri} The new URI object.\r\n */\r\ngoog.Uri.create = function(\r\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\r\n opt_fragment, opt_ignoreCase) {\r\n\r\n var uri = new goog.Uri(null, opt_ignoreCase);\r\n\r\n // Only set the parts if they are defined and not empty strings.\r\n opt_scheme && uri.setScheme(opt_scheme);\r\n opt_userInfo && uri.setUserInfo(opt_userInfo);\r\n opt_domain && uri.setDomain(opt_domain);\r\n opt_port && uri.setPort(opt_port);\r\n opt_path && uri.setPath(opt_path);\r\n opt_query && uri.setQueryData(opt_query);\r\n opt_fragment && uri.setFragment(opt_fragment);\r\n\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * Resolves a relative Uri against a base Uri, accepting both strings and\r\n * Uri objects.\r\n *\r\n * @param {*} base Base Uri.\r\n * @param {*} rel Relative Uri.\r\n * @return {!goog.Uri} Resolved uri.\r\n */\r\ngoog.Uri.resolve = function(base, rel) {\r\n if (!(base instanceof goog.Uri)) {\r\n base = goog.Uri.parse(base);\r\n }\r\n\r\n if (!(rel instanceof goog.Uri)) {\r\n rel = goog.Uri.parse(rel);\r\n }\r\n\r\n return base.resolve(rel);\r\n};\r\n\r\n\r\n/**\r\n * Removes dot segments in given path component, as described in\r\n * RFC 3986, section 5.2.4.\r\n *\r\n * @param {string} path A non-empty path component.\r\n * @return {string} Path component with removed dot segments.\r\n */\r\ngoog.Uri.removeDotSegments = function(path) {\r\n if (path == '..' || path == '.') {\r\n return '';\r\n\r\n } else if (\r\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\r\n // This optimization detects uris which do not contain dot-segments,\r\n // and as a consequence do not require any processing.\r\n return path;\r\n\r\n } else {\r\n var leadingSlash = goog.string.startsWith(path, '/');\r\n var segments = path.split('/');\r\n var out = [];\r\n\r\n for (var pos = 0; pos < segments.length;) {\r\n var segment = segments[pos++];\r\n\r\n if (segment == '.') {\r\n if (leadingSlash && pos == segments.length) {\r\n out.push('');\r\n }\r\n } else if (segment == '..') {\r\n if (out.length > 1 || out.length == 1 && out[0] != '') {\r\n out.pop();\r\n }\r\n if (leadingSlash && pos == segments.length) {\r\n out.push('');\r\n }\r\n } else {\r\n out.push(segment);\r\n leadingSlash = true;\r\n }\r\n }\r\n\r\n return out.join('/');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Decodes a value or returns the empty string if it isn't defined or empty.\r\n * @throws URIError If decodeURIComponent fails to decode val.\r\n * @param {string|undefined} val Value to decode.\r\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\r\n * not be decoded.\r\n * @return {string} Decoded value.\r\n * @private\r\n */\r\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\r\n // Don't use UrlDecode() here because val is not a query parameter.\r\n if (!val) {\r\n return '';\r\n }\r\n\r\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\r\n // so that we can distinguish between the 2 inputs. This is later undone by\r\n // removeDoubleEncoding_.\r\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\r\n decodeURIComponent(val);\r\n};\r\n\r\n\r\n/**\r\n * If unescapedPart is non null, then escapes any characters in it that aren't\r\n * valid characters in a url and also escapes any special characters that\r\n * appear in extra.\r\n *\r\n * @param {*} unescapedPart The string to encode.\r\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\r\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\r\n * encoding.\r\n * @return {?string} null iff unescapedPart == null.\r\n * @private\r\n */\r\ngoog.Uri.encodeSpecialChars_ = function(\r\n unescapedPart, extra, opt_removeDoubleEncoding) {\r\n if (goog.isString(unescapedPart)) {\r\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\r\n if (opt_removeDoubleEncoding) {\r\n // encodeURI double-escapes %XX sequences used to represent restricted\r\n // characters in some URI components, remove the double escaping here.\r\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\r\n }\r\n return encoded;\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\r\n * @param {string} ch One character string.\r\n * @return {string} Encoded string.\r\n * @private\r\n */\r\ngoog.Uri.encodeChar_ = function(ch) {\r\n var n = ch.charCodeAt(0);\r\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\r\n};\r\n\r\n\r\n/**\r\n * Removes double percent-encoding from a string.\r\n * @param {string} doubleEncodedString String\r\n * @return {string} String with double encoding removed.\r\n * @private\r\n */\r\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\r\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\r\n};\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in the scheme or\r\n * userInfo part of the URI.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in a relative path.\r\n * Colon is included due to RFC 3986 3.3.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in an absolute path.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in the query.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in the fragment.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInFragment_ = /#/g;\r\n\r\n\r\n/**\r\n * Checks whether two URIs have the same domain.\r\n * @param {string} uri1String First URI string.\r\n * @param {string} uri2String Second URI string.\r\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\r\n */\r\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\r\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\r\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\r\n var pieces1 = goog.uri.utils.split(uri1String);\r\n var pieces2 = goog.uri.utils.split(uri2String);\r\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\r\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\r\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\r\n pieces2[goog.uri.utils.ComponentIndex.PORT];\r\n};\r\n\r\n\r\n\r\n/**\r\n * Class used to represent URI query parameters. It is essentially a hash of\r\n * name-value pairs, though a name can be present more than once.\r\n *\r\n * Has the same interface as the collections in goog.structs.\r\n *\r\n * @param {?string=} opt_query Optional encoded query string to parse into\r\n * the object.\r\n * @param {goog.Uri=} opt_uri Optional uri object that should have its\r\n * cache invalidated when this object updates. Deprecated -- this\r\n * is no longer required.\r\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\r\n * name in #get.\r\n * @constructor\r\n * @struct\r\n * @final\r\n */\r\ngoog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {\r\n /**\r\n * The map containing name/value or name/array-of-values pairs.\r\n * May be null if it requires parsing from the query string.\r\n *\r\n * We need to use a Map because we cannot guarantee that the key names will\r\n * not be problematic for IE.\r\n *\r\n * @private {?goog.structs.Map<string, !Array<*>>}\r\n */\r\n this.keyMap_ = null;\r\n\r\n /**\r\n * The number of params, or null if it requires computing.\r\n * @private {?number}\r\n */\r\n this.count_ = null;\r\n\r\n /**\r\n * Encoded query string, or null if it requires computing from the key map.\r\n * @private {?string}\r\n */\r\n this.encodedQuery_ = opt_query || null;\r\n\r\n /**\r\n * If true, ignore the case of the parameter name in #get.\r\n * @private {boolean}\r\n */\r\n this.ignoreCase_ = !!opt_ignoreCase;\r\n};\r\n\r\n\r\n/**\r\n * If the underlying key map is not yet initialized, it parses the\r\n * query string and fills the map with parsed data.\r\n * @private\r\n */\r\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\r\n if (!this.keyMap_) {\r\n this.keyMap_ = new goog.structs.Map();\r\n this.count_ = 0;\r\n if (this.encodedQuery_) {\r\n var self = this;\r\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\r\n self.add(goog.string.urlDecode(name), value);\r\n });\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Creates a new query data instance from a map of names and values.\r\n *\r\n * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter\r\n * names to parameter value. If parameter value is an array, it is\r\n * treated as if the key maps to each individual value in the\r\n * array.\r\n * @param {goog.Uri=} opt_uri URI object that should have its cache\r\n * invalidated when this object updates.\r\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\r\n * name in #get.\r\n * @return {!goog.Uri.QueryData} The populated query data instance.\r\n */\r\ngoog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {\r\n var keys = goog.structs.getKeys(map);\r\n if (typeof keys == 'undefined') {\r\n throw new Error('Keys are undefined');\r\n }\r\n\r\n var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);\r\n var values = goog.structs.getValues(map);\r\n for (var i = 0; i < keys.length; i++) {\r\n var key = keys[i];\r\n var value = values[i];\r\n if (!goog.isArray(value)) {\r\n queryData.add(key, value);\r\n } else {\r\n queryData.setValues(key, value);\r\n }\r\n }\r\n return queryData;\r\n};\r\n\r\n\r\n/**\r\n * Creates a new query data instance from parallel arrays of parameter names\r\n * and values. Allows for duplicate parameter names. Throws an error if the\r\n * lengths of the arrays differ.\r\n *\r\n * @param {!Array<string>} keys Parameter names.\r\n * @param {!Array<?>} values Parameter values.\r\n * @param {goog.Uri=} opt_uri URI object that should have its cache\r\n * invalidated when this object updates.\r\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\r\n * name in #get.\r\n * @return {!goog.Uri.QueryData} The populated query data instance.\r\n */\r\ngoog.Uri.QueryData.createFromKeysValues = function(\r\n keys, values, opt_uri, opt_ignoreCase) {\r\n if (keys.length != values.length) {\r\n throw new Error('Mismatched lengths for keys/values');\r\n }\r\n var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);\r\n for (var i = 0; i < keys.length; i++) {\r\n queryData.add(keys[i], values[i]);\r\n }\r\n return queryData;\r\n};\r\n\r\n\r\n/**\r\n * @return {?number} The number of parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.getCount = function() {\r\n this.ensureKeyMapInitialized_();\r\n return this.count_;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key value pair.\r\n * @param {string} key Name.\r\n * @param {*} value Value.\r\n * @return {!goog.Uri.QueryData} Instance of this object.\r\n */\r\ngoog.Uri.QueryData.prototype.add = function(key, value) {\r\n this.ensureKeyMapInitialized_();\r\n this.invalidateCache_();\r\n\r\n key = this.getKeyName_(key);\r\n var values = this.keyMap_.get(key);\r\n if (!values) {\r\n this.keyMap_.set(key, (values = []));\r\n }\r\n values.push(value);\r\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Removes all the params with the given key.\r\n * @param {string} key Name.\r\n * @return {boolean} Whether any parameter was removed.\r\n */\r\ngoog.Uri.QueryData.prototype.remove = function(key) {\r\n this.ensureKeyMapInitialized_();\r\n\r\n key = this.getKeyName_(key);\r\n if (this.keyMap_.containsKey(key)) {\r\n this.invalidateCache_();\r\n\r\n // Decrement parameter count.\r\n this.count_ =\r\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\r\n return this.keyMap_.remove(key);\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Clears the parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.clear = function() {\r\n this.invalidateCache_();\r\n this.keyMap_ = null;\r\n this.count_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether we have any parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.isEmpty = function() {\r\n this.ensureKeyMapInitialized_();\r\n return this.count_ == 0;\r\n};\r\n\r\n\r\n/**\r\n * Whether there is a parameter with the given name\r\n * @param {string} key The parameter name to check for.\r\n * @return {boolean} Whether there is a parameter with the given name.\r\n */\r\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\r\n this.ensureKeyMapInitialized_();\r\n key = this.getKeyName_(key);\r\n return this.keyMap_.containsKey(key);\r\n};\r\n\r\n\r\n/**\r\n * Whether there is a parameter with the given value.\r\n * @param {*} value The value to check for.\r\n * @return {boolean} Whether there is a parameter with the given value.\r\n */\r\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\r\n // NOTE(arv): This solution goes through all the params even if it was the\r\n // first param. We can get around this by not reusing code or by switching to\r\n // iterators.\r\n var vals = this.getValues();\r\n return goog.array.contains(vals, value);\r\n};\r\n\r\n\r\n/**\r\n * Runs a callback on every key-value pair in the map, including duplicate keys.\r\n * This won't maintain original order when duplicate keys are interspersed (like\r\n * getKeys() / getValues()).\r\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\r\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\r\n * @template SCOPE\r\n */\r\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\r\n this.ensureKeyMapInitialized_();\r\n this.keyMap_.forEach(function(values, key) {\r\n goog.array.forEach(values, function(value) {\r\n f.call(opt_scope, value, key, this);\r\n }, this);\r\n }, this);\r\n};\r\n\r\n\r\n/**\r\n * Returns all the keys of the parameters. If a key is used multiple times\r\n * it will be included multiple times in the returned array\r\n * @return {!Array<string>} All the keys of the parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.getKeys = function() {\r\n this.ensureKeyMapInitialized_();\r\n // We need to get the values to know how many keys to add.\r\n var vals = this.keyMap_.getValues();\r\n var keys = this.keyMap_.getKeys();\r\n var rv = [];\r\n for (var i = 0; i < keys.length; i++) {\r\n var val = vals[i];\r\n for (var j = 0; j < val.length; j++) {\r\n rv.push(keys[i]);\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Returns all the values of the parameters with the given name. If the query\r\n * data has no such key this will return an empty array. If no key is given\r\n * all values wil be returned.\r\n * @param {string=} opt_key The name of the parameter to get the values for.\r\n * @return {!Array<?>} All the values of the parameters with the given name.\r\n */\r\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\r\n this.ensureKeyMapInitialized_();\r\n var rv = [];\r\n if (goog.isString(opt_key)) {\r\n if (this.containsKey(opt_key)) {\r\n rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));\r\n }\r\n } else {\r\n // Return all values.\r\n var values = this.keyMap_.getValues();\r\n for (var i = 0; i < values.length; i++) {\r\n rv = goog.array.concat(rv, values[i]);\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Sets a key value pair and removes all other keys with the same value.\r\n *\r\n * @param {string} key Name.\r\n * @param {*} value Value.\r\n * @return {!goog.Uri.QueryData} Instance of this object.\r\n */\r\ngoog.Uri.QueryData.prototype.set = function(key, value) {\r\n this.ensureKeyMapInitialized_();\r\n this.invalidateCache_();\r\n\r\n // TODO(chrishenry): This could be better written as\r\n // this.remove(key), this.add(key, value), but that would reorder\r\n // the key (since the key is first removed and then added at the\r\n // end) and we would have to fix unit tests that depend on key\r\n // ordering.\r\n key = this.getKeyName_(key);\r\n if (this.containsKey(key)) {\r\n this.count_ =\r\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\r\n }\r\n this.keyMap_.set(key, [value]);\r\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Returns the first value associated with the key. If the query data has no\r\n * such key this will return undefined or the optional default.\r\n * @param {string} key The name of the parameter to get the value for.\r\n * @param {*=} opt_default The default value to return if the query data\r\n * has no such key.\r\n * @return {*} The first string value associated with the key, or opt_default\r\n * if there's no value.\r\n */\r\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\r\n if (!key) {\r\n return opt_default;\r\n }\r\n var values = this.getValues(key);\r\n return values.length > 0 ? String(values[0]) : opt_default;\r\n};\r\n\r\n\r\n/**\r\n * Sets the values for a key. If the key already exists, this will\r\n * override all of the existing values that correspond to the key.\r\n * @param {string} key The key to set values for.\r\n * @param {!Array<?>} values The values to set.\r\n */\r\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\r\n this.remove(key);\r\n\r\n if (values.length > 0) {\r\n this.invalidateCache_();\r\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\r\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {string} Encoded query string.\r\n * @override\r\n */\r\ngoog.Uri.QueryData.prototype.toString = function() {\r\n if (this.encodedQuery_) {\r\n return this.encodedQuery_;\r\n }\r\n\r\n if (!this.keyMap_) {\r\n return '';\r\n }\r\n\r\n var sb = [];\r\n\r\n // In the past, we use this.getKeys() and this.getVals(), but that\r\n // generates a lot of allocations as compared to simply iterating\r\n // over the keys.\r\n var keys = this.keyMap_.getKeys();\r\n for (var i = 0; i < keys.length; i++) {\r\n var key = keys[i];\r\n var encodedKey = goog.string.urlEncode(key);\r\n var val = this.getValues(key);\r\n for (var j = 0; j < val.length; j++) {\r\n var param = encodedKey;\r\n // Ensure that null and undefined are encoded into the url as\r\n // literal strings.\r\n if (val[j] !== '') {\r\n param += '=' + goog.string.urlEncode(val[j]);\r\n }\r\n sb.push(param);\r\n }\r\n }\r\n\r\n return this.encodedQuery_ = sb.join('&');\r\n};\r\n\r\n\r\n/**\r\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\r\n * any of the URI components).\r\n * @return {string} Decoded query string.\r\n */\r\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\r\n return goog.Uri.decodeOrEmpty_(this.toString());\r\n};\r\n\r\n\r\n/**\r\n * Invalidate the cache.\r\n * @private\r\n */\r\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\r\n this.encodedQuery_ = null;\r\n};\r\n\r\n\r\n/**\r\n * Removes all keys that are not in the provided list. (Modifies this object.)\r\n * @param {Array<string>} keys The desired keys.\r\n * @return {!goog.Uri.QueryData} a reference to this object.\r\n */\r\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\r\n this.ensureKeyMapInitialized_();\r\n this.keyMap_.forEach(function(value, key) {\r\n if (!goog.array.contains(keys, key)) {\r\n this.remove(key);\r\n }\r\n }, this);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Clone the query data instance.\r\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\r\n */\r\ngoog.Uri.QueryData.prototype.clone = function() {\r\n var rv = new goog.Uri.QueryData();\r\n rv.encodedQuery_ = this.encodedQuery_;\r\n if (this.keyMap_) {\r\n rv.keyMap_ = this.keyMap_.clone();\r\n rv.count_ = this.count_;\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Helper function to get the key name from a JavaScript object. Converts\r\n * the object to a string, and to lower case if necessary.\r\n * @private\r\n * @param {*} arg The object to get a key name from.\r\n * @return {string} valid key name which can be looked up in #keyMap_.\r\n */\r\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\r\n var keyName = String(arg);\r\n if (this.ignoreCase_) {\r\n keyName = keyName.toLowerCase();\r\n }\r\n return keyName;\r\n};\r\n\r\n\r\n/**\r\n * Ignore case in parameter names.\r\n * NOTE: If there are already key/value pairs in the QueryData, and\r\n * ignoreCase_ is set to false, the keys will all be lower-cased.\r\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\r\n */\r\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\r\n var resetKeys = ignoreCase && !this.ignoreCase_;\r\n if (resetKeys) {\r\n this.ensureKeyMapInitialized_();\r\n this.invalidateCache_();\r\n this.keyMap_.forEach(function(value, key) {\r\n var lowerCase = key.toLowerCase();\r\n if (key != lowerCase) {\r\n this.remove(key);\r\n this.setValues(lowerCase, value);\r\n }\r\n }, this);\r\n }\r\n this.ignoreCase_ = ignoreCase;\r\n};\r\n\r\n\r\n/**\r\n * Extends a query data object with another query data or map like object. This\r\n * operates 'in-place', it does not create a new QueryData object.\r\n *\r\n * @param {...(?goog.Uri.QueryData|?goog.structs.Map<?, ?>|?Object)} var_args\r\n * The object from which key value pairs will be copied. Note: does not\r\n * accept null.\r\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\r\n * types of parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\r\n for (var i = 0; i < arguments.length; i++) {\r\n var data = arguments[i];\r\n goog.structs.forEach(\r\n data, function(value, key) { this.add(key, value); }, this);\r\n }\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Base TestChannel implementation.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.BaseTestChannel');\r\n\r\ngoog.require('goog.labs.net.webChannel.Channel');\r\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\ngoog.require('goog.labs.net.webChannel.requestStats');\r\ngoog.require('goog.net.WebChannel');\r\n\r\ngoog.forwardDeclare('goog.labs.net.webChannel.WebChannelBase');\r\n\r\n\r\n\r\n/**\r\n * A TestChannel is used during the first part of channel negotiation\r\n * with the server to create the channel. It helps us determine whether we're\r\n * behind a buffering proxy.\r\n *\r\n * @constructor\r\n * @struct\r\n * @param {!goog.labs.net.webChannel.Channel} channel The channel\r\n * that owns this test channel.\r\n * @param {!goog.labs.net.webChannel.WebChannelDebug} channelDebug A\r\n * WebChannelDebug instance to use for logging.\r\n * @implements {goog.labs.net.webChannel.Channel}\r\n */\r\ngoog.labs.net.webChannel.BaseTestChannel = function(channel, channelDebug) {\r\n /**\r\n * The channel that owns this test channel\r\n * @private {!goog.labs.net.webChannel.Channel}\r\n */\r\n this.channel_ = channel;\r\n\r\n /**\r\n * The channel debug to use for logging\r\n * @private {!goog.labs.net.webChannel.WebChannelDebug}\r\n */\r\n this.channelDebug_ = channelDebug;\r\n\r\n /**\r\n * Extra HTTP headers to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraHeaders_ = null;\r\n\r\n /**\r\n * The test request.\r\n * @private {goog.labs.net.webChannel.ChannelRequest}\r\n */\r\n this.request_ = null;\r\n\r\n /**\r\n * Whether we have received the first result as an intermediate result. This\r\n * helps us determine whether we're behind a buffering proxy.\r\n * @private {boolean}\r\n */\r\n this.receivedIntermediateResult_ = false;\r\n\r\n /**\r\n * The relative path for test requests.\r\n * @private {?string}\r\n */\r\n this.path_ = null;\r\n\r\n /**\r\n * The last status code received.\r\n * @private {number}\r\n */\r\n this.lastStatusCode_ = -1;\r\n\r\n /**\r\n * A subdomain prefix for using a subdomain in IE for the backchannel\r\n * requests.\r\n * @private {?string}\r\n */\r\n this.hostPrefix_ = null;\r\n\r\n /**\r\n * The effective client protocol as indicated by the initial handshake\r\n * response via the x-client-wire-protocol header.\r\n *\r\n * @private {?string}\r\n */\r\n this.clientProtocol_ = null;\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannel = goog.net.WebChannel;\r\nvar BaseTestChannel = goog.labs.net.webChannel.BaseTestChannel;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\nvar ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\nvar Channel = goog.labs.net.webChannel.Channel;\r\n\r\n\r\n/**\r\n * Enum type for the test channel state machine\r\n * @enum {number}\r\n * @private\r\n */\r\nBaseTestChannel.State_ = {\r\n /**\r\n * The state for the TestChannel state machine where we making the\r\n * initial call to get the server configured parameters.\r\n */\r\n INIT: 0,\r\n\r\n /**\r\n * The state for the TestChannel state machine where we're checking to\r\n * se if we're behind a buffering proxy.\r\n */\r\n CONNECTION_TESTING: 1\r\n};\r\n\r\n\r\n/**\r\n * The state of the state machine for this object.\r\n *\r\n * @private {?BaseTestChannel.State_}\r\n */\r\nBaseTestChannel.prototype.state_ = null;\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @param {Object} extraHeaders The HTTP headers.\r\n */\r\nBaseTestChannel.prototype.setExtraHeaders = function(extraHeaders) {\r\n this.extraHeaders_ = extraHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Starts the test channel. This initiates connections to the server.\r\n *\r\n * @param {string} path The relative uri for the test connection.\r\n */\r\nBaseTestChannel.prototype.connect = function(path) {\r\n this.path_ = path;\r\n var sendDataUri = this.channel_.getForwardChannelUri(this.path_);\r\n\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_ONE_START);\r\n\r\n // If the channel already has the result of the handshake, then skip it.\r\n var handshakeResult = this.channel_.getConnectionState().handshakeResult;\r\n if (goog.isDefAndNotNull(handshakeResult)) {\r\n this.hostPrefix_ = this.channel_.correctHostPrefix(handshakeResult[0]);\r\n this.state_ = BaseTestChannel.State_.CONNECTION_TESTING;\r\n this.checkBufferingProxy_();\r\n return;\r\n }\r\n\r\n // the first request returns server specific parameters\r\n sendDataUri.setParameterValues('MODE', 'init');\r\n\r\n // http-session-id to be generated as the response\r\n if (!this.channel_.getBackgroundChannelTest() &&\r\n this.channel_.getHttpSessionIdParam()) {\r\n sendDataUri.setParameterValues(WebChannel.X_HTTP_SESSION_ID,\r\n this.channel_.getHttpSessionIdParam());\r\n }\r\n\r\n this.request_ = ChannelRequest.createChannelRequest(this, this.channelDebug_);\r\n\r\n this.request_.setExtraHeaders(this.extraHeaders_);\r\n\r\n this.request_.xmlHttpGet(\r\n sendDataUri, false /* decodeChunks */, null /* hostPrefix */);\r\n this.state_ = BaseTestChannel.State_.INIT;\r\n};\r\n\r\n\r\n/**\r\n * Begins the second stage of the test channel where we test to see if we're\r\n * behind a buffering proxy. The server sends back a multi-chunked response\r\n * with the first chunk containing the content '1' and then two seconds later\r\n * sending the second chunk containing the content '2'. Depending on how we\r\n * receive the content, we can tell if we're behind a buffering proxy.\r\n * @private\r\n */\r\nBaseTestChannel.prototype.checkBufferingProxy_ = function() {\r\n this.channelDebug_.debug('TestConnection: starting stage 2');\r\n\r\n // If the test result is already available, skip its execution.\r\n var bufferingProxyResult =\r\n this.channel_.getConnectionState().bufferingProxyResult;\r\n if (goog.isDefAndNotNull(bufferingProxyResult)) {\r\n this.channelDebug_.debug(function() {\r\n return 'TestConnection: skipping stage 2, precomputed result is ' +\r\n bufferingProxyResult ?\r\n 'Buffered' :\r\n 'Unbuffered';\r\n });\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_START);\r\n if (bufferingProxyResult) { // Buffered/Proxy connection\r\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\r\n this.channel_.testConnectionFinished(this, false);\r\n } else { // Unbuffered/NoProxy connection\r\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\r\n this.channel_.testConnectionFinished(this, true);\r\n }\r\n return; // Skip the test\r\n }\r\n this.request_ = ChannelRequest.createChannelRequest(this, this.channelDebug_);\r\n this.request_.setExtraHeaders(this.extraHeaders_);\r\n var recvDataUri = this.channel_.getBackChannelUri(\r\n this.hostPrefix_,\r\n /** @type {string} */ (this.path_));\r\n\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_START);\r\n recvDataUri.setParameterValues('TYPE', 'xmlhttp');\r\n\r\n var param = this.channel_.getHttpSessionIdParam();\r\n var value = this.channel_.getHttpSessionId();\r\n if (param && value) {\r\n recvDataUri.setParameterValue(param, value);\r\n }\r\n\r\n this.request_.xmlHttpGet(\r\n recvDataUri, false /** decodeChunks */, this.hostPrefix_);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.createXhrIo = function(hostPrefix) {\r\n return this.channel_.createXhrIo(hostPrefix);\r\n};\r\n\r\n\r\n/**\r\n * Aborts the test channel.\r\n */\r\nBaseTestChannel.prototype.abort = function() {\r\n if (this.request_) {\r\n this.request_.cancel();\r\n this.request_ = null;\r\n }\r\n this.lastStatusCode_ = -1;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the test channel is closed. The ChannelRequest object expects\r\n * this method to be implemented on its handler.\r\n *\r\n * @return {boolean} Whether the channel is closed.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.isClosed = function() {\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Callback from ChannelRequest for when new data is received\r\n *\r\n * @param {ChannelRequest} req The request object.\r\n * @param {string} responseText The text of the response.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.onRequestData = function(req, responseText) {\r\n this.lastStatusCode_ = req.getLastStatusCode();\r\n if (this.state_ == BaseTestChannel.State_.INIT) {\r\n this.channelDebug_.debug('TestConnection: Got data for stage 1');\r\n\r\n this.applyControlHeaders_(req);\r\n\r\n if (!responseText) {\r\n this.channelDebug_.debug('TestConnection: Null responseText');\r\n // The server should always send text; something is wrong here\r\n this.channel_.testConnectionFailure(this, ChannelRequest.Error.BAD_DATA);\r\n return;\r\n }\r\n\r\n\r\n try {\r\n var channel = /** @type {!goog.labs.net.webChannel.WebChannelBase} */ (\r\n this.channel_);\r\n var respArray = channel.getWireCodec().decodeMessage(responseText);\r\n } catch (e) {\r\n this.channelDebug_.dumpException(e);\r\n this.channel_.testConnectionFailure(this, ChannelRequest.Error.BAD_DATA);\r\n return;\r\n }\r\n this.hostPrefix_ = this.channel_.correctHostPrefix(respArray[0]);\r\n } else if (this.state_ == BaseTestChannel.State_.CONNECTION_TESTING) {\r\n if (this.receivedIntermediateResult_) {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_DATA_TWO);\r\n } else {\r\n // '11111' is used instead of '1' to prevent a small amount of buffering\r\n // by Safari.\r\n if (responseText == '11111') {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_DATA_ONE);\r\n this.receivedIntermediateResult_ = true;\r\n if (this.checkForEarlyNonBuffered_()) {\r\n // If early chunk detection is on, and we passed the tests,\r\n // assume HTTP_OK, cancel the test and turn on noproxy mode.\r\n this.lastStatusCode_ = 200;\r\n this.request_.cancel();\r\n this.channelDebug_.debug(\r\n 'Test connection succeeded; using streaming connection');\r\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\r\n this.channel_.testConnectionFinished(this, true);\r\n }\r\n } else {\r\n requestStats.notifyStatEvent(\r\n requestStats.Stat.TEST_STAGE_TWO_DATA_BOTH);\r\n this.receivedIntermediateResult_ = false;\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Callback from ChannelRequest that indicates a request has completed.\r\n *\r\n * @param {!ChannelRequest} req The request object.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.onRequestComplete = function(req) {\r\n this.lastStatusCode_ = this.request_.getLastStatusCode();\r\n if (!this.request_.getSuccess()) {\r\n this.channelDebug_.debug(\r\n 'TestConnection: request failed, in state ' + this.state_);\r\n if (this.state_ == BaseTestChannel.State_.INIT) {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_ONE_FAILED);\r\n } else if (this.state_ == BaseTestChannel.State_.CONNECTION_TESTING) {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_FAILED);\r\n }\r\n this.channel_.testConnectionFailure(\r\n this,\r\n /** @type {ChannelRequest.Error} */\r\n (this.request_.getLastError()));\r\n return;\r\n }\r\n\r\n if (this.state_ == BaseTestChannel.State_.INIT) {\r\n this.state_ = BaseTestChannel.State_.CONNECTION_TESTING;\r\n\r\n this.channelDebug_.debug(\r\n 'TestConnection: request complete for initial check');\r\n\r\n this.checkBufferingProxy_();\r\n } else if (this.state_ == BaseTestChannel.State_.CONNECTION_TESTING) {\r\n this.channelDebug_.debug('TestConnection: request complete for stage 2');\r\n\r\n var goodConn = this.receivedIntermediateResult_;\r\n if (goodConn) {\r\n this.channelDebug_.debug(\r\n 'Test connection succeeded; using streaming connection');\r\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\r\n this.channel_.testConnectionFinished(this, true);\r\n } else {\r\n this.channelDebug_.debug('Test connection failed; not using streaming');\r\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\r\n this.channel_.testConnectionFinished(this, false);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Apply any control headers from the initial handshake response.\r\n *\r\n * @param {!ChannelRequest} req The request object.\r\n * @private\r\n */\r\nBaseTestChannel.prototype.applyControlHeaders_ = function(req) {\r\n if (this.channel_.getBackgroundChannelTest()) {\r\n return;\r\n }\r\n\r\n var xhr = req.getXhr();\r\n if (xhr) {\r\n var protocolHeader = xhr.getStreamingResponseHeader(\r\n WebChannel.X_CLIENT_WIRE_PROTOCOL);\r\n this.clientProtocol_ = protocolHeader ? protocolHeader : null;\r\n\r\n if (this.channel_.getHttpSessionIdParam()) {\r\n var httpSessionIdHeader = xhr.getStreamingResponseHeader(\r\n WebChannel.X_HTTP_SESSION_ID);\r\n if (httpSessionIdHeader) {\r\n this.channel_.setHttpSessionId(httpSessionIdHeader);\r\n } else {\r\n this.channelDebug_.warning(\r\n 'Missing X_HTTP_SESSION_ID in the handshake response');\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {?string} The client protocol as recorded with the init handshake\r\n * request.\r\n */\r\nBaseTestChannel.prototype.getClientProtocol = function() {\r\n return this.clientProtocol_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the last status code received for a request.\r\n * @return {number} The last status code received for a request.\r\n */\r\nBaseTestChannel.prototype.getLastStatusCode = function() {\r\n return this.lastStatusCode_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether we should be using secondary domains when the\r\n * server instructs us to do so.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.shouldUseSecondaryDomains = function() {\r\n return this.channel_.shouldUseSecondaryDomains();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.isActive = function() {\r\n return this.channel_.isActive();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} True if test stage 2 detected a non-buffered\r\n * channel early and early no buffering detection is enabled.\r\n * @private\r\n */\r\nBaseTestChannel.prototype.checkForEarlyNonBuffered_ = function() {\r\n return ChannelRequest.supportsXhrStreaming();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getForwardChannelUri = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getBackChannelUri = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.correctHostPrefix = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.createDataUri = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.testConnectionFinished = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.testConnectionFailure = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getConnectionState = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.setHttpSessionIdParam = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getHttpSessionIdParam = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.setHttpSessionId = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getHttpSessionId = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getBackgroundChannelTest = goog.abstractMethod;\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview This class manages the network connectivity state.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.ConnectionState');\r\n\r\n\r\n\r\n/**\r\n * The connectivity state of the channel.\r\n *\r\n * @constructor\r\n * @struct\r\n */\r\ngoog.labs.net.webChannel.ConnectionState = function() {\r\n /**\r\n * Handshake result.\r\n * @type {Array<string>}\r\n */\r\n this.handshakeResult = null;\r\n\r\n /**\r\n * The result of checking if there is a buffering proxy in the network.\r\n * True means the connection is buffered, False means unbuffered,\r\n * null means that the result is not available.\r\n * @type {?boolean}\r\n */\r\n this.bufferingProxyResult = null;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Datastructure: Set.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * This class implements a set data structure. Adding and removing is O(1). It\r\n * supports both object and primitive values. Be careful because you can add\r\n * both 1 and new Number(1), because these are not the same. You can even add\r\n * multiple new Number(1) because these are not equal.\r\n */\r\n\r\n\r\ngoog.provide('goog.structs.Set');\r\n\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.Collection');\r\ngoog.require('goog.structs.Map');\r\n\r\n/**\r\n * A set that can contain both primitives and objects. Adding and removing\r\n * elements is O(1). Primitives are treated as identical if they have the same\r\n * type and convert to the same string. Objects are treated as identical only\r\n * if they are references to the same object. WARNING: A goog.structs.Set can\r\n * contain both 1 and (new Number(1)), because they are not the same. WARNING:\r\n * Adding (new Number(1)) twice will yield two distinct elements, because they\r\n * are two different objects. WARNING: Any object that is added to a\r\n * goog.structs.Set will be modified! Because goog.getUid() is used to\r\n * identify objects, every object in the set will be mutated.\r\n * @param {Array<T>|Object<?,T>=} opt_values Initial values to start with.\r\n * @constructor\r\n * @implements {goog.structs.Collection<T>}\r\n * @final\r\n * @template T\r\n * @deprecated This type is misleading: use ES6 Set instead.\r\n */\r\ngoog.structs.Set = function(opt_values) {\r\n this.map_ = new goog.structs.Map;\r\n if (opt_values) {\r\n this.addAll(opt_values);\r\n }\r\n};\r\n\r\n/**\r\n * A function that returns a unique id.\r\n * @private @const {function(?Object): number}\r\n */\r\ngoog.structs.Set.getUid_ = goog.getUid;\r\n\r\n\r\n/**\r\n * Obtains a unique key for an element of the set. Primitives will yield the\r\n * same key if they have the same type and convert to the same string. Object\r\n * references will yield the same key only if they refer to the same object.\r\n * @param {*} val Object or primitive value to get a key for.\r\n * @return {string} A unique key for this value/object.\r\n * @private\r\n */\r\ngoog.structs.Set.getKey_ = function(val) {\r\n var type = typeof val;\r\n if (type == 'object' && val || type == 'function') {\r\n return 'o' + goog.structs.Set.getUid_(/** @type {Object} */ (val));\r\n } else {\r\n return type.substr(0, 1) + val;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of elements in the set.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.getCount = function() {\r\n return this.map_.getCount();\r\n};\r\n\r\n\r\n/**\r\n * Add a primitive or an object to the set.\r\n * @param {T} element The primitive or object to add.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.add = function(element) {\r\n this.map_.set(goog.structs.Set.getKey_(element), element);\r\n};\r\n\r\n\r\n/**\r\n * Adds all the values in the given collection to this set.\r\n * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection\r\n * containing the elements to add.\r\n */\r\ngoog.structs.Set.prototype.addAll = function(col) {\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n this.add(values[i]);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes all values in the given collection from this set.\r\n * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection\r\n * containing the elements to remove.\r\n */\r\ngoog.structs.Set.prototype.removeAll = function(col) {\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n this.remove(values[i]);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes the given element from this set.\r\n * @param {T} element The primitive or object to remove.\r\n * @return {boolean} Whether the element was found and removed.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.remove = function(element) {\r\n return this.map_.remove(goog.structs.Set.getKey_(element));\r\n};\r\n\r\n\r\n/**\r\n * Removes all elements from this set.\r\n */\r\ngoog.structs.Set.prototype.clear = function() {\r\n this.map_.clear();\r\n};\r\n\r\n\r\n/**\r\n * Tests whether this set is empty.\r\n * @return {boolean} True if there are no elements in this set.\r\n */\r\ngoog.structs.Set.prototype.isEmpty = function() {\r\n return this.map_.isEmpty();\r\n};\r\n\r\n\r\n/**\r\n * Tests whether this set contains the given element.\r\n * @param {T} element The primitive or object to test for.\r\n * @return {boolean} True if this set contains the given element.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.contains = function(element) {\r\n return this.map_.containsKey(goog.structs.Set.getKey_(element));\r\n};\r\n\r\n\r\n/**\r\n * Tests whether this set contains all the values in a given collection.\r\n * Repeated elements in the collection are ignored, e.g. (new\r\n * goog.structs.Set([1, 2])).containsAll([1, 1]) is True.\r\n * @param {goog.structs.Collection<T>|Object} col A collection-like object.\r\n * @return {boolean} True if the set contains all elements.\r\n */\r\ngoog.structs.Set.prototype.containsAll = function(col) {\r\n return goog.structs.every(col, this.contains, this);\r\n};\r\n\r\n\r\n/**\r\n * Finds all values that are present in both this set and the given collection.\r\n * @param {Array<S>|Object<?,S>} col A collection.\r\n * @return {!goog.structs.Set<T|S>} A new set containing all the values\r\n * (primitives or objects) present in both this set and the given\r\n * collection.\r\n * @template S\r\n */\r\ngoog.structs.Set.prototype.intersection = function(col) {\r\n var result = new goog.structs.Set();\r\n\r\n var values = goog.structs.getValues(col);\r\n for (var i = 0; i < values.length; i++) {\r\n var value = values[i];\r\n if (this.contains(value)) {\r\n result.add(value);\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Finds all values that are present in this set and not in the given\r\n * collection.\r\n * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection.\r\n * @return {!goog.structs.Set} A new set containing all the values\r\n * (primitives or objects) present in this set but not in the given\r\n * collection.\r\n */\r\ngoog.structs.Set.prototype.difference = function(col) {\r\n var result = this.clone();\r\n result.removeAll(col);\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Returns an array containing all the elements in this set.\r\n * @return {!Array<T>} An array containing all the elements in this set.\r\n */\r\ngoog.structs.Set.prototype.getValues = function() {\r\n return this.map_.getValues();\r\n};\r\n\r\n\r\n/**\r\n * Creates a shallow clone of this set.\r\n * @return {!goog.structs.Set<T>} A new set containing all the same elements as\r\n * this set.\r\n */\r\ngoog.structs.Set.prototype.clone = function() {\r\n return new goog.structs.Set(this);\r\n};\r\n\r\n\r\n/**\r\n * Tests whether the given collection consists of the same elements as this set,\r\n * regardless of order, without repetition. Primitives are treated as equal if\r\n * they have the same type and convert to the same string; objects are treated\r\n * as equal if they are references to the same object. This operation is O(n).\r\n * @param {goog.structs.Collection<T>|Object} col A collection.\r\n * @return {boolean} True if the given collection consists of the same elements\r\n * as this set, regardless of order, without repetition.\r\n */\r\ngoog.structs.Set.prototype.equals = function(col) {\r\n return this.getCount() == goog.structs.getCount(col) && this.isSubsetOf(col);\r\n};\r\n\r\n\r\n/**\r\n * Tests whether the given collection contains all the elements in this set.\r\n * Primitives are treated as equal if they have the same type and convert to the\r\n * same string; objects are treated as equal if they are references to the same\r\n * object. This operation is O(n).\r\n * @param {goog.structs.Collection<T>|Object} col A collection.\r\n * @return {boolean} True if this set is a subset of the given collection.\r\n */\r\ngoog.structs.Set.prototype.isSubsetOf = function(col) {\r\n var colCount = goog.structs.getCount(col);\r\n if (this.getCount() > colCount) {\r\n return false;\r\n }\r\n // TODO(user) Find the minimal collection size where the conversion makes\r\n // the contains() method faster.\r\n if (!(col instanceof goog.structs.Set) && colCount > 5) {\r\n // Convert to a goog.structs.Set so that goog.structs.contains runs in\r\n // O(1) time instead of O(n) time.\r\n col = new goog.structs.Set(col);\r\n }\r\n return goog.structs.every(\r\n this, function(value) { return goog.structs.contains(col, value); });\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the elements in this set.\r\n * @param {boolean=} opt_keys This argument is ignored.\r\n * @return {!goog.iter.Iterator} An iterator over the elements in this set.\r\n */\r\ngoog.structs.Set.prototype.__iterator__ = function(opt_keys) {\r\n return this.map_.__iterator__(false);\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Interface and shared data structures for implementing\r\n * different wire protocol versions.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.Wire');\r\n\r\ngoog.forwardDeclare('goog.structs.Map');\r\n\r\n\r\n\r\n/**\r\n * The interface class.\r\n *\r\n * @interface\r\n */\r\ngoog.labs.net.webChannel.Wire = function() {};\r\n\r\n\r\ngoog.scope(function() {\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\n\r\n\r\n/**\r\n * The latest protocol version that this class supports. We request this version\r\n * from the server when opening the connection. Should match\r\n * LATEST_CHANNEL_VERSION on the server code.\r\n * @type {number}\r\n */\r\nWire.LATEST_CHANNEL_VERSION = 8;\r\n\r\n\r\n/**\r\n * The JSON field key for the raw data wrapper object.\r\n * @type {string}\r\n */\r\nWire.RAW_DATA_KEY = '__data__';\r\n\r\n\r\n\r\n/**\r\n * Simple container class for a (mapId, map) pair.\r\n * @param {number} mapId The id for this map.\r\n * @param {!Object|!goog.structs.Map} map The map itself.\r\n * @param {!Object=} opt_context The context associated with the map.\r\n * @constructor\r\n * @struct\r\n */\r\nWire.QueuedMap = function(mapId, map, opt_context) {\r\n /**\r\n * The id for this map.\r\n * @type {number}\r\n */\r\n this.mapId = mapId;\r\n\r\n /**\r\n * The map itself.\r\n * @type {!Object|!goog.structs.Map}\r\n */\r\n this.map = map;\r\n\r\n /**\r\n * The context for the map.\r\n * @type {Object}\r\n */\r\n this.context = opt_context || null;\r\n};\r\n\r\n\r\n/**\r\n * @return {number|undefined} the size of the raw JSON message or\r\n * undefined if the message is not encoded as a raw JSON message\r\n */\r\nWire.QueuedMap.prototype.getRawDataSize = function() {\r\n if (Wire.RAW_DATA_KEY in this.map) {\r\n var data = this.map[Wire.RAW_DATA_KEY];\r\n if (goog.isString(data)) {\r\n return data.length;\r\n }\r\n }\r\n\r\n return undefined;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A pool of forward channel requests to enable real-time\r\n * messaging from the client to server.\r\n */\r\n\r\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\r\n\r\ngoog.module.declareLegacyNamespace();\r\n\r\nvar ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\r\nvar Set = goog.require('goog.structs.Set');\r\nvar Wire = goog.require('goog.labs.net.webChannel.Wire');\r\nvar array = goog.require('goog.array');\r\nvar googString = goog.require('goog.string');\r\n\r\n\r\n/**\r\n * This class represents the state of all forward channel requests.\r\n *\r\n * @param {number=} opt_maxPoolSize The maximum pool size.\r\n *\r\n * @struct @constructor @final\r\n */\r\nvar ForwardChannelRequestPool = function(opt_maxPoolSize) {\r\n /**\r\n * The max pool size as configured.\r\n *\r\n * @private {number}\r\n */\r\n this.maxPoolSizeConfigured_ =\r\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\r\n\r\n /**\r\n * The current size limit of the request pool. This limit is meant to be\r\n * read-only after the channel is fully opened.\r\n *\r\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\r\n * configurable.\r\n *\r\n * @private {number}\r\n */\r\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\r\n this.maxPoolSizeConfigured_ :\r\n 1;\r\n\r\n /**\r\n * The container for all the pending request objects.\r\n *\r\n * @private {Set<ChannelRequest>}\r\n */\r\n this.requestPool_ = null;\r\n\r\n if (this.maxSize_ > 1) {\r\n this.requestPool_ = new Set();\r\n }\r\n\r\n /**\r\n * The single request object when the pool size is limited to one.\r\n *\r\n * @private {ChannelRequest}\r\n */\r\n this.request_ = null;\r\n\r\n /**\r\n * Saved pending messages when the pool is cancelled.\r\n *\r\n * @private {!Array<Wire.QueuedMap>}\r\n */\r\n this.pendingMessages_ = [];\r\n};\r\n\r\n\r\n/**\r\n * The default size limit of the request pool.\r\n *\r\n * @private {number}\r\n */\r\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\r\n\r\n\r\n/**\r\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\r\n * as a fallback and will always return false for other browsers where\r\n * PerformanceNavigationTiming is not available.\r\n * @private\r\n */\r\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\r\n if (goog.global.PerformanceNavigationTiming) {\r\n var entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\r\n goog.global.performance.getEntriesByType('navigation'));\r\n return entrys.length > 0 &&\r\n (entrys[0].nextHopProtocol == 'hq' ||\r\n entrys[0].nextHopProtocol == 'h2');\r\n }\r\n return !!(\r\n goog.global.chrome && goog.global.chrome.loadTimes &&\r\n goog.global.chrome.loadTimes() &&\r\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\r\n};\r\n\r\n\r\n/**\r\n * Once we know the client protocol (from the handshake), check if we need\r\n * enable the request pool accordingly. This is more robust than using\r\n * browser-internal APIs (specific to Chrome).\r\n *\r\n * @param {string} clientProtocol The client protocol\r\n */\r\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\r\n clientProtocol) {\r\n if (this.requestPool_) {\r\n return;\r\n }\r\n\r\n if (googString.contains(clientProtocol, 'spdy') ||\r\n googString.contains(clientProtocol, 'quic') ||\r\n googString.contains(clientProtocol, 'h2')) {\r\n this.maxSize_ = this.maxPoolSizeConfigured_;\r\n this.requestPool_ = new Set();\r\n if (this.request_) {\r\n this.addRequest(this.request_);\r\n this.request_ = null;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} True if the pool is full.\r\n */\r\nForwardChannelRequestPool.prototype.isFull = function() {\r\n if (this.request_) {\r\n return true;\r\n }\r\n\r\n if (this.requestPool_) {\r\n return this.requestPool_.getCount() >= this.maxSize_;\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The current size limit.\r\n */\r\nForwardChannelRequestPool.prototype.getMaxSize = function() {\r\n return this.maxSize_;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of pending requests in the pool.\r\n */\r\nForwardChannelRequestPool.prototype.getRequestCount = function() {\r\n if (this.request_) {\r\n return 1;\r\n }\r\n\r\n if (this.requestPool_) {\r\n return this.requestPool_.getCount();\r\n }\r\n\r\n return 0;\r\n};\r\n\r\n\r\n/**\r\n * @param {ChannelRequest} req The channel request.\r\n * @return {boolean} True if the request is a included inside the pool.\r\n */\r\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\r\n if (this.request_) {\r\n return this.request_ == req;\r\n }\r\n\r\n if (this.requestPool_) {\r\n return this.requestPool_.contains(req);\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Adds a new request to the pool.\r\n *\r\n * @param {!ChannelRequest} req The new channel request.\r\n */\r\nForwardChannelRequestPool.prototype.addRequest = function(req) {\r\n if (this.requestPool_) {\r\n this.requestPool_.add(req);\r\n } else {\r\n this.request_ = req;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes the given request from the pool.\r\n *\r\n * @param {ChannelRequest} req The channel request.\r\n * @return {boolean} Whether the request has been removed from the pool.\r\n */\r\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\r\n if (this.request_ && this.request_ == req) {\r\n this.request_ = null;\r\n return true;\r\n }\r\n\r\n if (this.requestPool_ && this.requestPool_.contains(req)) {\r\n this.requestPool_.remove(req);\r\n return true;\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Clears the pool and cancel all the pending requests.\r\n */\r\nForwardChannelRequestPool.prototype.cancel = function() {\r\n // save any pending messages\r\n this.pendingMessages_ = this.getPendingMessages();\r\n\r\n if (this.request_) {\r\n this.request_.cancel();\r\n this.request_ = null;\r\n return;\r\n }\r\n\r\n if (this.requestPool_ && !this.requestPool_.isEmpty()) {\r\n array.forEach(this.requestPool_.getValues(), function(val) {\r\n val.cancel();\r\n });\r\n this.requestPool_.clear();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether there are any pending requests.\r\n */\r\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\r\n return (this.request_ != null) ||\r\n (this.requestPool_ != null && !this.requestPool_.isEmpty());\r\n};\r\n\r\n\r\n/**\r\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\r\n * as a new array.\r\n */\r\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\r\n if (this.request_ != null) {\r\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\r\n }\r\n\r\n if (this.requestPool_ != null && !this.requestPool_.isEmpty()) {\r\n var result = this.pendingMessages_;\r\n array.forEach(this.requestPool_.getValues(), function(val) {\r\n result = result.concat(val.getPendingMessages());\r\n });\r\n return result;\r\n }\r\n\r\n return array.clone(this.pendingMessages_);\r\n};\r\n\r\n\r\n/**\r\n * Records pending messages, e.g. when a request receives a failed response.\r\n *\r\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\r\n */\r\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\r\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\r\n};\r\n\r\n\r\n/**\r\n * Clears any recorded pending messages.\r\n */\r\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\r\n this.pendingMessages_.length = 0;\r\n};\r\n\r\n\r\n/**\r\n * Cancels all pending requests and force the completion of channel requests.\r\n *\r\n * Need go through the standard onRequestComplete logic to expose the max-retry\r\n * failure in the standard way.\r\n *\r\n * @param {function(!ChannelRequest)} onComplete The completion callback.\r\n * @return {boolean} true if any request has been forced to complete.\r\n */\r\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\r\n if (this.request_ != null) {\r\n this.request_.cancel();\r\n onComplete(this.request_);\r\n return true;\r\n }\r\n\r\n if (this.requestPool_ && !this.requestPool_.isEmpty()) {\r\n array.forEach(this.requestPool_.getValues(), function(val) {\r\n val.cancel();\r\n onComplete(val);\r\n });\r\n return true;\r\n }\r\n\r\n return false;\r\n};\r\n\r\nexports = ForwardChannelRequestPool;\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Definition of various formatters for logging. Please minimize\r\n * dependencies this file has on other closure classes as any dependency it\r\n * takes won't be able to use the logging infrastructure.\r\n *\r\n */\r\n\r\ngoog.provide('goog.debug.Formatter');\r\ngoog.provide('goog.debug.HtmlFormatter');\r\ngoog.provide('goog.debug.TextFormatter');\r\n\r\ngoog.require('goog.debug');\r\ngoog.require('goog.debug.Logger');\r\ngoog.require('goog.debug.RelativeTimeProvider');\r\ngoog.require('goog.html.SafeHtml');\r\ngoog.require('goog.html.SafeUrl');\r\ngoog.require('goog.html.uncheckedconversions');\r\ngoog.require('goog.string.Const');\r\n\r\n\r\n\r\n/**\r\n * Base class for Formatters. A Formatter is used to format a LogRecord into\r\n * something that can be displayed to the user.\r\n *\r\n * @param {string=} opt_prefix The prefix to place before text records.\r\n * @constructor\r\n */\r\ngoog.debug.Formatter = function(opt_prefix) {\r\n this.prefix_ = opt_prefix || '';\r\n\r\n /**\r\n * A provider that returns the relative start time.\r\n * @type {goog.debug.RelativeTimeProvider}\r\n * @private\r\n */\r\n this.startTimeProvider_ =\r\n goog.debug.RelativeTimeProvider.getDefaultInstance();\r\n};\r\n\r\n\r\n/**\r\n * Whether to append newlines to the end of formatted log records.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.appendNewline = true;\r\n\r\n\r\n/**\r\n * Whether to show absolute time in the DebugWindow.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showAbsoluteTime = true;\r\n\r\n\r\n/**\r\n * Whether to show relative time in the DebugWindow.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showRelativeTime = true;\r\n\r\n\r\n/**\r\n * Whether to show the logger name in the DebugWindow.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showLoggerName = true;\r\n\r\n\r\n/**\r\n * Whether to show the logger exception text.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showExceptionText = false;\r\n\r\n\r\n/**\r\n * Whether to show the severity level.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showSeverityLevel = false;\r\n\r\n\r\n/**\r\n * Formats a record.\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {string} The formatted string.\r\n */\r\ngoog.debug.Formatter.prototype.formatRecord = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Formats a record as SafeHtml.\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {!goog.html.SafeHtml} The formatted string as SafeHtml.\r\n */\r\ngoog.debug.Formatter.prototype.formatRecordAsHtml = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Sets the start time provider. By default, this is the default instance\r\n * but can be changed.\r\n * @param {goog.debug.RelativeTimeProvider} provider The provider to use.\r\n */\r\ngoog.debug.Formatter.prototype.setStartTimeProvider = function(provider) {\r\n this.startTimeProvider_ = provider;\r\n};\r\n\r\n\r\n/**\r\n * Returns the start time provider. By default, this is the default instance\r\n * but can be changed.\r\n * @return {goog.debug.RelativeTimeProvider} The start time provider.\r\n */\r\ngoog.debug.Formatter.prototype.getStartTimeProvider = function() {\r\n return this.startTimeProvider_;\r\n};\r\n\r\n\r\n/**\r\n * Resets the start relative time.\r\n */\r\ngoog.debug.Formatter.prototype.resetRelativeTimeStart = function() {\r\n this.startTimeProvider_.reset();\r\n};\r\n\r\n\r\n/**\r\n * Returns a string for the time/date of the LogRecord.\r\n * @param {goog.debug.LogRecord} logRecord The record to get a time stamp for.\r\n * @return {string} A string representation of the time/date of the LogRecord.\r\n * @private\r\n */\r\ngoog.debug.Formatter.getDateTimeStamp_ = function(logRecord) {\r\n var time = new Date(logRecord.getMillis());\r\n return goog.debug.Formatter.getTwoDigitString_((time.getFullYear() - 2000)) +\r\n goog.debug.Formatter.getTwoDigitString_((time.getMonth() + 1)) +\r\n goog.debug.Formatter.getTwoDigitString_(time.getDate()) + ' ' +\r\n goog.debug.Formatter.getTwoDigitString_(time.getHours()) + ':' +\r\n goog.debug.Formatter.getTwoDigitString_(time.getMinutes()) + ':' +\r\n goog.debug.Formatter.getTwoDigitString_(time.getSeconds()) + '.' +\r\n goog.debug.Formatter.getTwoDigitString_(\r\n Math.floor(time.getMilliseconds() / 10));\r\n};\r\n\r\n\r\n/**\r\n * Returns the number as a two-digit string, meaning it prepends a 0 if the\r\n * number if less than 10.\r\n * @param {number} n The number to format.\r\n * @return {string} A two-digit string representation of `n`.\r\n * @private\r\n */\r\ngoog.debug.Formatter.getTwoDigitString_ = function(n) {\r\n if (n < 10) {\r\n return '0' + n;\r\n }\r\n return String(n);\r\n};\r\n\r\n\r\n/**\r\n * Returns a string for the number of seconds relative to the start time.\r\n * Prepads with spaces so that anything less than 1000 seconds takes up the\r\n * same number of characters for better formatting.\r\n * @param {goog.debug.LogRecord} logRecord The log to compare time to.\r\n * @param {number} relativeTimeStart The start time to compare to.\r\n * @return {string} The number of seconds of the LogRecord relative to the\r\n * start time.\r\n * @private\r\n */\r\ngoog.debug.Formatter.getRelativeTime_ = function(logRecord, relativeTimeStart) {\r\n var ms = logRecord.getMillis() - relativeTimeStart;\r\n var sec = ms / 1000;\r\n var str = sec.toFixed(3);\r\n\r\n var spacesToPrepend = 0;\r\n if (sec < 1) {\r\n spacesToPrepend = 2;\r\n } else {\r\n while (sec < 100) {\r\n spacesToPrepend++;\r\n sec *= 10;\r\n }\r\n }\r\n while (spacesToPrepend-- > 0) {\r\n str = ' ' + str;\r\n }\r\n return str;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Formatter that returns formatted html. See formatRecord for the classes\r\n * it uses for various types of formatted output.\r\n *\r\n * @param {string=} opt_prefix The prefix to place before text records.\r\n * @constructor\r\n * @extends {goog.debug.Formatter}\r\n */\r\ngoog.debug.HtmlFormatter = function(opt_prefix) {\r\n goog.debug.Formatter.call(this, opt_prefix);\r\n};\r\ngoog.inherits(goog.debug.HtmlFormatter, goog.debug.Formatter);\r\n\r\n\r\n/**\r\n * Exposes an exception that has been caught by a try...catch and outputs the\r\n * error as HTML with a stack trace.\r\n *\r\n * @param {*} err Error object or string.\r\n * @param {?Function=} fn If provided, when collecting the stack trace all\r\n * frames above the topmost call to this function, including that call,\r\n * will be left out of the stack trace.\r\n * @return {string} Details of exception, as HTML.\r\n */\r\ngoog.debug.HtmlFormatter.exposeException = function(err, fn) {\r\n var html = goog.debug.HtmlFormatter.exposeExceptionAsHtml(err, fn);\r\n return goog.html.SafeHtml.unwrap(html);\r\n};\r\n\r\n\r\n/**\r\n * Exposes an exception that has been caught by a try...catch and outputs the\r\n * error with a stack trace.\r\n *\r\n * @param {*} err Error object or string.\r\n * @param {?Function=} fn If provided, when collecting the stack trace all\r\n * frames above the topmost call to this function, including that call,\r\n * will be left out of the stack trace.\r\n * @return {!goog.html.SafeHtml} Details of exception.\r\n */\r\ngoog.debug.HtmlFormatter.exposeExceptionAsHtml = function(err, fn) {\r\n try {\r\n var e = goog.debug.normalizeErrorObject(err);\r\n // Create the error message\r\n var viewSourceUrl =\r\n goog.debug.HtmlFormatter.createViewSourceUrl_(e.fileName);\r\n var error = goog.html.SafeHtml.concat(\r\n goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n 'Message: ' + e.message + '\\nUrl: '),\r\n goog.html.SafeHtml.create(\r\n 'a', {href: viewSourceUrl, target: '_new'}, e.fileName),\r\n goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n '\\nLine: ' + e.lineNumber + '\\n\\nBrowser stack:\\n' + e.stack +\r\n '-> ' +\r\n '[end]\\n\\nJS stack traversal:\\n' + goog.debug.getStacktrace(fn) +\r\n '-> '));\r\n return error;\r\n } catch (e2) {\r\n return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n 'Exception trying to expose exception! You win, we lose. ' + e2);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {?string=} fileName\r\n * @return {!goog.html.SafeUrl} SafeUrl with view-source scheme, pointing at\r\n * fileName.\r\n * @private\r\n */\r\ngoog.debug.HtmlFormatter.createViewSourceUrl_ = function(fileName) {\r\n if (!goog.isDefAndNotNull(fileName)) {\r\n fileName = '';\r\n }\r\n if (!/^https?:\\/\\//i.test(fileName)) {\r\n return goog.html.SafeUrl.fromConstant(\r\n goog.string.Const.from('sanitizedviewsrc'));\r\n }\r\n var sanitizedFileName = goog.html.SafeUrl.sanitize(fileName);\r\n return goog.html.uncheckedconversions\r\n .safeUrlFromStringKnownToSatisfyTypeContract(\r\n goog.string.Const.from('view-source scheme plus HTTP/HTTPS URL'),\r\n 'view-source:' + goog.html.SafeUrl.unwrap(sanitizedFileName));\r\n};\r\n\r\n\r\n\r\n/**\r\n * Whether to show the logger exception text\r\n * @type {boolean}\r\n * @override\r\n */\r\ngoog.debug.HtmlFormatter.prototype.showExceptionText = true;\r\n\r\n\r\n/**\r\n * Formats a record\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {string} The formatted string as html.\r\n * @override\r\n */\r\ngoog.debug.HtmlFormatter.prototype.formatRecord = function(logRecord) {\r\n if (!logRecord) {\r\n return '';\r\n }\r\n // OK not to use goog.html.SafeHtml.unwrap() here.\r\n return this.formatRecordAsHtml(logRecord).getTypedStringValue();\r\n};\r\n\r\n\r\n/**\r\n * Formats a record.\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {!goog.html.SafeHtml} The formatted string as SafeHtml.\r\n * @override\r\n */\r\ngoog.debug.HtmlFormatter.prototype.formatRecordAsHtml = function(logRecord) {\r\n if (!logRecord) {\r\n return goog.html.SafeHtml.EMPTY;\r\n }\r\n\r\n var className;\r\n switch (logRecord.getLevel().value) {\r\n case goog.debug.Logger.Level.SHOUT.value:\r\n className = 'dbg-sh';\r\n break;\r\n case goog.debug.Logger.Level.SEVERE.value:\r\n className = 'dbg-sev';\r\n break;\r\n case goog.debug.Logger.Level.WARNING.value:\r\n className = 'dbg-w';\r\n break;\r\n case goog.debug.Logger.Level.INFO.value:\r\n className = 'dbg-i';\r\n break;\r\n case goog.debug.Logger.Level.FINE.value:\r\n default:\r\n className = 'dbg-f';\r\n break;\r\n }\r\n\r\n // HTML for user defined prefix, time, logger name, and severity.\r\n var sb = [];\r\n sb.push(this.prefix_, ' ');\r\n if (this.showAbsoluteTime) {\r\n sb.push('[', goog.debug.Formatter.getDateTimeStamp_(logRecord), '] ');\r\n }\r\n if (this.showRelativeTime) {\r\n sb.push(\r\n '[', goog.debug.Formatter.getRelativeTime_(\r\n logRecord, this.startTimeProvider_.get()),\r\n 's] ');\r\n }\r\n if (this.showLoggerName) {\r\n sb.push('[', logRecord.getLoggerName(), '] ');\r\n }\r\n if (this.showSeverityLevel) {\r\n sb.push('[', logRecord.getLevel().name, '] ');\r\n }\r\n var fullPrefixHtml =\r\n goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(sb.join(''));\r\n\r\n // HTML for exception text and log record.\r\n var exceptionHtml = goog.html.SafeHtml.EMPTY;\r\n if (this.showExceptionText && logRecord.getException()) {\r\n exceptionHtml = goog.html.SafeHtml.concat(\r\n goog.html.SafeHtml.BR,\r\n goog.debug.HtmlFormatter.exposeExceptionAsHtml(\r\n logRecord.getException()));\r\n }\r\n var logRecordHtml = goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n logRecord.getMessage());\r\n var recordAndExceptionHtml = goog.html.SafeHtml.create(\r\n 'span', {'class': className},\r\n goog.html.SafeHtml.concat(logRecordHtml, exceptionHtml));\r\n\r\n\r\n // Combine both pieces of HTML and, if needed, append a final newline.\r\n var html;\r\n if (this.appendNewline) {\r\n html = goog.html.SafeHtml.concat(\r\n fullPrefixHtml, recordAndExceptionHtml, goog.html.SafeHtml.BR);\r\n } else {\r\n html = goog.html.SafeHtml.concat(fullPrefixHtml, recordAndExceptionHtml);\r\n }\r\n return html;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Formatter that returns formatted plain text\r\n *\r\n * @param {string=} opt_prefix The prefix to place before text records.\r\n * @constructor\r\n * @extends {goog.debug.Formatter}\r\n * @final\r\n */\r\ngoog.debug.TextFormatter = function(opt_prefix) {\r\n goog.debug.Formatter.call(this, opt_prefix);\r\n};\r\ngoog.inherits(goog.debug.TextFormatter, goog.debug.Formatter);\r\n\r\n\r\n/**\r\n * Formats a record as text\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {string} The formatted string.\r\n * @override\r\n */\r\ngoog.debug.TextFormatter.prototype.formatRecord = function(logRecord) {\r\n var sb = [];\r\n sb.push(this.prefix_, ' ');\r\n if (this.showAbsoluteTime) {\r\n sb.push('[', goog.debug.Formatter.getDateTimeStamp_(logRecord), '] ');\r\n }\r\n if (this.showRelativeTime) {\r\n sb.push(\r\n '[', goog.debug.Formatter.getRelativeTime_(\r\n logRecord, this.startTimeProvider_.get()),\r\n 's] ');\r\n }\r\n\r\n if (this.showLoggerName) {\r\n sb.push('[', logRecord.getLoggerName(), '] ');\r\n }\r\n if (this.showSeverityLevel) {\r\n sb.push('[', logRecord.getLevel().name, '] ');\r\n }\r\n sb.push(logRecord.getMessage());\r\n if (this.showExceptionText) {\r\n var exception = logRecord.getException();\r\n if (exception) {\r\n var exceptionText =\r\n exception instanceof Error ? exception.message : exception.toString();\r\n sb.push('\\n', exceptionText);\r\n }\r\n }\r\n if (this.appendNewline) {\r\n sb.push('\\n');\r\n }\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Formats a record as text\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {!goog.html.SafeHtml} The formatted string as SafeHtml. This is\r\n * just an HTML-escaped version of the text obtained from formatRecord().\r\n * @override\r\n */\r\ngoog.debug.TextFormatter.prototype.formatRecordAsHtml = function(logRecord) {\r\n return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n goog.debug.TextFormatter.prototype.formatRecord(logRecord));\r\n};\r\n","// Copyright 2012 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n\r\n/**\r\n * @fileoverview Defines a class for parsing JSON using the browser's built in\r\n * JSON library.\r\n */\r\n\r\ngoog.provide('goog.json.NativeJsonProcessor');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.json.Processor');\r\n\r\n\r\n\r\n/**\r\n * A class that parses and stringifies JSON using the browser's built-in JSON\r\n * library, if it is available.\r\n *\r\n * Note that the native JSON api has subtle differences across browsers, so\r\n * use this implementation with care. See json_test#assertSerialize\r\n * for details on the differences from goog.json.\r\n *\r\n * This implementation is signficantly faster than goog.json, at least on\r\n * Chrome. See json_perf.html for a perf test showing the difference.\r\n *\r\n * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during\r\n * serialization.\r\n * @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during\r\n * parsing.\r\n * @constructor\r\n * @implements {goog.json.Processor}\r\n * @final\r\n */\r\ngoog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) {\r\n goog.asserts.assert(goog.isDef(goog.global['JSON']), 'JSON not defined');\r\n\r\n /**\r\n * @type {goog.json.Replacer|null|undefined}\r\n * @private\r\n */\r\n this.replacer_ = opt_replacer;\r\n\r\n /**\r\n * @type {goog.json.Reviver|null|undefined}\r\n * @private\r\n */\r\n this.reviver_ = opt_reviver;\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.json.NativeJsonProcessor.prototype.stringify = function(object) {\r\n return goog.global['JSON'].stringify(object, this.replacer_);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.json.NativeJsonProcessor.prototype.parse = function(s) {\r\n return goog.global['JSON'].parse(s, this.reviver_);\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\r\n * to support pluggable wire-format to improve wire efficiency and to enable\r\n * binary encoding. Such support will require an interface class, which\r\n * will be added later.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.WireV8');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.json');\r\ngoog.require('goog.json.NativeJsonProcessor');\r\ngoog.require('goog.labs.net.webChannel.Wire');\r\ngoog.require('goog.structs');\r\n\r\ngoog.forwardDeclare('goog.structs.Map');\r\n\r\n\r\n\r\n/**\r\n * The v8 codec class.\r\n *\r\n * @constructor\r\n * @struct\r\n */\r\ngoog.labs.net.webChannel.WireV8 = function() {\r\n /**\r\n * Parser for a response payload. The parser should return an array.\r\n * @private {!goog.string.Parser}\r\n */\r\n this.parser_ = new goog.json.NativeJsonProcessor();\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WireV8 = goog.labs.net.webChannel.WireV8;\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\n\r\n\r\n/**\r\n * Encodes a standalone message into the wire format.\r\n *\r\n * May throw exception if the message object contains any invalid elements.\r\n *\r\n * @param {!Object|!goog.structs.Map} message The message data.\r\n * V8 only support JS objects (or Map).\r\n * @param {!Array<string>} buffer The text buffer to write the message to.\r\n * @param {string=} opt_prefix The prefix for each field of the object.\r\n */\r\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\r\n var prefix = opt_prefix || '';\r\n try {\r\n goog.structs.forEach(message, function(value, key) {\r\n var encodedValue = value;\r\n if (goog.isObject(value)) {\r\n encodedValue = goog.json.serialize(value);\r\n } // keep the fast-path for primitive types\r\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\r\n });\r\n } catch (ex) {\r\n // We send a map here because lots of the retry logic relies on map IDs,\r\n // so we have to send something (possibly redundant).\r\n buffer.push(\r\n prefix + 'type' +\r\n '=' + encodeURIComponent('_badmap'));\r\n throw ex;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Encodes all the buffered messages of the forward channel.\r\n *\r\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\r\n * V8 only support JS objects.\r\n * @param {number} count The number of messages to be encoded.\r\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\r\n * @return {string} the encoded messages\r\n */\r\nWireV8.prototype.encodeMessageQueue = function(\r\n messageQueue, count, badMapHandler) {\r\n var offset = -1;\r\n while (true) {\r\n var sb = ['count=' + count];\r\n // To save a bit of bandwidth, specify the base mapId and the rest as\r\n // offsets from it.\r\n if (offset == -1) {\r\n if (count > 0) {\r\n offset = messageQueue[0].mapId;\r\n sb.push('ofs=' + offset);\r\n } else {\r\n offset = 0;\r\n }\r\n } else {\r\n sb.push('ofs=' + offset);\r\n }\r\n var done = true;\r\n for (var i = 0; i < count; i++) {\r\n var mapId = messageQueue[i].mapId;\r\n var map = messageQueue[i].map;\r\n mapId -= offset;\r\n if (mapId < 0) {\r\n // redo the encoding in case of retry/reordering, plus extra space\r\n offset = Math.max(0, messageQueue[i].mapId - 100);\r\n done = false;\r\n continue;\r\n }\r\n try {\r\n this.encodeMessage(map, sb, 'req' + mapId + '_');\r\n } catch (ex) {\r\n if (badMapHandler) {\r\n badMapHandler(map);\r\n }\r\n }\r\n }\r\n if (done) {\r\n return sb.join('&');\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Decodes a standalone message received from the wire. May throw exception\r\n * if text is ill-formatted.\r\n *\r\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\r\n * and eval() is disallowed in Chrome apps too.\r\n *\r\n * Invalid JS literals include null array elements, quotas etc.\r\n *\r\n * @param {string} messageText The string content as received from the wire.\r\n * @return {*} The decoded message object.\r\n */\r\nWireV8.prototype.decodeMessage = function(messageText) {\r\n var response = this.parser_.parse(messageText);\r\n goog.asserts.assert(goog.isArray(response)); // throw exception\r\n return response;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utility functions for managing networking, such as\r\n * testing network connectivity.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.netUtils');\r\n\r\ngoog.require('goog.Uri');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\n\r\ngoog.scope(function() {\r\nvar netUtils = goog.labs.net.webChannel.netUtils;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\n\r\n\r\n/**\r\n * Default timeout to allow for URI pings.\r\n * @type {number}\r\n */\r\nnetUtils.NETWORK_TIMEOUT = 10000;\r\n\r\n\r\n/**\r\n * Pings the network with an image URI to check if an error is a server error\r\n * or user's network error.\r\n *\r\n * The caller needs to add a 'rand' parameter to make sure the response is\r\n * not fulfilled by browser cache.\r\n *\r\n * @param {function(boolean)} callback The function to call back with results.\r\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\r\n * test.\r\n */\r\nnetUtils.testNetwork = function(callback, opt_imageUri) {\r\n var uri = opt_imageUri;\r\n if (!uri) {\r\n // default google.com image\r\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\r\n\r\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\r\n uri.setScheme('https'); // e.g. chrome-extension\r\n }\r\n uri.makeUnique();\r\n }\r\n\r\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\r\n};\r\n\r\n\r\n/**\r\n * Test loading the given image, retrying if necessary.\r\n * @param {string} url URL to the image.\r\n * @param {number} timeout Milliseconds before giving up.\r\n * @param {function(boolean)} callback Function to call with results.\r\n * @param {number} retries The number of times to retry.\r\n * @param {!WebChannelDebug} channelDebug The debug object\r\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\r\n * between retries - defaults to 0.\r\n */\r\nnetUtils.testLoadImageWithRetries = function(\r\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\r\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\r\n if (retries == 0) {\r\n // no more retries, give up\r\n callback(false);\r\n return;\r\n }\r\n\r\n var pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\r\n retries--;\r\n netUtils.testLoadImage(url, timeout, function(succeeded) {\r\n if (succeeded) {\r\n callback(true);\r\n } else {\r\n // try again\r\n goog.global.setTimeout(function() {\r\n netUtils.testLoadImageWithRetries(\r\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\r\n }, pauseBetweenRetries);\r\n }\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Test loading the given image.\r\n * @param {string} url URL to the image.\r\n * @param {number} timeout Milliseconds before giving up.\r\n * @param {function(boolean)} callback Function to call with results.\r\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\r\n */\r\nnetUtils.testLoadImage = function(url, timeout, callback) {\r\n var channelDebug = new WebChannelDebug();\r\n channelDebug.debug('TestLoadImage: loading ' + url);\r\n if (goog.global.Image) {\r\n var img = new Image();\r\n img.onload = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\r\n true, callback);\r\n img.onerror = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\r\n false, callback);\r\n img.onabort = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\r\n false, callback);\r\n img.ontimeout = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\r\n false, callback);\r\n\r\n goog.global.setTimeout(function() {\r\n if (img.ontimeout) {\r\n img.ontimeout();\r\n }\r\n }, timeout);\r\n img.src = url;\r\n } else {\r\n // log ERROR_OTHER from environements where Image is not supported\r\n callback(false);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Wrap the image callback with debug and cleanup logic.\r\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\r\n * @param {!Image} img The image element.\r\n * @param {string} debugText The debug text.\r\n * @param {boolean} result The result of image loading.\r\n * @param {function(boolean)} callback The image callback.\r\n * @private\r\n */\r\nnetUtils.imageCallback_ = function(\r\n channelDebug, img, debugText, result, callback) {\r\n try {\r\n channelDebug.debug(debugText);\r\n netUtils.clearImageCallbacks_(img);\r\n callback(result);\r\n } catch (e) {\r\n channelDebug.dumpException(e);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears handlers to avoid memory leaks.\r\n * @param {Image} img The image to clear handlers from.\r\n * @private\r\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\r\n */\r\nnetUtils.clearImageCallbacks_ = function(img) {\r\n img.onload = null;\r\n img.onerror = null;\r\n img.onabort = null;\r\n img.ontimeout = null;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n\r\n/**\r\n * @fileoverview Utility to attempt native JSON processing, falling back to\r\n * goog.json if not available.\r\n *\r\n * This is intended as a drop-in for current users of goog.json who want\r\n * to take advantage of native JSON if present.\r\n *\r\n * @author nnaze@google.com (Nathan Naze)\r\n */\r\n\r\ngoog.provide('goog.json.hybrid');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.json');\r\n\r\n\r\n/**\r\n * Attempts to serialize the JSON string natively, falling back to\r\n * `goog.json.serialize` if unsuccessful.\r\n * @param {!Object} obj JavaScript object to serialize to JSON.\r\n * @return {string} Resulting JSON string.\r\n */\r\ngoog.json.hybrid.stringify =\r\n goog.json.USE_NATIVE_JSON ? goog.global['JSON']['stringify'] : function(\r\n obj) {\r\n if (goog.global.JSON) {\r\n try {\r\n return goog.global.JSON.stringify(obj);\r\n } catch (e) {\r\n // Native serialization failed. Fall through to retry with\r\n // goog.json.serialize.\r\n }\r\n }\r\n\r\n return goog.json.serialize(obj);\r\n };\r\n\r\n\r\n/**\r\n * Attempts to parse the JSON string natively, falling back to\r\n * the supplied `fallbackParser` if unsuccessful.\r\n * @param {string} jsonString JSON string to parse.\r\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\r\n * if native\r\n * @return {?Object} Resulting JSON object.\r\n * @private\r\n */\r\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\r\n if (goog.global.JSON) {\r\n try {\r\n var obj = goog.global.JSON.parse(jsonString);\r\n goog.asserts.assert(typeof obj == 'object');\r\n return /** @type {?Object} */ (obj);\r\n } catch (e) {\r\n // Native parse failed. Fall through to retry with goog.json.parse.\r\n }\r\n }\r\n\r\n return fallbackParser(jsonString);\r\n};\r\n\r\n\r\n/**\r\n * Attempts to parse the JSON string natively, falling back to\r\n * `goog.json.parse` if unsuccessful.\r\n * @param {string} jsonString JSON string to parse.\r\n * @return {?Object} Resulting JSON object.\r\n */\r\ngoog.json.hybrid.parse =\r\n goog.json.USE_NATIVE_JSON ? goog.global['JSON']['parse'] : function(\r\n jsonString) {\r\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\r\n };\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Wrapper class for handling XmlHttpRequests.\r\n *\r\n * One off requests can be sent through goog.net.XhrIo.send() or an\r\n * instance can be created to send multiple requests. Each request uses its\r\n * own XmlHttpRequest object and handles clearing of the event callback to\r\n * ensure no leaks.\r\n *\r\n * XhrIo is event based, it dispatches events on success, failure, finishing,\r\n * ready-state change, or progress (download and upload).\r\n *\r\n * The ready-state or timeout event fires first, followed by\r\n * a generic completed event. Then the abort, error, or success event\r\n * is fired as appropriate. Progress events are fired as they are\r\n * received. Lastly, the ready event will fire to indicate that the\r\n * object may be used to make another request.\r\n *\r\n * The error event may also be called before completed and\r\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\r\n *\r\n * This class does not support multiple requests, queuing, or prioritization.\r\n *\r\n * When progress events are supported by the browser, and progress is\r\n * enabled via .setProgressEventsEnabled(true), the\r\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\r\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\r\n * will be fired for download and upload progress respectively.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.net.XhrIo');\r\ngoog.provide('goog.net.XhrIo.ResponseType');\r\n\r\ngoog.require('goog.Timer');\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.debug.entryPointRegistry');\r\ngoog.require('goog.events.EventTarget');\r\ngoog.require('goog.json.hybrid');\r\ngoog.require('goog.log');\r\ngoog.require('goog.net.ErrorCode');\r\ngoog.require('goog.net.EventType');\r\ngoog.require('goog.net.HttpStatus');\r\ngoog.require('goog.net.XmlHttp');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.Map');\r\ngoog.require('goog.uri.utils');\r\ngoog.require('goog.userAgent');\r\n\r\ngoog.forwardDeclare('goog.Uri');\r\n\r\ngoog.scope(function() {\r\n\r\n/**\r\n * Basic class for handling XMLHttpRequests.\r\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\r\n * creating XMLHttpRequest objects.\r\n * @constructor\r\n * @extends {goog.events.EventTarget}\r\n */\r\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\r\n XhrIo.base(this, 'constructor');\r\n\r\n /**\r\n * Map of default headers to add to every request, use:\r\n * XhrIo.headers.set(name, value)\r\n * @type {!goog.structs.Map}\r\n */\r\n this.headers = new goog.structs.Map();\r\n\r\n /**\r\n * Optional XmlHttpFactory\r\n * @private {goog.net.XmlHttpFactory}\r\n */\r\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\r\n\r\n /**\r\n * Whether XMLHttpRequest is active. A request is active from the time send()\r\n * is called until onReadyStateChange() is complete, or error() or abort()\r\n * is called.\r\n * @private {boolean}\r\n */\r\n this.active_ = false;\r\n\r\n /**\r\n * The XMLHttpRequest object that is being used for the transfer.\r\n * @private {?goog.net.XhrLike.OrNative}\r\n */\r\n this.xhr_ = null;\r\n\r\n /**\r\n * The options to use with the current XMLHttpRequest object.\r\n * @private {?Object}\r\n */\r\n this.xhrOptions_ = null;\r\n\r\n /**\r\n * Last URL that was requested.\r\n * @private {string|goog.Uri}\r\n */\r\n this.lastUri_ = '';\r\n\r\n /**\r\n * Method for the last request.\r\n * @private {string}\r\n */\r\n this.lastMethod_ = '';\r\n\r\n /**\r\n * Last error code.\r\n * @private {!goog.net.ErrorCode}\r\n */\r\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\r\n\r\n /**\r\n * Last error message.\r\n * @private {Error|string}\r\n */\r\n this.lastError_ = '';\r\n\r\n /**\r\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\r\n * happen in IE when it does a synchronous load and one error is handled in\r\n * the ready statte change and one is handled due to send() throwing an\r\n * exception.\r\n * @private {boolean}\r\n */\r\n this.errorDispatched_ = false;\r\n\r\n /**\r\n * Used to make sure we don't fire the complete event from inside a send call.\r\n * @private {boolean}\r\n */\r\n this.inSend_ = false;\r\n\r\n /**\r\n * Used in determining if a call to {@link #onReadyStateChange_} is from\r\n * within a call to this.xhr_.open.\r\n * @private {boolean}\r\n */\r\n this.inOpen_ = false;\r\n\r\n /**\r\n * Used in determining if a call to {@link #onReadyStateChange_} is from\r\n * within a call to this.xhr_.abort.\r\n * @private {boolean}\r\n */\r\n this.inAbort_ = false;\r\n\r\n /**\r\n * Number of milliseconds after which an incomplete request will be aborted\r\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\r\n * is set.\r\n * @private {number}\r\n */\r\n this.timeoutInterval_ = 0;\r\n\r\n /**\r\n * Timer to track request timeout.\r\n * @private {?number}\r\n */\r\n this.timeoutId_ = null;\r\n\r\n /**\r\n * The requested type for the response. The empty string means use the default\r\n * XHR behavior.\r\n * @private {goog.net.XhrIo.ResponseType}\r\n */\r\n this.responseType_ = ResponseType.DEFAULT;\r\n\r\n /**\r\n * Whether a \"credentialed\" request is to be sent (one that is aware of\r\n * cookies and authentication). This is applicable only for cross-domain\r\n * requests and more recent browsers that support this part of the HTTP Access\r\n * Control standard.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\r\n *\r\n * @private {boolean}\r\n */\r\n this.withCredentials_ = false;\r\n\r\n /**\r\n * Whether progress events are enabled for this request. This is\r\n * disabled by default because setting a progress event handler\r\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\r\n * even in cases where a pre-flight request would not otherwise be\r\n * sent.\r\n *\r\n * @see http://xhr.spec.whatwg.org/#security-considerations\r\n *\r\n * Note that this can cause problems for Firefox 22 and below, as an\r\n * older \"LSProgressEvent\" will be dispatched by the browser. That\r\n * progress event is no longer supported, and can lead to failures,\r\n * including throwing exceptions.\r\n *\r\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\r\n * @see b/23469793\r\n *\r\n * @private {boolean}\r\n */\r\n this.progressEventsEnabled_ = false;\r\n\r\n /**\r\n * True if we can use XMLHttpRequest's timeout directly.\r\n * @private {boolean}\r\n */\r\n this.useXhr2Timeout_ = false;\r\n};\r\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\r\n\r\nvar XhrIo = goog.net.XhrIo;\r\n\r\n/**\r\n * Response types that may be requested for XMLHttpRequests.\r\n * @enum {string}\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\r\n */\r\ngoog.net.XhrIo.ResponseType = {\r\n DEFAULT: '',\r\n TEXT: 'text',\r\n DOCUMENT: 'document',\r\n // Not supported as of Chrome 10.0.612.1 dev\r\n BLOB: 'blob',\r\n ARRAY_BUFFER: 'arraybuffer'\r\n};\r\n\r\nvar ResponseType = goog.net.XhrIo.ResponseType;\r\n\r\n\r\n/**\r\n * A reference to the XhrIo logger\r\n * @private {?goog.log.Logger}\r\n * @const\r\n */\r\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\r\n\r\n\r\n/**\r\n * The Content-Type HTTP header name\r\n * @type {string}\r\n */\r\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\r\n\r\n\r\n/**\r\n * The Content-Transfer-Encoding HTTP header name\r\n * @type {string}\r\n */\r\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\r\n\r\n\r\n/**\r\n * The pattern matching the 'http' and 'https' URI schemes\r\n * @type {!RegExp}\r\n */\r\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\r\n\r\n\r\n/**\r\n * The methods that typically come along with form data. We set different\r\n * headers depending on whether the HTTP action is one of these.\r\n * @type {!Array<string>}\r\n */\r\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\r\n\r\n\r\n/**\r\n * The Content-Type HTTP header value for a url-encoded form\r\n * @type {string}\r\n */\r\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\r\n 'application/x-www-form-urlencoded;charset=utf-8';\r\n\r\n\r\n/**\r\n * The XMLHttpRequest Level two timeout delay ms property name.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\r\n *\r\n * @private {string}\r\n * @const\r\n */\r\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\r\n\r\n\r\n/**\r\n * The XMLHttpRequest Level two ontimeout handler property name.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\r\n *\r\n * @private {string}\r\n * @const\r\n */\r\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\r\n\r\n\r\n/**\r\n * All non-disposed instances of goog.net.XhrIo created\r\n * by {@link goog.net.XhrIo.send} are in this Array.\r\n * @see goog.net.XhrIo.cleanup\r\n * @private {!Array<!goog.net.XhrIo>}\r\n */\r\ngoog.net.XhrIo.sendInstances_ = [];\r\n\r\n\r\n/**\r\n * Static send that creates a short lived instance of XhrIo to send the\r\n * request.\r\n * @see goog.net.XhrIo.cleanup\r\n * @param {string|goog.Uri} url Uri to make request to.\r\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\r\n * for when request is complete.\r\n * @param {string=} opt_method Send method, default: GET.\r\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\r\n * opt_content Body data.\r\n * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the\r\n * request.\r\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\r\n * incomplete request will be aborted; 0 means no timeout is set.\r\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\r\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\r\n * @return {!goog.net.XhrIo} The sent XhrIo.\r\n */\r\ngoog.net.XhrIo.send = function(\r\n url, opt_callback, opt_method, opt_content, opt_headers,\r\n opt_timeoutInterval, opt_withCredentials) {\r\n var x = new goog.net.XhrIo();\r\n goog.net.XhrIo.sendInstances_.push(x);\r\n if (opt_callback) {\r\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\r\n }\r\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\r\n if (opt_timeoutInterval) {\r\n x.setTimeoutInterval(opt_timeoutInterval);\r\n }\r\n if (opt_withCredentials) {\r\n x.setWithCredentials(opt_withCredentials);\r\n }\r\n x.send(url, opt_method, opt_content, opt_headers);\r\n return x;\r\n};\r\n\r\n\r\n/**\r\n * Disposes all non-disposed instances of goog.net.XhrIo created by\r\n * {@link goog.net.XhrIo.send}.\r\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\r\n * it creates when the request completes or fails. However, if\r\n * the request never completes, then the goog.net.XhrIo is not disposed.\r\n * This can occur if the window is unloaded before the request completes.\r\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\r\n * it creates and make the client of {@link goog.net.XhrIo.send} be\r\n * responsible for disposing it in this case. However, this makes things\r\n * significantly more complicated for the client, and the whole point\r\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\r\n * Clients of {@link goog.net.XhrIo.send} should call\r\n * {@link goog.net.XhrIo.cleanup} when doing final\r\n * cleanup on window unload.\r\n */\r\ngoog.net.XhrIo.cleanup = function() {\r\n var instances = goog.net.XhrIo.sendInstances_;\r\n while (instances.length) {\r\n instances.pop().dispose();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Installs exception protection for all entry point introduced by\r\n * goog.net.XhrIo instances which are not protected by\r\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\r\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\r\n * {@link goog.events.protectBrowserEventEntryPoint}.\r\n *\r\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\r\n * protect the entry point(s).\r\n */\r\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\r\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\r\n errorHandler.protectEntryPoint(\r\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\r\n};\r\n\r\n\r\n/**\r\n * Disposes of the specified goog.net.XhrIo created by\r\n * {@link goog.net.XhrIo.send} and removes it from\r\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\r\n this.dispose();\r\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of milliseconds after which an incomplete request will be\r\n * aborted, or 0 if no timeout is set.\r\n * @return {number} Timeout interval in milliseconds.\r\n */\r\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\r\n return this.timeoutInterval_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the number of milliseconds after which an incomplete request will be\r\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\r\n * timeout is set.\r\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\r\n */\r\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\r\n this.timeoutInterval_ = Math.max(0, ms);\r\n};\r\n\r\n\r\n/**\r\n * Sets the desired type for the response. At time of writing, this is only\r\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\r\n *\r\n * If this is used, the response may only be accessed via {@link #getResponse}.\r\n *\r\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\r\n */\r\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\r\n this.responseType_ = type;\r\n};\r\n\r\n\r\n/**\r\n * Gets the desired type for the response.\r\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseType = function() {\r\n return this.responseType_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether a \"credentialed\" request that is aware of cookie and\r\n * authentication information should be made. This option is only supported by\r\n * browsers that support HTTP Access Control. As of this writing, this option\r\n * is not supported in IE.\r\n *\r\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\r\n * request.\r\n */\r\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\r\n this.withCredentials_ = withCredentials;\r\n};\r\n\r\n\r\n/**\r\n * Gets whether a \"credentialed\" request is to be sent.\r\n * @return {boolean} The desired type for the response.\r\n */\r\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\r\n return this.withCredentials_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether progress events are enabled for this request. Note\r\n * that progress events require pre-flight OPTIONS request handling\r\n * for CORS requests, and may cause trouble with older browsers. See\r\n * progressEventsEnabled_ for details.\r\n * @param {boolean} enabled Whether progress events should be enabled.\r\n */\r\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\r\n this.progressEventsEnabled_ = enabled;\r\n};\r\n\r\n\r\n/**\r\n * Gets whether progress events are enabled.\r\n * @return {boolean} Whether progress events are enabled for this request.\r\n */\r\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\r\n return this.progressEventsEnabled_;\r\n};\r\n\r\n\r\n/**\r\n * Instance send that actually uses XMLHttpRequest to make a server call.\r\n * @param {string|goog.Uri} url Uri to make request to.\r\n * @param {string=} opt_method Send method, default: GET.\r\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\r\n * opt_content Body data.\r\n * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the\r\n * request.\r\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\r\n * types of parameters for opt_headers.\r\n */\r\ngoog.net.XhrIo.prototype.send = function(\r\n url, opt_method, opt_content, opt_headers) {\r\n if (this.xhr_) {\r\n throw new Error(\r\n '[goog.net.XhrIo] Object is active with another request=' +\r\n this.lastUri_ + '; newUri=' + url);\r\n }\r\n\r\n var method = opt_method ? opt_method.toUpperCase() : 'GET';\r\n\r\n this.lastUri_ = url;\r\n this.lastError_ = '';\r\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\r\n this.lastMethod_ = method;\r\n this.errorDispatched_ = false;\r\n this.active_ = true;\r\n\r\n // Use the factory to create the XHR object and options\r\n this.xhr_ = this.createXhr();\r\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\r\n goog.net.XmlHttp.getOptions();\r\n\r\n // Set up the onreadystatechange callback\r\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\r\n\r\n // Set up upload/download progress events, if progress events are supported.\r\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\r\n this.xhr_.onprogress =\r\n goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);\r\n if (this.xhr_.upload) {\r\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\r\n }\r\n }\r\n\r\n /**\r\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\r\n * is generally permission denied\r\n */\r\n try {\r\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\r\n this.inOpen_ = true;\r\n this.xhr_.open(method, String(url), true); // Always async!\r\n this.inOpen_ = false;\r\n } catch (err) {\r\n goog.log.fine(\r\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\r\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\r\n return;\r\n }\r\n\r\n // We can't use null since this won't allow requests with form data to have a\r\n // content length specified which will cause some proxies to return a 411\r\n // error.\r\n var content = opt_content || '';\r\n\r\n var headers = this.headers.clone();\r\n\r\n // Add headers specific to this request\r\n if (opt_headers) {\r\n goog.structs.forEach(\r\n opt_headers, function(value, key) { headers.set(key, value); });\r\n }\r\n\r\n // Find whether a content type header is set, ignoring case.\r\n // HTTP header names are case-insensitive. See:\r\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\r\n var contentTypeKey =\r\n goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);\r\n\r\n var contentIsFormData =\r\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\r\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\r\n !contentTypeKey && !contentIsFormData) {\r\n // For requests typically with form data, default to the url-encoded form\r\n // content type unless this is a FormData request. For FormData,\r\n // the browser will automatically add a multipart/form-data content type\r\n // with an appropriate multipart boundary.\r\n headers.set(\r\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\r\n }\r\n\r\n // Add the headers to the Xhr object\r\n headers.forEach(function(value, key) {\r\n this.xhr_.setRequestHeader(key, value);\r\n }, this);\r\n\r\n if (this.responseType_) {\r\n this.xhr_.responseType = this.responseType_;\r\n }\r\n // Set xhr_.withCredentials only when the value is different, or else in\r\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\r\n if ('withCredentials' in this.xhr_ &&\r\n this.xhr_.withCredentials !== this.withCredentials_) {\r\n this.xhr_.withCredentials = this.withCredentials_;\r\n }\r\n\r\n /**\r\n * Try to send the request, or other wise report an error (404 not found).\r\n */\r\n try {\r\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\r\n if (this.timeoutInterval_ > 0) {\r\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\r\n goog.log.fine(\r\n this.logger_, this.formatMsg_(\r\n 'Will abort after ' + this.timeoutInterval_ +\r\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\r\n if (this.useXhr2Timeout_) {\r\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\r\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\r\n goog.bind(this.timeout_, this);\r\n } else {\r\n this.timeoutId_ =\r\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\r\n }\r\n }\r\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\r\n this.inSend_ = true;\r\n this.xhr_.send(content);\r\n this.inSend_ = false;\r\n\r\n } catch (err) {\r\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\r\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Determines if the argument is an XMLHttpRequest that supports the level 2\r\n * timeout value and event.\r\n *\r\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\r\n * handler. Perhaps the confusion in the bug referenced below hasn't\r\n * entirely been resolved.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\r\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\r\n *\r\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\r\n * @return {boolean} True if the request supports level 2 timeout.\r\n * @private\r\n */\r\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\r\n return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&\r\n goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&\r\n goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} header An HTTP header key.\r\n * @return {boolean} Whether the key is a content type header (ignoring\r\n * case.\r\n * @private\r\n */\r\ngoog.net.XhrIo.isContentTypeHeader_ = function(header) {\r\n return goog.string.caseInsensitiveEquals(\r\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header);\r\n};\r\n\r\n\r\n/**\r\n * Creates a new XHR object.\r\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\r\n * @protected\r\n */\r\ngoog.net.XhrIo.prototype.createXhr = function() {\r\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\r\n goog.net.XmlHttp();\r\n};\r\n\r\n\r\n/**\r\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\r\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\r\n * the request.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.timeout_ = function() {\r\n if (typeof goog == 'undefined') {\r\n // If goog is undefined then the callback has occurred as the application\r\n // is unloading and will error. Thus we let it silently fail.\r\n } else if (this.xhr_) {\r\n this.lastError_ =\r\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\r\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\r\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\r\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\r\n this.abort(goog.net.ErrorCode.TIMEOUT);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Something errorred, so inactivate, fire error callback and clean up\r\n * @param {goog.net.ErrorCode} errorCode The error code.\r\n * @param {Error} err The error object.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\r\n this.active_ = false;\r\n if (this.xhr_) {\r\n this.inAbort_ = true;\r\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\r\n this.inAbort_ = false;\r\n }\r\n this.lastError_ = err;\r\n this.lastErrorCode_ = errorCode;\r\n this.dispatchErrors_();\r\n this.cleanUpXhr_();\r\n};\r\n\r\n\r\n/**\r\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\r\n * not dispatch multiple error events.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\r\n if (!this.errorDispatched_) {\r\n this.errorDispatched_ = true;\r\n this.dispatchEvent(goog.net.EventType.COMPLETE);\r\n this.dispatchEvent(goog.net.EventType.ERROR);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Abort the current XMLHttpRequest\r\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\r\n * defaults to ABORT.\r\n */\r\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\r\n if (this.xhr_ && this.active_) {\r\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\r\n this.active_ = false;\r\n this.inAbort_ = true;\r\n this.xhr_.abort();\r\n this.inAbort_ = false;\r\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\r\n this.dispatchEvent(goog.net.EventType.COMPLETE);\r\n this.dispatchEvent(goog.net.EventType.ABORT);\r\n this.cleanUpXhr_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Nullifies all callbacks to reduce risks of leaks.\r\n * @override\r\n * @protected\r\n */\r\ngoog.net.XhrIo.prototype.disposeInternal = function() {\r\n if (this.xhr_) {\r\n // We explicitly do not call xhr_.abort() unless active_ is still true.\r\n // This is to avoid unnecessarily aborting a successful request when\r\n // dispose() is called in a callback triggered by a complete response, but\r\n // in which browser cleanup has not yet finished.\r\n // (See http://b/issue?id=1684217.)\r\n if (this.active_) {\r\n this.active_ = false;\r\n this.inAbort_ = true;\r\n this.xhr_.abort();\r\n this.inAbort_ = false;\r\n }\r\n this.cleanUpXhr_(true);\r\n }\r\n\r\n XhrIo.base(this, 'disposeInternal');\r\n};\r\n\r\n\r\n/**\r\n * Internal handler for the XHR object's readystatechange event. This method\r\n * checks the status and the readystate and fires the correct callbacks.\r\n * If the request has ended, the handlers are cleaned up and the XHR object is\r\n * nullified.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\r\n if (this.isDisposed()) {\r\n // This method is the target of an untracked goog.Timer.callOnce().\r\n return;\r\n }\r\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\r\n // Were not being called from within a call to this.xhr_.send\r\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\r\n this.onReadyStateChangeEntryPoint_();\r\n } else {\r\n this.onReadyStateChangeHelper_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Used to protect the onreadystatechange handler entry point. Necessary\r\n * as {#onReadyStateChange_} maybe called from within send or abort, this\r\n * method is only called when {#onReadyStateChange_} is called as an\r\n * entry point.\r\n * {@see #protectEntryPoints}\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\r\n this.onReadyStateChangeHelper_();\r\n};\r\n\r\n\r\n/**\r\n * Helper for {@link #onReadyStateChange_}. This is used so that\r\n * entry point calls to {@link #onReadyStateChange_} can be routed through\r\n * {@link #onReadyStateChangeEntryPoint_}.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\r\n if (!this.active_) {\r\n // can get called inside abort call\r\n return;\r\n }\r\n\r\n if (typeof goog == 'undefined') {\r\n // NOTE(user): If goog is undefined then the callback has occurred as the\r\n // application is unloading and will error. Thus we let it silently fail.\r\n\r\n } else if (\r\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\r\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\r\n this.getStatus() == 2) {\r\n // NOTE(user): In IE if send() errors on a *local* request the readystate\r\n // is still changed to COMPLETE. We need to ignore it and allow the\r\n // try/catch around send() to pick up the error.\r\n goog.log.fine(\r\n this.logger_,\r\n this.formatMsg_('Local request error detected and ignored'));\r\n\r\n } else {\r\n // In IE when the response has been cached we sometimes get the callback\r\n // from inside the send call and this usually breaks code that assumes that\r\n // XhrIo is asynchronous. If that is the case we delay the callback\r\n // using a timer.\r\n if (this.inSend_ &&\r\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\r\n return;\r\n }\r\n\r\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\r\n\r\n // readyState indicates the transfer has finished\r\n if (this.isComplete()) {\r\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\r\n\r\n this.active_ = false;\r\n\r\n try {\r\n // Call the specific callbacks for success or failure. Only call the\r\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\r\n if (this.isSuccess()) {\r\n this.dispatchEvent(goog.net.EventType.COMPLETE);\r\n this.dispatchEvent(goog.net.EventType.SUCCESS);\r\n } else {\r\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\r\n this.lastError_ =\r\n this.getStatusText() + ' [' + this.getStatus() + ']';\r\n this.dispatchErrors_();\r\n }\r\n } finally {\r\n this.cleanUpXhr_();\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Internal handler for the XHR object's onprogress event. Fires both a generic\r\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\r\n * allow specific binding for each XHR progress event.\r\n * @param {!ProgressEvent} e XHR progress event.\r\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\r\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\r\n * event should be dispatched.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\r\n goog.asserts.assert(\r\n e.type === goog.net.EventType.PROGRESS,\r\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\r\n this.dispatchEvent(\r\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\r\n this.dispatchEvent(\r\n goog.net.XhrIo.buildProgressEvent_(\r\n e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\r\n goog.net.EventType.UPLOAD_PROGRESS));\r\n};\r\n\r\n\r\n/**\r\n * Creates a representation of the native ProgressEvent. IE doesn't support\r\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\r\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\r\n * @param {!ProgressEvent} e XHR progress event.\r\n * @param {!goog.net.EventType} eventType The type of the event.\r\n * @return {!ProgressEvent} The progress event.\r\n * @private\r\n */\r\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\r\n return /** @type {!ProgressEvent} */ ({\r\n type: eventType,\r\n lengthComputable: e.lengthComputable,\r\n loaded: e.loaded,\r\n total: e.total\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\r\n * object.\r\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\r\n * fire any events).\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\r\n if (this.xhr_) {\r\n // Cancel any pending timeout event handler.\r\n this.cleanUpTimeoutTimer_();\r\n\r\n // Save reference so we can mark it as closed after the READY event. The\r\n // READY event may trigger another request, thus we must nullify this.xhr_\r\n var xhr = this.xhr_;\r\n var clearedOnReadyStateChange =\r\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\r\n goog.nullFunction :\r\n null;\r\n this.xhr_ = null;\r\n this.xhrOptions_ = null;\r\n\r\n if (!opt_fromDispose) {\r\n this.dispatchEvent(goog.net.EventType.READY);\r\n }\r\n\r\n try {\r\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\r\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\r\n // allow you to set the onreadystatechange to NULL so nullFunction is\r\n // used.\r\n xhr.onreadystatechange = clearedOnReadyStateChange;\r\n } catch (e) {\r\n // This seems to occur with a Gears HTTP request. Delayed the setting of\r\n // this onreadystatechange until after READY is sent out and catching the\r\n // error to see if we can track down the problem.\r\n goog.log.error(\r\n this.logger_,\r\n 'Problem encountered resetting onreadystatechange: ' + e.message);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Make sure the timeout timer isn't running.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\r\n if (this.xhr_ && this.useXhr2Timeout_) {\r\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\r\n }\r\n if (this.timeoutId_) {\r\n goog.Timer.clear(this.timeoutId_);\r\n this.timeoutId_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether there is an active request.\r\n */\r\ngoog.net.XhrIo.prototype.isActive = function() {\r\n return !!this.xhr_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the request has completed.\r\n */\r\ngoog.net.XhrIo.prototype.isComplete = function() {\r\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the request completed with a success.\r\n */\r\ngoog.net.XhrIo.prototype.isSuccess = function() {\r\n var status = this.getStatus();\r\n // A zero status code is considered successful for local files.\r\n return goog.net.HttpStatus.isSuccess(status) ||\r\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} whether the effective scheme of the last URI that was\r\n * fetched was 'http' or 'https'.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\r\n var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\r\n return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);\r\n};\r\n\r\n\r\n/**\r\n * Get the readystate from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\r\n */\r\ngoog.net.XhrIo.prototype.getReadyState = function() {\r\n return this.xhr_ ?\r\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\r\n goog.net.XmlHttp.ReadyState\r\n .UNINITIALIZED;\r\n};\r\n\r\n\r\n/**\r\n * Get the status from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @return {number} Http status.\r\n */\r\ngoog.net.XhrIo.prototype.getStatus = function() {\r\n /**\r\n * IE doesn't like you checking status until the readystate is greater than 2\r\n * (i.e. it is receiving or complete). The try/catch is used for when the\r\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\r\n */\r\n try {\r\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\r\n this.xhr_.status :\r\n -1;\r\n } catch (e) {\r\n return -1;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the status text from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @return {string} Status text.\r\n */\r\ngoog.net.XhrIo.prototype.getStatusText = function() {\r\n /**\r\n * IE doesn't like you checking status until the readystate is greater than 2\r\n * (i.e. it is receiving or complete). The try/catch is used for when the\r\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\r\n */\r\n try {\r\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\r\n this.xhr_.statusText :\r\n '';\r\n } catch (e) {\r\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\r\n return '';\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the last Uri that was requested\r\n * @return {string} Last Uri.\r\n */\r\ngoog.net.XhrIo.prototype.getLastUri = function() {\r\n return String(this.lastUri_);\r\n};\r\n\r\n\r\n/**\r\n * Get the response text from the Xhr object\r\n * Will only return correct result when called from the context of a callback.\r\n * @return {string} Result from the server, or '' if no result available.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseText = function() {\r\n try {\r\n return this.xhr_ ? this.xhr_.responseText : '';\r\n } catch (e) {\r\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\r\n // states that responseText should return '' (and responseXML null)\r\n // when the state is not LOADING or DONE. Instead, IE can\r\n // throw unexpected exceptions, for example when a request is aborted\r\n // or no data is available yet.\r\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\r\n return '';\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the response body from the Xhr object. This property is only available\r\n * in IE since version 7 according to MSDN:\r\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\r\n * Will only return correct result when called from the context of a callback.\r\n *\r\n * One option is to construct a VBArray from the returned object and convert\r\n * it to a JavaScript array using the toArray method:\r\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\r\n * This will result in an array of numbers in the range of [0..255]\r\n *\r\n * Another option is to use the VBScript CStr method to convert it into a\r\n * string as outlined in http://stackoverflow.com/questions/1919972\r\n *\r\n * @return {Object} Binary result from the server or null if not available.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseBody = function() {\r\n try {\r\n if (this.xhr_ && 'responseBody' in this.xhr_) {\r\n return this.xhr_['responseBody'];\r\n }\r\n } catch (e) {\r\n // IE can throw unexpected exceptions, for example when a request is aborted\r\n // or no data is yet available.\r\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Get the response XML from the Xhr object\r\n * Will only return correct result when called from the context of a callback.\r\n * @return {Document} The DOM Document representing the XML file, or null\r\n * if no result available.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseXml = function() {\r\n try {\r\n return this.xhr_ ? this.xhr_.responseXML : null;\r\n } catch (e) {\r\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\r\n return null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the response and evaluates it as JSON from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\r\n * stripping of the response before parsing. This needs to be set only if\r\n * your backend server prepends the same prefix string to the JSON response.\r\n * @throws Error if the response text is invalid JSON.\r\n * @return {Object|undefined} JavaScript object.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\r\n if (!this.xhr_) {\r\n return undefined;\r\n }\r\n\r\n var responseText = this.xhr_.responseText;\r\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\r\n responseText = responseText.substring(opt_xssiPrefix.length);\r\n }\r\n\r\n return goog.json.hybrid.parse(responseText);\r\n};\r\n\r\n\r\n/**\r\n * Get the response as the type specificed by {@link #setResponseType}. At time\r\n * of writing, this is only directly supported in very recent versions of WebKit\r\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\r\n * try to emulate it.\r\n *\r\n * Emulating the response means following the rules laid out at\r\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\r\n *\r\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\r\n * response types of DEFAULT or TEXT may be used, and the response returned will\r\n * be the text response.\r\n *\r\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\r\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\r\n * response returned will be either the text response or the Mozilla\r\n * implementation of the array buffer response.\r\n *\r\n * On browsers will full support, any valid response type supported by the\r\n * browser may be used, and the response provided by the browser will be\r\n * returned.\r\n *\r\n * @return {*} The response.\r\n */\r\ngoog.net.XhrIo.prototype.getResponse = function() {\r\n try {\r\n if (!this.xhr_) {\r\n return null;\r\n }\r\n if ('response' in this.xhr_) {\r\n return this.xhr_.response;\r\n }\r\n switch (this.responseType_) {\r\n case ResponseType.DEFAULT:\r\n case ResponseType.TEXT:\r\n return this.xhr_.responseText;\r\n // DOCUMENT and BLOB don't need to be handled here because they are\r\n // introduced in the same spec that adds the .response field, and would\r\n // have been caught above.\r\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\r\n // implemented using a draft spec rather than the final spec.\r\n case ResponseType.ARRAY_BUFFER:\r\n if ('mozResponseArrayBuffer' in this.xhr_) {\r\n return this.xhr_.mozResponseArrayBuffer;\r\n }\r\n }\r\n // Fell through to a response type that is not supported on this browser.\r\n goog.log.error(\r\n this.logger_, 'Response type ' + this.responseType_ + ' is not ' +\r\n 'supported on this browser');\r\n return null;\r\n } catch (e) {\r\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\r\n return null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the value of the response-header with the given name from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * and the request has completed\r\n * @param {string} key The name of the response-header to retrieve.\r\n * @return {string|undefined} The value of the response-header named key.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\r\n if (!this.xhr_ || !this.isComplete()) {\r\n return undefined;\r\n }\r\n\r\n var value = this.xhr_.getResponseHeader(key);\r\n return goog.isNull(value) ? undefined : value;\r\n};\r\n\r\n\r\n/**\r\n * Gets the text of all the headers in the response.\r\n * Will only return correct result when called from the context of a callback\r\n * and the request has completed.\r\n * @return {string} The value of the response headers or empty string.\r\n */\r\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\r\n // getAllResponseHeaders can return null if no response has been received,\r\n // ensure we always return an empty string.\r\n return this.xhr_ && this.isComplete() ?\r\n (this.xhr_.getAllResponseHeaders() || '') :\r\n '';\r\n};\r\n\r\n\r\n/**\r\n * Returns all response headers as a key-value map.\r\n * Multiple values for the same header key can be combined into one,\r\n * separated by a comma and a space.\r\n * Note that the native getResponseHeader method for retrieving a single header\r\n * does a case insensitive match on the header name. This method does not\r\n * include any case normalization logic, it will just return a key-value\r\n * representation of the headers.\r\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\r\n * @return {!Object<string, string>} An object with the header keys as keys\r\n * and header values as values.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\r\n // TODO(b/120371595): Make this function parse headers as per the spec\r\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\r\n\r\n var headersObject = {};\r\n var headersArray = this.getAllResponseHeaders().split('\\r\\n');\r\n for (var i = 0; i < headersArray.length; i++) {\r\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\r\n continue;\r\n }\r\n var keyValue =\r\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\r\n var key = keyValue[0];\r\n var value = keyValue[1];\r\n\r\n if (!goog.isString(value)) {\r\n // There must be a value but it can be the empty string.\r\n continue;\r\n }\r\n\r\n // Whitespace at the start and end of the value is meaningless.\r\n value = value.trim();\r\n // The key should not contain whitespace but we currently ignore that.\r\n\r\n var values = headersObject[key] || [];\r\n headersObject[key] = values;\r\n values.push(value);\r\n }\r\n\r\n return goog.object.map(headersObject, function(values) {\r\n return values.join(', ');\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Get the value of the response-header with the given name from the Xhr object.\r\n * As opposed to {@link #getResponseHeader}, this method does not require that\r\n * the request has completed.\r\n * @param {string} key The name of the response-header to retrieve.\r\n * @return {?string} The value of the response-header, or null if it is\r\n * unavailable.\r\n */\r\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\r\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\r\n};\r\n\r\n\r\n/**\r\n * Gets the text of all the headers in the response. As opposed to\r\n * {@link #getAllResponseHeaders}, this method does not require that the request\r\n * has completed.\r\n * @return {string} The value of the response headers or empty string.\r\n */\r\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\r\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\r\n};\r\n\r\n\r\n/**\r\n * Get the last error message\r\n * @return {!goog.net.ErrorCode} Last error code.\r\n */\r\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\r\n return this.lastErrorCode_;\r\n};\r\n\r\n\r\n/**\r\n * Get the last error message\r\n * @return {string} Last error message.\r\n */\r\ngoog.net.XhrIo.prototype.getLastError = function() {\r\n return goog.isString(this.lastError_) ? this.lastError_ :\r\n String(this.lastError_);\r\n};\r\n\r\n\r\n/**\r\n * Adds the last method, status and URI to the message. This is used to add\r\n * this information to the logging calls.\r\n * @param {string} msg The message text that we want to add the extra text to.\r\n * @return {string} The message with the extra text appended.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\r\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\r\n this.getStatus() + ']';\r\n};\r\n\r\n\r\n// Register the xhr handler as an entry point, so that\r\n// it can be monitored for exception handling, etc.\r\ngoog.debug.entryPointRegistry.register(\r\n /**\r\n * @param {function(!Function): !Function} transformer The transforming\r\n * function.\r\n */\r\n function(transformer) {\r\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\r\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\r\n });\r\n}); // goog.scope\r\n","// Copyright 2011 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Constants for HTTP status codes.\r\n */\r\n\r\ngoog.provide('goog.net.HttpStatus');\r\n\r\n\r\n/**\r\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\r\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\r\n * @see http://tools.ietf.org/html/rfc6585\r\n * @see https://tools.ietf.org/html/rfc4918\r\n * @see https://tools.ietf.org/html/rfc7538\r\n * @enum {number}\r\n */\r\ngoog.net.HttpStatus = {\r\n // Informational 1xx\r\n CONTINUE: 100,\r\n SWITCHING_PROTOCOLS: 101,\r\n\r\n // Successful 2xx\r\n OK: 200,\r\n CREATED: 201,\r\n ACCEPTED: 202,\r\n NON_AUTHORITATIVE_INFORMATION: 203,\r\n NO_CONTENT: 204,\r\n RESET_CONTENT: 205,\r\n PARTIAL_CONTENT: 206,\r\n MULTI_STATUS: 207,\r\n\r\n // Redirection 3xx\r\n MULTIPLE_CHOICES: 300,\r\n MOVED_PERMANENTLY: 301,\r\n FOUND: 302,\r\n SEE_OTHER: 303,\r\n NOT_MODIFIED: 304,\r\n USE_PROXY: 305,\r\n TEMPORARY_REDIRECT: 307,\r\n PERMANENT_REDIRECT: 308,\r\n\r\n // Client Error 4xx\r\n BAD_REQUEST: 400,\r\n UNAUTHORIZED: 401,\r\n PAYMENT_REQUIRED: 402,\r\n FORBIDDEN: 403,\r\n NOT_FOUND: 404,\r\n METHOD_NOT_ALLOWED: 405,\r\n NOT_ACCEPTABLE: 406,\r\n PROXY_AUTHENTICATION_REQUIRED: 407,\r\n REQUEST_TIMEOUT: 408,\r\n CONFLICT: 409,\r\n GONE: 410,\r\n LENGTH_REQUIRED: 411,\r\n PRECONDITION_FAILED: 412,\r\n REQUEST_ENTITY_TOO_LARGE: 413,\r\n REQUEST_URI_TOO_LONG: 414,\r\n UNSUPPORTED_MEDIA_TYPE: 415,\r\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\r\n EXPECTATION_FAILED: 417,\r\n UNPROCESSABLE_ENTITY: 422,\r\n LOCKED: 423,\r\n FAILED_DEPENDENCY: 424,\r\n PRECONDITION_REQUIRED: 428,\r\n TOO_MANY_REQUESTS: 429,\r\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\r\n\r\n // Server Error 5xx\r\n INTERNAL_SERVER_ERROR: 500,\r\n NOT_IMPLEMENTED: 501,\r\n BAD_GATEWAY: 502,\r\n SERVICE_UNAVAILABLE: 503,\r\n GATEWAY_TIMEOUT: 504,\r\n HTTP_VERSION_NOT_SUPPORTED: 505,\r\n INSUFFICIENT_STORAGE: 507,\r\n NETWORK_AUTHENTICATION_REQUIRED: 511,\r\n\r\n /*\r\n * IE returns this code for 204 due to its use of URLMon, which returns this\r\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\r\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\r\n */\r\n QUIRK_IE_NO_CONTENT: 1223\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the given status should be considered successful.\r\n *\r\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\r\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\r\n * and IE's no content code (1223).\r\n *\r\n * @param {number} status The status code to test.\r\n * @return {boolean} Whether the status code should be considered successful.\r\n */\r\ngoog.net.HttpStatus.isSuccess = function(status) {\r\n switch (status) {\r\n case goog.net.HttpStatus.OK:\r\n case goog.net.HttpStatus.CREATED:\r\n case goog.net.HttpStatus.ACCEPTED:\r\n case goog.net.HttpStatus.NO_CONTENT:\r\n case goog.net.HttpStatus.PARTIAL_CONTENT:\r\n case goog.net.HttpStatus.NOT_MODIFIED:\r\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\r\n return true;\r\n\r\n default:\r\n return false;\r\n }\r\n};\r\n","// Copyright 2017 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Provides CORS support for HTTP based RPC requests.\r\n *\r\n * As part of net.rpc package, CORS features provided by this class\r\n * depend on the server support. Please check related specs to decide how\r\n * to enable any of the features provided by this class.\r\n *\r\n */\r\n\r\ngoog.module('goog.net.rpc.HttpCors');\r\n\r\nvar GoogUri = goog.require('goog.Uri');\r\nvar googObject = goog.require('goog.object');\r\nvar googString = goog.require('goog.string');\r\nvar googUriUtils = goog.require('goog.uri.utils');\r\n\r\n\r\n/**\r\n * The default URL parameter name to overwrite http headers with a URL param\r\n * to avoid CORS preflight.\r\n *\r\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\r\n *\r\n * @type {string}\r\n */\r\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\r\n\r\n\r\n/**\r\n * The default URL parameter name to overwrite http method with a URL param\r\n * to avoid CORS preflight.\r\n *\r\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\r\n *\r\n * @type {string}\r\n */\r\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\r\n\r\n\r\n/**\r\n * Generates the URL parameter value with custom headers encoded as\r\n * HTTP/1.1 headers block.\r\n *\r\n * @param {!Object<string, string>} headers The custom headers.\r\n * @return {string} The URL param to overwrite custom HTTP headers.\r\n */\r\nexports.generateHttpHeadersOverwriteParam = function(headers) {\r\n var result = '';\r\n googObject.forEach(headers, function(value, key) {\r\n result += key;\r\n result += ':';\r\n result += value;\r\n result += '\\r\\n';\r\n });\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Generates the URL-encoded URL parameter value with custom headers encoded as\r\n * HTTP/1.1 headers block.\r\n *\r\n * @param {!Object<string, string>} headers The custom headers.\r\n * @return {string} The URL param to overwrite custom HTTP headers.\r\n */\r\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\r\n return googString.urlEncode(\r\n exports.generateHttpHeadersOverwriteParam(headers));\r\n};\r\n\r\n\r\n/**\r\n * Sets custom HTTP headers via an overwrite URL param.\r\n *\r\n * @param {!GoogUri|string} url The URI object or a string path.\r\n * @param {string} urlParam The URL param name.\r\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\r\n * @return {!GoogUri|string} The URI object or a string path with headers\r\n * encoded as a url param.\r\n */\r\nexports.setHttpHeadersWithOverwriteParam = function(\r\n url, urlParam, extraHeaders) {\r\n if (googObject.isEmpty(extraHeaders)) {\r\n return url;\r\n }\r\n var httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\r\n if (goog.isString(url)) {\r\n return googUriUtils.appendParam(\r\n url, googString.urlEncode(urlParam), httpHeaders);\r\n } else {\r\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\r\n return url;\r\n }\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\r\n *\r\n * When WebChannelBase is used as the underlying transport, the capabilities\r\n * of the WebChannel are limited to what's supported by the implementation.\r\n * Particularly, multiplexing is not possible, and only strings are\r\n * supported as message types.\r\n *\r\n */\r\n\r\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.events.EventTarget');\r\ngoog.require('goog.json');\r\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\r\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\r\ngoog.require('goog.labs.net.webChannel.Wire');\r\ngoog.require('goog.log');\r\ngoog.require('goog.net.WebChannel');\r\ngoog.require('goog.net.WebChannelTransport');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.string.path');\r\n\r\n\r\n\r\n/**\r\n * Implementation of {@link goog.net.WebChannelTransport} with\r\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\r\n * implementation.\r\n *\r\n * @constructor\r\n * @struct\r\n * @implements {goog.net.WebChannelTransport}\r\n * @final\r\n */\r\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\r\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\r\n throw new Error('Environmental error: no available transport.');\r\n }\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannelBaseTransport = goog.labs.net.webChannel.WebChannelBaseTransport;\r\nvar WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.prototype.createWebChannel = function(\r\n url, opt_options) {\r\n return new WebChannelBaseTransport.Channel(url, opt_options);\r\n};\r\n\r\n\r\n\r\n/**\r\n * Implementation of the {@link goog.net.WebChannel} interface.\r\n *\r\n * @param {string} url The URL path for the new WebChannel instance.\r\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\r\n * new WebChannel instance.\r\n *\r\n * @constructor\r\n * @implements {goog.net.WebChannel}\r\n * @extends {goog.events.EventTarget}\r\n * @final\r\n */\r\nWebChannelBaseTransport.Channel = function(url, opt_options) {\r\n WebChannelBaseTransport.Channel.base(this, 'constructor');\r\n\r\n /**\r\n * @private {!WebChannelBase} The underlying channel object.\r\n */\r\n this.channel_ = new WebChannelBase(\r\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\r\n\r\n /**\r\n * @private {string} The URL of the target server end-point.\r\n */\r\n this.url_ = url;\r\n\r\n /**\r\n * The test URL of the target server end-point. This value defaults to\r\n * this.url_ + '/test'.\r\n *\r\n * @private {string}\r\n */\r\n this.testUrl_ = (opt_options && opt_options.testUrl) ?\r\n opt_options.testUrl :\r\n goog.string.path.join(this.url_, 'test');\r\n\r\n /**\r\n * @private {goog.log.Logger} The logger for this class.\r\n */\r\n this.logger_ =\r\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\r\n\r\n /**\r\n * @private {Object<string, string>} Extra URL parameters\r\n * to be added to each HTTP request.\r\n */\r\n this.messageUrlParams_ =\r\n (opt_options && opt_options.messageUrlParams) || null;\r\n\r\n var messageHeaders = (opt_options && opt_options.messageHeaders) || null;\r\n\r\n // default is false\r\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\r\n if (messageHeaders) {\r\n goog.object.set(\r\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\r\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\r\n } else {\r\n messageHeaders = goog.object.create(\r\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\r\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\r\n }\r\n }\r\n\r\n this.channel_.setExtraHeaders(messageHeaders);\r\n\r\n var initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\r\n\r\n if (opt_options && opt_options.messageContentType) {\r\n if (initHeaders) {\r\n goog.object.set(\r\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\r\n opt_options.messageContentType);\r\n } else {\r\n initHeaders = goog.object.create(\r\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\r\n opt_options.messageContentType);\r\n }\r\n }\r\n\r\n if (opt_options && opt_options.clientProfile) {\r\n if (initHeaders) {\r\n goog.object.set(\r\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\r\n opt_options.clientProfile);\r\n } else {\r\n initHeaders = goog.object.create(\r\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\r\n opt_options.clientProfile);\r\n }\r\n }\r\n\r\n this.channel_.setInitHeaders(initHeaders);\r\n\r\n var httpHeadersOverwriteParam =\r\n opt_options && opt_options.httpHeadersOverwriteParam;\r\n if (httpHeadersOverwriteParam &&\r\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\r\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\r\n }\r\n\r\n /**\r\n * @private {boolean} Whether to enable CORS.\r\n */\r\n this.supportsCrossDomainXhr_ =\r\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\r\n\r\n /**\r\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\r\n */\r\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\r\n\r\n // Note that httpSessionIdParam will be ignored if the same parameter name\r\n // has already been specified with messageUrlParams\r\n var httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\r\n if (httpSessionIdParam &&\r\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\r\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\r\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\r\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\r\n goog.log.warning(this.logger_,\r\n 'Ignore httpSessionIdParam also specified with messageUrlParams: '\r\n + httpSessionIdParam);\r\n }\r\n }\r\n\r\n /**\r\n * The channel handler.\r\n *\r\n * @private {!WebChannelBaseTransport.Channel.Handler_}\r\n */\r\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\r\n};\r\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\r\n\r\n\r\n/**\r\n * @override\r\n * @suppress {checkTypes}\r\n */\r\nWebChannelBaseTransport.Channel.prototype.addEventListener = function(\r\n type, handler, /** boolean= */ opt_capture, opt_handlerScope) {\r\n WebChannelBaseTransport.Channel.base(\r\n this, 'addEventListener', type, handler, opt_capture, opt_handlerScope);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n * @suppress {checkTypes}\r\n */\r\nWebChannelBaseTransport.Channel.prototype.removeEventListener = function(\r\n type, handler, /** boolean= */ opt_capture, opt_handlerScope) {\r\n WebChannelBaseTransport.Channel.base(\r\n this, 'removeEventListener', type, handler, opt_capture,\r\n opt_handlerScope);\r\n};\r\n\r\n\r\n/**\r\n * Test path is always set to \"/url/test\".\r\n *\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.open = function() {\r\n this.channel_.setHandler(this.channelHandler_);\r\n if (this.supportsCrossDomainXhr_) {\r\n this.channel_.setSupportsCrossDomainXhrs(true);\r\n }\r\n this.channel_.connect(\r\n this.testUrl_, this.url_, (this.messageUrlParams_ || undefined));\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.close = function() {\r\n this.channel_.disconnect();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\r\n // to be implemented\r\n throw new Error('Not implemented');\r\n};\r\n\r\n\r\n/**\r\n * The WebChannelBase only supports object types.\r\n *\r\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\r\n *\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\r\n goog.asserts.assert(\r\n goog.isObject(message) || goog.isString(message),\r\n 'only object type or raw string is supported');\r\n\r\n if (goog.isString(message)) {\r\n var rawJson = {};\r\n rawJson[Wire.RAW_DATA_KEY] = message;\r\n this.channel_.sendMap(rawJson);\r\n } else if (this.sendRawJson_) {\r\n var rawJson = {};\r\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\r\n this.channel_.sendMap(rawJson);\r\n } else {\r\n this.channel_.sendMap(message);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\r\n this.channel_.setHandler(null);\r\n delete this.channelHandler_;\r\n this.channel_.disconnect();\r\n delete this.channel_;\r\n\r\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\r\n};\r\n\r\n\r\n\r\n/**\r\n * The message event.\r\n *\r\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\r\n * @constructor\r\n * @extends {goog.net.WebChannel.MessageEvent}\r\n * @final\r\n */\r\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\r\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\r\n\r\n // single-metadata only\r\n var metadata = array['__sm__'];\r\n if (metadata) {\r\n this.metadataKey = goog.object.getAnyKey(metadata);\r\n if (this.metadataKey) {\r\n this.data = goog.object.get(metadata, this.metadataKey);\r\n } else {\r\n this.data = metadata; // empty\r\n }\r\n } else {\r\n this.data = array;\r\n }\r\n};\r\ngoog.inherits(\r\n WebChannelBaseTransport.Channel.MessageEvent,\r\n goog.net.WebChannel.MessageEvent);\r\n\r\n\r\n\r\n/**\r\n * The error event.\r\n *\r\n * @param {WebChannelBase.Error} error The error code.\r\n * @constructor\r\n * @extends {goog.net.WebChannel.ErrorEvent}\r\n * @final\r\n */\r\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\r\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\r\n\r\n /**\r\n * High-level status code.\r\n */\r\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\r\n\r\n /**\r\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\r\n */\r\n this.errorCode = error;\r\n};\r\ngoog.inherits(\r\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\r\n\r\n\r\n\r\n/**\r\n * Implementation of {@link WebChannelBase.Handler} interface.\r\n *\r\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\r\n *\r\n * @constructor\r\n * @extends {WebChannelBase.Handler}\r\n * @private\r\n */\r\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\r\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\r\n\r\n /**\r\n * @type {!WebChannelBaseTransport.Channel}\r\n * @private\r\n */\r\n this.channel_ = channel;\r\n};\r\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\r\n channel) {\r\n goog.log.info(\r\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\r\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\r\n function(channel, array) {\r\n goog.asserts.assert(array, 'array expected to be defined');\r\n this.channel_.dispatchEvent(\r\n new WebChannelBaseTransport.Channel.MessageEvent(array));\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\r\n channel, error) {\r\n goog.log.info(\r\n this.channel_.logger_, 'WebChannel aborted on ' + this.channel_.url_ +\r\n ' due to channel error: ' + error);\r\n this.channel_.dispatchEvent(\r\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\r\n channel, opt_pendingMaps, opt_undeliveredMaps) {\r\n goog.log.info(\r\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\r\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\r\n return new WebChannelBaseTransport.ChannelProperties(this.channel_);\r\n};\r\n\r\n\r\n\r\n/**\r\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\r\n *\r\n * @param {!WebChannelBase} channel The underlying channel object.\r\n *\r\n * @constructor\r\n * @implements {goog.net.WebChannel.RuntimeProperties}\r\n * @final\r\n */\r\nWebChannelBaseTransport.ChannelProperties = function(channel) {\r\n /**\r\n * The underlying channel object.\r\n *\r\n * @private {!WebChannelBase}\r\n */\r\n this.channel_ = channel;\r\n\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\r\n function() {\r\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\r\n return this.getConcurrentRequestLimit() > 1;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\r\n function() {\r\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\r\n function() {\r\n return this.channel_.getHttpSessionId();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\r\n callback) {\r\n this.channel_.setForwardChannelFlushCallback(callback);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\r\n goog.abstractMethod;\r\n\r\n\r\n/** @override */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\r\n function() {\r\n return this.channel_.getLastStatusCode();\r\n};\r\n}); // goog.scope\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for dealing with POSIX path strings. Based on\r\n * Python's os.path and posixpath.\r\n * @author nnaze@google.com (Nathan Naze)\r\n */\r\n\r\ngoog.provide('goog.string.path');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * Returns the final component of a pathname.\r\n * See http://docs.python.org/library/os.path.html#os.path.basename\r\n * @param {string} path A pathname.\r\n * @return {string} path The final component of a pathname, i.e. everything\r\n * after the final slash.\r\n */\r\ngoog.string.path.baseName = function(path) {\r\n var i = path.lastIndexOf('/') + 1;\r\n return path.slice(i);\r\n};\r\n\r\n\r\n/**\r\n * Alias to goog.string.path.baseName.\r\n * @param {string} path A pathname.\r\n * @return {string} path The final component of a pathname.\r\n * @deprecated Use goog.string.path.baseName.\r\n */\r\ngoog.string.path.basename = goog.string.path.baseName;\r\n\r\n\r\n/**\r\n * Returns the directory component of a pathname.\r\n * See http://docs.python.org/library/os.path.html#os.path.dirname\r\n * @param {string} path A pathname.\r\n * @return {string} The directory component of a pathname, i.e. everything\r\n * leading up to the final slash.\r\n */\r\ngoog.string.path.dirname = function(path) {\r\n var i = path.lastIndexOf('/') + 1;\r\n var head = path.slice(0, i);\r\n // If the path isn't all forward slashes, trim the trailing slashes.\r\n if (!/^\\/+$/.test(head)) {\r\n head = head.replace(/\\/+$/, '');\r\n }\r\n return head;\r\n};\r\n\r\n\r\n/**\r\n * Extracts the extension part of a pathname.\r\n * @param {string} path The path name to process.\r\n * @return {string} The extension if any, otherwise the empty string.\r\n */\r\ngoog.string.path.extension = function(path) {\r\n var separator = '.';\r\n // Combining all adjacent periods in the basename to a single period.\r\n var baseName = goog.string.path.baseName(path).replace(/\\.+/g, separator);\r\n var separatorIndex = baseName.lastIndexOf(separator);\r\n return separatorIndex <= 0 ? '' : baseName.substr(separatorIndex + 1);\r\n};\r\n\r\n\r\n// TODO(johnlenz): goog.string.path.join should not accept undefined\r\n/**\r\n * Joins one or more path components (e.g. 'foo/' and 'bar' make 'foo/bar').\r\n * An absolute component will discard all previous component.\r\n * See http://docs.python.org/library/os.path.html#os.path.join\r\n * @param {...(string|undefined)} var_args One of more path components.\r\n * @return {string} The path components joined.\r\n */\r\ngoog.string.path.join = function(var_args) {\r\n var path = arguments[0];\r\n\r\n for (var i = 1; i < arguments.length; i++) {\r\n var arg = arguments[i];\r\n if (goog.string.startsWith(arg, '/')) {\r\n path = arg;\r\n } else if (path == '' || goog.string.endsWith(path, '/')) {\r\n path += arg;\r\n } else {\r\n path += '/' + arg;\r\n }\r\n }\r\n\r\n return path;\r\n};\r\n\r\n\r\n/**\r\n * Normalizes a pathname by collapsing duplicate separators, parent directory\r\n * references ('..'), and current directory references ('.').\r\n * See http://docs.python.org/library/os.path.html#os.path.normpath\r\n * @param {string} path One or more path components.\r\n * @return {string} The path after normalization.\r\n */\r\ngoog.string.path.normalizePath = function(path) {\r\n if (path == '') {\r\n return '.';\r\n }\r\n\r\n var initialSlashes = '';\r\n // POSIX will keep two slashes, but three or more will be collapsed to one.\r\n if (goog.string.startsWith(path, '/')) {\r\n initialSlashes = '/';\r\n if (goog.string.startsWith(path, '//') &&\r\n !goog.string.startsWith(path, '///')) {\r\n initialSlashes = '//';\r\n }\r\n }\r\n\r\n var parts = path.split('/');\r\n var newParts = [];\r\n\r\n for (var i = 0; i < parts.length; i++) {\r\n var part = parts[i];\r\n\r\n // '' and '.' don't change the directory, ignore.\r\n if (part == '' || part == '.') {\r\n continue;\r\n }\r\n\r\n // A '..' should pop a directory unless this is not an absolute path and\r\n // we're at the root, or we've travelled upwards relatively in the last\r\n // iteration.\r\n if (part != '..' || (!initialSlashes && !newParts.length) ||\r\n goog.array.peek(newParts) == '..') {\r\n newParts.push(part);\r\n } else {\r\n newParts.pop();\r\n }\r\n }\r\n\r\n var returnPath = initialSlashes + newParts.join('/');\r\n return returnPath || '.';\r\n};\r\n\r\n\r\n/**\r\n * Splits a pathname into \"dirname\" and \"baseName\" components, where \"baseName\"\r\n * is everything after the final slash. Either part may return an empty string.\r\n * See http://docs.python.org/library/os.path.html#os.path.split\r\n * @param {string} path A pathname.\r\n * @return {!Array<string>} An array of [dirname, basename].\r\n */\r\ngoog.string.path.split = function(path) {\r\n var head = goog.string.path.dirname(path);\r\n var tail = goog.string.path.baseName(path);\r\n return [head, tail];\r\n};\r\n\r\n// TODO(nnaze): Implement other useful functions from os.path\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Transport support for WebChannel.\r\n *\r\n * The <code>WebChannelTransport</code> implementation serves as the factory\r\n * for <code>WebChannel</code>, which offers an abstraction for\r\n * point-to-point socket-like communication similar to what BrowserChannel\r\n * or HTML5 WebSocket offers.\r\n *\r\n */\r\n\r\ngoog.provide('goog.net.WebChannelTransport');\r\n\r\ngoog.forwardDeclare('goog.net.WebChannel');\r\ngoog.forwardDeclare('goog.net.WebChannel.Options');\r\n\r\n\r\n\r\n/**\r\n * A WebChannelTransport instance represents a shared context of logical\r\n * connectivity between a browser client and a remote origin.\r\n *\r\n * Over a single WebChannelTransport instance, multiple WebChannels may be\r\n * created against different URLs, which may all share the same\r\n * underlying connectivity (i.e. TCP connection) whenever possible.\r\n *\r\n * When multi-domains are supported, such as CORS, multiple origins may be\r\n * supported over a single WebChannelTransport instance at the same time.\r\n *\r\n * Sharing between different window contexts such as tabs is not addressed\r\n * by WebChannelTransport. Applications may choose HTML5 shared workers\r\n * or other techniques to access the same transport instance\r\n * across different window contexts.\r\n *\r\n * @interface\r\n */\r\ngoog.net.WebChannelTransport = function() {};\r\n\r\n\r\n/**\r\n * The client version. This integer value will be passed to the server\r\n * when a channel is opened to inform the server the client \"capabilities\".\r\n *\r\n * Wire protocol version is a different concept and is internal to the\r\n * transport implementation.\r\n *\r\n * @const\r\n * @type {number}\r\n */\r\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\r\n\r\n\r\n/**\r\n * Create a new WebChannel instance.\r\n *\r\n * The new WebChannel is to be opened against the server-side resource\r\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\r\n * semantics.\r\n *\r\n * @param {string} url The URL path for the new WebChannel instance.\r\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\r\n * new WebChannel instance. The configuration object is reusable after\r\n * the new channel instance is created.\r\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\r\n */\r\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\r\n * avoid exposing concrete classes to clients.\r\n *\r\n */\r\n\r\ngoog.provide('goog.net.createWebChannelTransport');\r\n\r\ngoog.require('goog.functions');\r\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\r\n\r\n\r\n/**\r\n * Create a new WebChannelTransport instance using the default implementation.\r\n * Throws an error message if no default transport available in the current\r\n * environment.\r\n *\r\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\r\n */\r\ngoog.net.createWebChannelTransport =\r\n /** @type {function(): !goog.net.WebChannelTransport} */ (\r\n goog.partial(\r\n goog.functions.create,\r\n goog.labs.net.webChannel.WebChannelBaseTransport));\r\n","// Copyright 2008 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for creating functions. Loosely inspired by these\r\n * java classes from the Guava library:\r\n * com.google.common.base.Functions\r\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\r\n *\r\n * com.google.common.base.Predicates\r\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\r\n *\r\n * More about these can be found at\r\n * https://github.com/google/guava/wiki/FunctionalExplained\r\n *\r\n * @author nicksantos@google.com (Nick Santos)\r\n */\r\n\r\n\r\ngoog.provide('goog.functions');\r\n\r\n\r\n/**\r\n * Creates a function that always returns the same value.\r\n * @param {T} retValue The value to return.\r\n * @return {function():T} The new function.\r\n * @template T\r\n */\r\ngoog.functions.constant = function(retValue) {\r\n return function() { return retValue; };\r\n};\r\n\r\n\r\n/**\r\n * Always returns false.\r\n * @type {function(...): boolean}\r\n */\r\ngoog.functions.FALSE = function() {\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Always returns true.\r\n * @type {function(...): boolean}\r\n */\r\ngoog.functions.TRUE = function() {\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Always returns NULL.\r\n * @type {function(...): null}\r\n */\r\ngoog.functions.NULL = function() {\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * A simple function that returns the first argument of whatever is passed\r\n * into it.\r\n * @param {T=} opt_returnValue The single value that will be returned.\r\n * @param {...*} var_args Optional trailing arguments. These are ignored.\r\n * @return {T} The first argument passed in, or undefined if nothing was passed.\r\n * @template T\r\n */\r\ngoog.functions.identity = function(opt_returnValue, var_args) {\r\n return opt_returnValue;\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that always throws an error with the given message.\r\n * @param {string} message The error message.\r\n * @return {!Function} The error-throwing function.\r\n */\r\ngoog.functions.error = function(message) {\r\n return function() {\r\n throw new Error(message);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that throws the given object.\r\n * @param {*} err An object to be thrown.\r\n * @return {!Function} The error-throwing function.\r\n */\r\ngoog.functions.fail = function(err) {\r\n return function() { throw err; };\r\n};\r\n\r\n\r\n/**\r\n * Given a function, create a function that keeps opt_numArgs arguments and\r\n * silently discards all additional arguments.\r\n * @param {Function} f The original function.\r\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\r\n * @return {!Function} A version of f that only keeps the first opt_numArgs\r\n * arguments.\r\n */\r\ngoog.functions.lock = function(f, opt_numArgs) {\r\n opt_numArgs = opt_numArgs || 0;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns its nth argument.\r\n * @param {number} n The position of the return argument.\r\n * @return {!Function} A new function.\r\n */\r\ngoog.functions.nth = function(n) {\r\n return function() { return arguments[n]; };\r\n};\r\n\r\n\r\n/**\r\n * Like goog.partial(), except that arguments are added after arguments to the\r\n * returned function.\r\n *\r\n * Usage:\r\n * function f(arg1, arg2, arg3, arg4) { ... }\r\n * var g = goog.functions.partialRight(f, arg3, arg4);\r\n * g(arg1, arg2);\r\n *\r\n * @param {!Function} fn A function to partially apply.\r\n * @param {...*} var_args Additional arguments that are partially applied to fn\r\n * at the end.\r\n * @return {!Function} A partially-applied form of the function goog.partial()\r\n * was invoked as a method of.\r\n */\r\ngoog.functions.partialRight = function(fn, var_args) {\r\n var rightArgs = Array.prototype.slice.call(arguments, 1);\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n var newArgs = Array.prototype.slice.call(arguments);\r\n newArgs.push.apply(newArgs, rightArgs);\r\n return fn.apply(self, newArgs);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Given a function, create a new function that swallows its return value\r\n * and replaces it with a new one.\r\n * @param {Function} f A function.\r\n * @param {T} retValue A new return value.\r\n * @return {function(...?):T} A new function.\r\n * @template T\r\n */\r\ngoog.functions.withReturnValue = function(f, retValue) {\r\n return goog.functions.sequence(f, goog.functions.constant(retValue));\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns whether its argument equals the given value.\r\n *\r\n * Example:\r\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\r\n *\r\n * @param {*} value The value to compare to.\r\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\r\n * comparison rather than a strict (===) one. Defaults to false.\r\n * @return {function(*):boolean} The new function.\r\n */\r\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\r\n return function(other) {\r\n return opt_useLooseComparison ? (value == other) : (value === other);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates the composition of the functions passed in.\r\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\r\n * @param {function(...?):T} fn The final function.\r\n * @param {...Function} var_args A list of functions.\r\n * @return {function(...?):T} The composition of all inputs.\r\n * @template T\r\n */\r\ngoog.functions.compose = function(fn, var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n var result;\r\n if (length) {\r\n result = functions[length - 1].apply(self, arguments);\r\n }\r\n\r\n for (var i = length - 2; i >= 0; i--) {\r\n result = functions[i].call(self, result);\r\n }\r\n return result;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that calls the functions passed in in sequence, and\r\n * returns the value of the last function. For example,\r\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\r\n * @param {...Function} var_args A list of functions.\r\n * @return {!Function} A function that calls all inputs in sequence.\r\n */\r\ngoog.functions.sequence = function(var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n var result;\r\n for (var i = 0; i < length; i++) {\r\n result = functions[i].apply(self, arguments);\r\n }\r\n return result;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns true if each of its components evaluates\r\n * to true. The components are evaluated in order, and the evaluation will be\r\n * short-circuited as soon as a function returns false.\r\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\r\n * @param {...Function} var_args A list of functions.\r\n * @return {function(...?):boolean} A function that ANDs its component\r\n * functions.\r\n */\r\ngoog.functions.and = function(var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n for (var i = 0; i < length; i++) {\r\n if (!functions[i].apply(self, arguments)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns true if any of its components evaluates\r\n * to true. The components are evaluated in order, and the evaluation will be\r\n * short-circuited as soon as a function returns true.\r\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\r\n * @param {...Function} var_args A list of functions.\r\n * @return {function(...?):boolean} A function that ORs its component\r\n * functions.\r\n */\r\ngoog.functions.or = function(var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n for (var i = 0; i < length; i++) {\r\n if (functions[i].apply(self, arguments)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns the Boolean opposite of a provided function.\r\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\r\n * @param {!Function} f The original function.\r\n * @return {function(...?):boolean} A function that delegates to f and returns\r\n * opposite.\r\n */\r\ngoog.functions.not = function(f) {\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n return !f.apply(self, arguments);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Generic factory function to construct an object given the constructor\r\n * and the arguments. Intended to be bound to create object factories.\r\n *\r\n * Example:\r\n *\r\n * var factory = goog.partial(goog.functions.create, Class);\r\n *\r\n * @param {function(new:T, ...)} constructor The constructor for the Object.\r\n * @param {...*} var_args The arguments to be passed to the constructor.\r\n * @return {T} A new instance of the class given in `constructor`.\r\n * @template T\r\n */\r\ngoog.functions.create = function(constructor, var_args) {\r\n /**\r\n * @constructor\r\n * @final\r\n */\r\n var temp = function() {};\r\n temp.prototype = constructor.prototype;\r\n\r\n // obj will have constructor's prototype in its chain and\r\n // 'obj instanceof constructor' will be true.\r\n var obj = new temp();\r\n\r\n // obj is initialized by constructor.\r\n // arguments is only array-like so lacks shift(), but can be used with\r\n // the Array prototype function.\r\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the return value cache should be used.\r\n * This should only be used to disable caches when testing.\r\n */\r\ngoog.functions.CACHE_RETURN_VALUE =\r\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\r\n\r\n\r\n/**\r\n * Gives a wrapper function that caches the return value of a parameterless\r\n * function when first called.\r\n *\r\n * When called for the first time, the given function is called and its\r\n * return value is cached (thus this is only appropriate for idempotent\r\n * functions). Subsequent calls will return the cached return value. This\r\n * allows the evaluation of expensive functions to be delayed until first used.\r\n *\r\n * To cache the return values of functions with parameters, see goog.memoize.\r\n *\r\n * @param {function():T} fn A function to lazily evaluate.\r\n * @return {function():T} A wrapped version the function.\r\n * @template T\r\n */\r\ngoog.functions.cacheReturnValue = function(fn) {\r\n var called = false;\r\n var value;\r\n\r\n return function() {\r\n if (!goog.functions.CACHE_RETURN_VALUE) {\r\n return fn();\r\n }\r\n\r\n if (!called) {\r\n value = fn();\r\n called = true;\r\n }\r\n\r\n return value;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once. All\r\n * additional calls are no-ops.\r\n *\r\n * This is particularly useful for initialization functions\r\n * that should be called, at most, once.\r\n *\r\n * @param {function():*} f Function to call.\r\n * @return {function():undefined} Wrapped function.\r\n */\r\ngoog.functions.once = function(f) {\r\n // Keep a reference to the function that we null out when we're done with\r\n // it -- that way, the function can be GC'd when we're done with it.\r\n var inner = f;\r\n return function() {\r\n if (inner) {\r\n var tmp = inner;\r\n inner = null;\r\n tmp();\r\n }\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once per interval\r\n * (specified in milliseconds). If the wrapper function is called N times within\r\n * that interval, only the Nth call will go through.\r\n *\r\n * This is particularly useful for batching up repeated actions where the\r\n * last action should win. This can be used, for example, for refreshing an\r\n * autocomplete pop-up every so often rather than updating with every keystroke,\r\n * since the final text typed by the user is the one that should produce the\r\n * final autocomplete results. For more stateful debouncing with support for\r\n * pausing, resuming, and canceling debounced actions, use\r\n * `goog.async.Debouncer`.\r\n *\r\n * @param {function(this:SCOPE, ...?)} f Function to call.\r\n * @param {number} interval Interval over which to debounce. The function will\r\n * only be called after the full interval has elapsed since the last call.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\r\n * @return {function(...?): undefined} Wrapped function.\r\n * @template SCOPE\r\n */\r\ngoog.functions.debounce = function(f, interval, opt_scope) {\r\n var timeout = 0;\r\n return /** @type {function(...?)} */ (function(var_args) {\r\n goog.global.clearTimeout(timeout);\r\n var args = arguments;\r\n timeout = goog.global.setTimeout(function() {\r\n f.apply(opt_scope, args);\r\n }, interval);\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once per interval\r\n * (specified in milliseconds). If the wrapper function is called N times in\r\n * that interval, both the 1st and the Nth calls will go through.\r\n *\r\n * This is particularly useful for limiting repeated user requests where the\r\n * the last action should win, but you also don't want to wait until the end of\r\n * the interval before sending a request out, as it leads to a perception of\r\n * slowness for the user.\r\n *\r\n * @param {function(this:SCOPE, ...?)} f Function to call.\r\n * @param {number} interval Interval over which to throttle. The function can\r\n * only be called once per interval.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\r\n * @return {function(...?): undefined} Wrapped function.\r\n * @template SCOPE\r\n */\r\ngoog.functions.throttle = function(f, interval, opt_scope) {\r\n var timeout = 0;\r\n var shouldFire = false;\r\n var args = [];\r\n\r\n var handleTimeout = function() {\r\n timeout = 0;\r\n if (shouldFire) {\r\n shouldFire = false;\r\n fire();\r\n }\r\n };\r\n\r\n var fire = function() {\r\n timeout = goog.global.setTimeout(handleTimeout, interval);\r\n f.apply(opt_scope, args);\r\n };\r\n\r\n return /** @type {function(...?)} */ (function(var_args) {\r\n args = arguments;\r\n if (!timeout) {\r\n fire();\r\n } else {\r\n shouldFire = true;\r\n }\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once per interval\r\n * (specified in milliseconds). If the wrapper function is called N times within\r\n * that interval, only the 1st call will go through.\r\n *\r\n * This is particularly useful for limiting repeated user requests where the\r\n * first request is guaranteed to have all the data required to perform the\r\n * final action, so there's no need to wait until the end of the interval before\r\n * sending the request out.\r\n *\r\n * @param {function(this:SCOPE, ...?)} f Function to call.\r\n * @param {number} interval Interval over which to rate-limit. The function will\r\n * only be called once per interval, and ignored for the remainer of the\r\n * interval.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\r\n * @return {function(...?): undefined} Wrapped function.\r\n * @template SCOPE\r\n */\r\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\r\n var timeout = 0;\r\n\r\n var handleTimeout = function() {\r\n timeout = 0;\r\n };\r\n\r\n return /** @type {function(...?)} */ (function(var_args) {\r\n if (!timeout) {\r\n timeout = goog.global.setTimeout(handleTimeout, interval);\r\n f.apply(opt_scope, arguments);\r\n }\r\n });\r\n};\r\n","/**\n * @license\n * Copyright 2017 Google Inc.\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.labs.net.webChannel.WebChannelBaseTransport');\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\n// goog.net.XhrIo\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;\n\n/**\n * This ignore statement is required as closure will minify these properties\n * if done in the typical prettier format\n */\n// prettier-ignore\nmodule['exports'] = {\n 'createWebChannelTransport': goog.net.createWebChannelTransport,\n 'ErrorCode': goog.net.ErrorCode,\n 'EventType': goog.net.EventType,\n 'WebChannel': goog.net.WebChannel,\n 'XhrIo': goog.net.XhrIo\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '../core/version';\nimport { PlatformSupport } from '../platform/platform';\n\nconst logClient = new Logger('@firebase/firestore');\n\nexport enum LogLevel {\n DEBUG,\n ERROR,\n SILENT\n}\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n if (logClient.logLevel === FirebaseLogLevel.DEBUG) {\n return LogLevel.DEBUG;\n } else if (logClient.logLevel === FirebaseLogLevel.SILENT) {\n return LogLevel.SILENT;\n } else {\n return LogLevel.ERROR;\n }\n}\nexport function setLogLevel(newLevel: LogLevel): void {\n /**\n * Map the new log level to the associated Firebase Log Level\n */\n switch (newLevel) {\n case LogLevel.DEBUG:\n logClient.logLevel = FirebaseLogLevel.DEBUG;\n break;\n case LogLevel.ERROR:\n logClient.logLevel = FirebaseLogLevel.ERROR;\n break;\n case LogLevel.SILENT:\n logClient.logLevel = FirebaseLogLevel.SILENT;\n break;\n default:\n logClient.error(\n `Firestore (${SDK_VERSION}): Invalid value passed to \\`setLogLevel\\``\n );\n }\n}\n\nexport function debug(tag: string, msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= FirebaseLogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}) [${tag}]: ${msg}`, ...args);\n }\n}\n\nexport function error(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= FirebaseLogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n const platform = PlatformSupport.getPlatform();\n try {\n return platform.formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 firebase from '@firebase/app';\n\n/** The semver (www.semver.org) version of the SDK. */\nexport const SDK_VERSION = firebase.SDK_VERSION;\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SDK_VERSION } from '../core/version';\n\nimport { error } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n error(message);\n\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 new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nexport function assert(assertion: boolean, message: string): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert } from './assert';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let autoId = '';\n for (let i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\n/** Duck-typed interface for objects that have an isEqual() method. */\nexport interface Equatable<T> {\n isEqual(other: T): boolean;\n}\n\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\nexport function equals<T>(\n left: Equatable<T> | null | undefined,\n right: T | null | undefined\n): boolean {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n } else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return (left as null | undefined) === right;\n }\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(left: Array<Equatable<T>>, right: T[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { primitiveComparator } from '../util/misc';\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\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 */\n constructor(\n readonly databaseId: DatabaseId,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nconst DEFAULT_DATABASE_NAME = '(default)';\n\n/** Represents the database ID a Firestore client is associated with. */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n\n compareTo(other: DatabaseId): number {\n return (\n primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * BatchID is a locally assigned ID for a batch of mutations that have been\n * applied.\n */\nexport type BatchId = number;\n\n/**\n * A locally-assigned ID used to refer to a target being watched via the\n * Watch service.\n */\nexport type TargetId = number;\n\nexport type ListenSequenceNumber = number;\n\n// TODO(b/35918695): In GRPC / node, tokens are Uint8Array. In WebChannel,\n// they're strings. We should probably (de-)serialize to a common internal type.\nexport type ProtoByteString = Uint8Array | string;\n\n/** The different states of a mutation batch. */\nexport type MutationBatchState = 'pending' | 'acknowledged' | 'rejected';\n\n/**\n * Describes the online state of the Firestore client. Note that this does not\n * indicate whether or not the remote store is trying to connect or not. This is\n * primarily used by the View / EventManager code to change their behavior while\n * offline (e.g. get() calls shouldn't wait for data from the server and\n * snapshot events should set metadata.isFromCache=true).\n */\nexport enum OnlineState {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it is currently\n * trying to establish a connection, but it has not succeeded or failed yet.\n * Higher-level components should not operate in offline mode.\n */\n Unknown,\n\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * successful message received from the backends.\n */\n Online,\n\n /**\n * The client is either trying to establish a connection but failing, or it\n * has been explicitly marked offline via a call to disableNetwork().\n * Higher-level components should operate in offline mode.\n */\n Offline\n}\n\n/** The source of an online state event. */\nexport enum OnlineStateSource {\n RemoteStore,\n SharedClientState\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { User } from '../auth/user';\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\nexport interface FirstPartyCredentialsSettings {\n type: 'gapi';\n client: unknown;\n sessionIndex: string;\n}\n\nexport interface ProviderCredentialsSettings {\n type: 'provider';\n client: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n */\n user: User;\n\n /** Extra header values to be passed along with a request */\n authHeaders: { [header: string]: string };\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n authHeaders: { [header: string]: string };\n constructor(value: string, public user: User) {\n this.authHeaders = {};\n // Set the headers using Object Literal notation to avoid minification\n this.authHeaders['Authorization'] = `Bearer ${value}`;\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (user: User) => void;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /** Requests a token for the current user. */\n getToken(): Promise<Token | null>;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n /**\n * Specifies a listener to be notified of credential changes\n * (sign-in / sign-out, token changes). It is immediately called once with the\n * initial user.\n */\n setChangeListener(changeListener: CredentialChangeListener): void;\n\n /** Removes the previously-set change listener. */\n removeChangeListener(): void;\n}\n\n/** A CredentialsProvider that always yields an empty token. */\nexport class EmptyCredentialsProvider implements CredentialsProvider {\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 private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(null);\n }\n\n invalidateToken(): void {}\n\n setChangeListener(changeListener: CredentialChangeListener): void {\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\n this.changeListener = changeListener;\n // Fire with initial user.\n changeListener(User.UNAUTHENTICATED);\n }\n\n removeChangeListener(): void {\n assert(\n this.changeListener !== null,\n 'removeChangeListener() when no listener registered'\n );\n this.changeListener = null;\n }\n}\n\nexport class FirebaseCredentialsProvider implements CredentialsProvider {\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: ((token: string | null) => void) | null = null;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n private receivedInitialUser: boolean = false;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n /** The listener registered with setChangeListener(). */\n private changeListener: CredentialChangeListener | null = null;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null;\n\n constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n this.receivedInitialUser = true;\n if (this.changeListener) {\n this.changeListener(this.currentUser);\n }\n };\n\n this.tokenCounter = 0;\n\n this.auth = authProvider.getImmediate({ optional: true });\n\n if (this.auth) {\n this.auth.addAuthTokenListener(this.tokenListener!);\n } else {\n // if auth is not available, invoke tokenListener once with null token\n this.tokenListener(null);\n authProvider.get().then(\n auth => {\n this.auth = auth;\n if (this.tokenListener) {\n // tokenListener can be removed by removeChangeListener()\n this.auth.addAuthTokenListener(this.tokenListener);\n }\n },\n () => {\n /* this.authProvider.get() never rejects */\n }\n );\n }\n }\n\n getToken(): Promise<Token | null> {\n assert(\n this.tokenListener != null,\n 'getToken cannot be called after listener removed.'\n );\n\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 initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\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 if (this.tokenCounter !== initialTokenCounter) {\n throw new FirestoreError(\n Code.ABORTED,\n 'getToken aborted due to token change.'\n );\n } else {\n if (tokenData) {\n assert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n setChangeListener(changeListener: CredentialChangeListener): void {\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\n this.changeListener = changeListener;\n\n // Fire the initial event\n if (this.receivedInitialUser) {\n changeListener(this.currentUser);\n }\n }\n\n removeChangeListener(): void {\n assert(this.tokenListener != null, 'removeChangeListener() called twice');\n assert(\n this.changeListener !== null,\n 'removeChangeListener() called when no listener registered'\n );\n\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n this.tokenListener = null;\n this.changeListener = null;\n }\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 private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n assert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n// Manual type definition for the subset of Gapi we use.\ninterface Gapi {\n auth: {\n getAuthHeaderValueForFirstParty: (\n userIdentifiers: Array<{ [key: string]: string }>\n ) => string | null;\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 */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n\n constructor(private gapi: Gapi, private sessionIndex: string) {}\n\n get authHeaders(): { [header: string]: string } {\n const headers: { [header: string]: string } = {\n 'X-Goog-AuthUser': this.sessionIndex\n };\n const authHeader = this.gapi.auth.getAuthHeaderValueForFirstParty([]);\n if (authHeader) {\n headers['Authorization'] = authHeader;\n }\n return headers;\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 */\nexport class FirstPartyCredentialsProvider implements CredentialsProvider {\n constructor(private gapi: Gapi, private sessionIndex: string) {}\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\n }\n\n setChangeListener(changeListener: CredentialChangeListener): void {\n // Fire with initial uid.\n changeListener(User.FIRST_PARTY);\n }\n\n removeChangeListener(): void {}\n\n invalidateToken(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyCredentialsProvider();\n }\n\n switch (credentials.type) {\n case 'gapi':\n const client = credentials.client as Gapi;\n // Make sure this really is a Gapi client.\n assert(\n !!(\n typeof client === 'object' &&\n client !== null &&\n client['auth'] &&\n client['auth']['getAuthHeaderValueForFirstParty']\n ),\n 'unexpected gapi interface'\n );\n return new FirstPartyCredentialsProvider(\n client,\n credentials.sessionIndex || '0'\n );\n\n case 'provider':\n return credentials.client;\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * as firestore from '@firebase/firestore-types';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = firestore.FirestoreErrorCode;\n\nexport const Code = {\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' as Code,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as Code,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as Code,\n\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' as Code,\n\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' as Code,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as Code,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as Code,\n\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' as Code,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as Code,\n\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' as Code,\n\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' as Code,\n\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' as Code,\n\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' as Code,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as Code,\n\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' as Code,\n\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' as Code,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as Code\n};\n\n/**\n * An error class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nexport class FirestoreError extends Error implements firestore.FirestoreError {\n name = 'FirebaseError';\n stack?: string;\n\n constructor(readonly code: Code, readonly message: string) {\n super(message);\n\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 * @license\n * Copyright 2017 Google Inc.\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 { assert } from './assert';\n\nexport interface Dict<V> {\n [stringKey: string]: V;\n [numberKey: number]: V;\n}\n\nexport function contains<V>(obj: Dict<V>, key: string | number): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function get<V>(obj: Dict<V>, key: string | number): V | null {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\n\nexport function size<V>(obj: Dict<V>): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nexport function defaulted<V>(value: V | undefined, defaultValue: V): V {\n return value !== undefined ? value : defaultValue;\n}\n\nexport function forEachNumber<V>(\n obj: Dict<V>,\n fn: (key: number, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const num = Number(key);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\n\nexport function values<V>(obj: Dict<V>): V[] {\n const vs: V[] = [];\n forEach(obj, (_, v) => vs.push(v));\n return vs;\n}\n\nexport function forEach<V>(\n obj: Dict<V>,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function lookupOrInsert<V>(\n obj: Dict<V>,\n key: string | number,\n valFn: () => V\n): V {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n assert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function shallowCopy<V>(obj: Dict<V>): Dict<V> {\n assert(\n obj && typeof obj === 'object',\n 'shallowCopy() expects object parameter.'\n );\n const result: Dict<V> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as obj from './obj';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\n/**\n * Validates that no arguments were passed in the invocation of functionName.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateNoArgs('myFunction', arguments);\n */\nexport function validateNoArgs(functionName: string, args: IArguments): void {\n if (args.length !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() does not support arguments, ` +\n 'but was called with ' +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateExactNumberOfArgs(\n functionName: string,\n args: IArguments,\n numberOfArgs: number\n): void {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires ` +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateAtLeastNumberOfArgs(\n functionName: string,\n args: IArguments,\n minNumberOfArgs: number\n): void {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires at least ` +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nexport function validateBetweenNumberOfArgs(\n functionName: string,\n args: IArguments,\n minNumberOfArgs: number,\n maxNumberOfArgs: number\n): void {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires between ${minNumberOfArgs} and ` +\n `${maxNumberOfArgs} arguments, but was called with ` +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nexport function validateNamedArrayAtLeastNumberOfElements<T>(\n functionName: string,\n value: T[],\n name: string,\n minNumberOfElements: number\n): void {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${name} argument to be an ` +\n 'array with at least ' +\n `${formatPlural(minNumberOfElements, 'element')}.`\n );\n }\n}\n\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nexport function validateArgType(\n functionName: string,\n type: ValidationType,\n position: number,\n argument: unknown\n): void {\n validateType(functionName, type, `${ordinal(position)} argument`, argument);\n}\n\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateOptionalArgType(\n functionName: string,\n type: ValidationType,\n position: number,\n argument: unknown\n): void {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nexport function validateNamedType(\n functionName: string,\n type: ValidationType,\n optionName: string,\n argument: unknown\n): void {\n validateType(functionName, type, `${optionName} option`, argument);\n}\n\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateNamedOptionalType(\n functionName: string,\n type: ValidationType,\n optionName: string,\n argument: unknown\n): void {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n\nexport function validateArrayElements<T>(\n functionName: string,\n optionName: string,\n typeDescription: string,\n argument: T[],\n validator: (arg0: T) => boolean\n): void {\n if (!(argument instanceof Array)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${optionName} ` +\n `option to be an array, but it was: ${valueDescription(argument)}`\n );\n }\n\n for (let i = 0; i < argument.length; ++i) {\n if (!validator(argument[i])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires all ${optionName} ` +\n `elements to be ${typeDescription}, but the value at index ${i} ` +\n `was: ${valueDescription(argument[i])}`\n );\n }\n }\n}\n\nexport function validateOptionalArrayElements<T>(\n functionName: string,\n optionName: string,\n typeDescription: string,\n argument: T[] | undefined,\n validator: (arg0: T) => boolean\n): void {\n if (argument !== undefined) {\n validateArrayElements(\n functionName,\n optionName,\n typeDescription,\n argument,\n validator\n );\n }\n}\n\n/**\n * Validates that the provided named option equals one of the expected values.\n */\nexport function validateNamedPropertyEquals<T>(\n functionName: string,\n inputName: string,\n optionName: string,\n input: T,\n expected: T[]\n): void {\n const expectedDescription: string[] = [];\n\n for (const val of expected) {\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n\n const actualDescription = valueDescription(input);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid value ${actualDescription} provided to function ${functionName}() for option ` +\n `\"${optionName}\". Acceptable values: ${expectedDescription.join(', ')}`\n );\n}\n\n/**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */\nexport function validateNamedOptionalPropertyEquals<T>(\n functionName: string,\n inputName: string,\n optionName: string,\n input: T,\n expected: T[]\n): void {\n if (input !== undefined) {\n validateNamedPropertyEquals(\n functionName,\n inputName,\n optionName,\n input,\n expected\n );\n }\n}\n\n/**\n * Validates that the provided argument is a valid enum.\n *\n * @param functionName Function making the validation call.\n * @param enums Array containing all possible values for the enum.\n * @param position Position of the argument in `functionName`.\n * @param argument Arugment to validate.\n */\nexport function validateStringEnum<T>(\n functionName: string,\n enums: string[],\n position: number,\n argument: unknown\n): void {\n if (!enums.some(element => element === argument)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid value ${valueDescription(argument)} provided to function ` +\n `${functionName}() for its ${ordinal(position)} argument. Acceptable ` +\n `values: ${enums.join(', ')}`\n );\n }\n}\n\n/** Helper to validate the type of a provided input. */\nfunction validateType(\n functionName: string,\n type: ValidationType,\n inputName: string,\n input: unknown\n): void {\n let valid = false;\n if (type === 'object') {\n valid = isPlainObject(input);\n } else if (type === 'non-empty string') {\n valid = typeof input === 'string' && input !== '';\n } else {\n valid = typeof input === type;\n }\n\n if (!valid) {\n const description = valueDescription(input);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${inputName} ` +\n `to be of type ${type}, but it was: ${description}`\n );\n }\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 */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** Hacky method to try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n const funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n const results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n\n/** Validates the provided argument is defined. */\nexport function validateDefined(\n functionName: string,\n position: number,\n argument: unknown\n): void {\n if (argument === undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a valid ${ordinal(position)} ` +\n `argument, but it was undefined.`\n );\n }\n}\n\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nexport function validateOptionNames(\n functionName: string,\n options: object,\n optionNames: string[]\n): void {\n obj.forEach(options as obj.Dict<unknown>, (key, _) => {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Unknown option '${key}' passed to function ${functionName}(). ` +\n 'Available options: ' +\n optionNames.join(', ')\n );\n }\n });\n}\n\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nexport function invalidClassError(\n functionName: string,\n type: string,\n position: number,\n argument: unknown\n): Error {\n const description = valueDescription(argument);\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${ordinal(position)} ` +\n `argument to be a ${type}, but it was: ${description}`\n );\n}\n\nexport function validatePositiveNumber(\n functionName: string,\n position: number,\n n: number\n): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function \"${functionName}()\" requires its ${ordinal(\n position\n )} argument to be a positive number, but it was: ${n}.`\n );\n }\n}\n\n/** Converts a number to its english word representation */\nfunction ordinal(num: number): string {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num: number, str: string): string {\n return `${num} ${str}` + (num === 1 ? '' : 's');\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Code, FirestoreError } from '../util/error';\nimport {\n validateArgType,\n validateExactNumberOfArgs\n} from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n constructor(latitude: number, longitude: number) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get longitude(): number {\n return this._long;\n }\n\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\nexport class Timestamp {\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n }\n\n constructor(readonly seconds: number, readonly nanoseconds: number) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n if (seconds < -62135596800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / 1e6;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\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 */\nexport class SnapshotVersion {\n static readonly MIN = new SnapshotVersion(new Timestamp(0, 0));\n\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n static fromMicroseconds(value: number): SnapshotVersion {\n const seconds = Math.floor(value / 1e6);\n const nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new Timestamp(seconds, nanos));\n }\n\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static forDeletedDoc(): SnapshotVersion {\n return SnapshotVersion.MIN;\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator<T extends BasePath<T>>(\n p1: BasePath<T>,\n p2: BasePath<T>\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nexport class ResourcePath extends BasePath<ResourcePath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\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\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n static fromString(path: string): ResourcePath {\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\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid path (${path}). Paths must not contain // in them.`\n );\n }\n\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n const segments = path.split('/').filter(segment => segment.length > 0);\n\n return new ResourcePath(segments);\n }\n\n static EMPTY_PATH = new ResourcePath([]);\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/** A dot-separated path for navigating sub-objects within a document. */\nexport class FieldPath extends BasePath<FieldPath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\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 */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static EMPTY_PATH = new FieldPath([]);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n assert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static EMPTY = new DocumentKey(new ResourcePath([]));\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n static fromPathString(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n // visible for testing\n root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n constructor(\n public comparator: Comparator<K>,\n root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\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>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\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>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n private isReverse: boolean;\n private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n constructor(\n node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\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(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry<K, V> {\n assert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry<K, V> | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n readonly color: boolean;\n readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\n return new LLRBNode<K, V>(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\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>(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode<K, V>).inorderTraversal(action)\n );\n }\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>(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode<K, V>).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n let smallest: LLRBNode<K, V>;\n let n: LLRBNode<K, V> = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode<K, V>).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode<K, V> {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode<K, V> {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode<K, V>).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode<K, V> {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode<K, V> {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\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 protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode<K, V>).check();\n if (blackDepth !== (this.right as LLRBNode<K, V>).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode<K, V> {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n return new LLRBNode<K, V>(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SortedMap, SortedMapIterator } from './sorted_map';\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 */\nexport class SortedSet<T> {\n private data: SortedMap<T, boolean>;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap<T, boolean>(this.comparator);\n }\n\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n static fromMapKeys<K, V>(map: SortedMap<K, V>): SortedSet<K> {\n let keys = new SortedSet<K>(map.comparator);\n map.forEach(key => {\n keys = keys.add(key);\n });\n return keys;\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator<T, boolean>;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet<T> {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet<T> {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet<T>): SortedSet<T> {\n let result: SortedSet<T> = this;\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet<T>): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator<T> {\n constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nimport {\n ArrayValue,\n DoubleValue,\n FieldValue,\n IntegerValue,\n NumberValue,\n ServerTimestampValue\n} from './field_value';\n\n/** Represents a transform within a TransformMutation. */\nexport interface TransformOperation {\n /**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue;\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 */\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue;\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 * @return a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null;\n\n isEqual(other: TransformOperation): boolean;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform implements TransformOperation {\n private constructor() {}\n static instance = new ServerTimestampTransform();\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n return new ServerTimestampValue(localWriteTime!, previousValue);\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\n return transformResult!;\n }\n\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null {\n return null; // Server timestamps are idempotent and don't require a base value.\n }\n\n isEqual(other: TransformOperation): boolean {\n return other instanceof ServerTimestampTransform;\n }\n}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation implements TransformOperation {\n constructor(readonly elements: FieldValue[]) {}\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n return this.apply(previousValue);\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\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 this.apply(previousValue);\n }\n\n private apply(previousValue: FieldValue | null): FieldValue {\n const result = coercedFieldValuesArray(previousValue);\n for (const toUnion of this.elements) {\n if (!result.find(element => element.isEqual(toUnion))) {\n result.push(toUnion);\n }\n }\n return new ArrayValue(result);\n }\n\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null {\n return null; // Array transforms are idempotent and don't require a base value.\n }\n\n isEqual(other: TransformOperation): boolean {\n return (\n other instanceof ArrayUnionTransformOperation &&\n misc.arrayEquals(other.elements, this.elements)\n );\n }\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation implements TransformOperation {\n constructor(readonly elements: FieldValue[]) {}\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n return this.apply(previousValue);\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\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 this.apply(previousValue);\n }\n\n private apply(previousValue: FieldValue | null): FieldValue {\n let result = coercedFieldValuesArray(previousValue);\n for (const toRemove of this.elements) {\n result = result.filter(element => !element.isEqual(toRemove));\n }\n return new ArrayValue(result);\n }\n\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null {\n return null; // Array transforms are idempotent and don't require a base value.\n }\n\n isEqual(other: TransformOperation): boolean {\n return (\n other instanceof ArrayRemoveTransformOperation &&\n misc.arrayEquals(other.elements, this.elements)\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 */\nexport class NumericIncrementTransformOperation implements TransformOperation {\n constructor(readonly operand: NumberValue) {}\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n const baseValue = this.computeBaseValue(previousValue);\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\n // Return an integer value iff the previous value and the operand is an\n // integer.\n if (\n baseValue instanceof IntegerValue &&\n this.operand instanceof IntegerValue\n ) {\n const sum = baseValue.internalValue + this.operand.internalValue;\n return new IntegerValue(sum);\n } else {\n const sum = baseValue.internalValue + this.operand.internalValue;\n return new DoubleValue(sum);\n }\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\n assert(\n transformResult !== null,\n \"Didn't receive transformResult for NUMERIC_ADD transform\"\n );\n return transformResult;\n }\n\n /**\n * Inspects the provided value, returning the provided value if it is already\n * a NumberValue, otherwise returning a coerced IntegerValue of 0.\n */\n computeBaseValue(previousValue: FieldValue | null): NumberValue {\n return previousValue instanceof NumberValue\n ? previousValue\n : new IntegerValue(0);\n }\n\n isEqual(other: TransformOperation): boolean {\n return (\n other instanceof NumericIncrementTransformOperation &&\n this.operand.isEqual(other.operand)\n );\n }\n}\n\nfunction coercedFieldValuesArray(value: FieldValue | null): FieldValue[] {\n if (value instanceof ArrayValue) {\n return value.internalValue.slice();\n } else {\n // coerce to empty array.\n return [];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport * as misc from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Document,\n MaybeDocument,\n NoDocument,\n UnknownDocument\n} from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldValue, ObjectValue } from './field_value';\nimport { FieldPath } from './path';\nimport { TransformOperation } from './transform_operation';\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 */\nexport class FieldMask {\n constructor(readonly fields: SortedSet<FieldPath>) {\n // TODO(dimond): validation of FieldMask\n }\n\n static fromSet(fields: SortedSet<FieldPath>): FieldMask {\n return new FieldMask(fields);\n }\n\n static fromArray(fields: FieldPath[]): FieldMask {\n let fieldsAsSet = new SortedSet<FieldPath>(FieldPath.comparator);\n fields.forEach(fieldPath => (fieldsAsSet = fieldsAsSet.add(fieldPath)));\n return new FieldMask(fieldsAsSet);\n }\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 */\n covers(fieldPath: FieldPath): boolean {\n let found = false;\n this.fields.forEach(fieldMaskPath => {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n found = true;\n }\n });\n return found;\n }\n\n isEqual(other: FieldMask): boolean {\n return this.fields.isEqual(other.fields);\n }\n}\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n\n isEqual(other: FieldTransform): boolean {\n return (\n this.field.isEqual(other.field) && this.transform.isEqual(other.transform)\n );\n }\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\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 readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n readonly transformResults: Array<FieldValue | null> | null\n ) {}\n}\n\nexport enum MutationType {\n Set,\n Patch,\n Transform,\n Delete,\n Verify\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 */\nexport class Precondition {\n static readonly NONE = new Precondition();\n\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n assert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n isValidFor(maybeDoc: MaybeDocument | null): boolean {\n if (this.updateTime !== undefined) {\n return (\n maybeDoc instanceof Document &&\n maybeDoc.version.isEqual(this.updateTime)\n );\n } else if (this.exists !== undefined) {\n return this.exists === maybeDoc instanceof Document;\n } else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n }\n\n isEqual(other: Precondition): boolean {\n return (\n misc.equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists\n );\n }\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, Patch, and Transform mutations. For Delete\n * mutations, we 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 null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set, Patch, and Transform mutations. As deletes\n * have no 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 return an `UnknownDocument` and rely on Watch to send us the\n * updated version.\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n\n /**\n * Applies this mutation to the given MaybeDocument or null for the purposes\n * of computing a new remote document. If the input document doesn't match the\n * expected state (e.g. it is null or outdated), an `UnknownDocument` can be\n * returned.\n *\n * @param maybeDoc The document to mutate. The input document can be null if\n * the client has no knowledge of the pre-mutation state of the document.\n * @param mutationResult The result of applying the mutation from the backend.\n * @return The mutated document. The returned document may be an\n * UnknownDocument if the mutation could not be applied to the locally\n * cached base document.\n */\n abstract applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument;\n\n /**\n * Applies this mutation to the given MaybeDocument or null for the purposes\n * of computing the new local view of a document. Both the input and returned\n * documents can be null.\n *\n * @param maybeDoc The document to mutate. The input document can be null if\n * the client has no knowledge of the pre-mutation state of the document.\n * @param baseDoc The state of the document prior to this mutation batch. The\n * input document can be null if the client has no knowledge of the\n * pre-mutation state of the document.\n * @param localWriteTime A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @return The mutated document. The returned document may be null, but only\n * if maybeDoc was null and the mutation would not create a new document.\n */\n abstract applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null;\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 * @return a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\n abstract extractBaseValue(maybeDoc: MaybeDocument | null): ObjectValue | null;\n\n abstract isEqual(other: Mutation): boolean;\n\n protected verifyKeyMatches(maybeDoc: MaybeDocument | null): void {\n if (maybeDoc != null) {\n assert(\n maybeDoc.key.isEqual(this.key),\n 'Can only apply a mutation to a document with the same key'\n );\n }\n }\n\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n protected static getPostMutationVersion(\n maybeDoc: MaybeDocument | null\n ): SnapshotVersion {\n if (maybeDoc instanceof Document) {\n return maybeDoc.version;\n } else {\n return SnapshotVersion.MIN;\n }\n }\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults == null,\n 'Transform results received by SetMutation.'\n );\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\n const version = mutationResult.version;\n return new Document(\n this.key,\n version,\n {\n hasCommittedMutations: true\n },\n this.value\n );\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n const version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(\n this.key,\n version,\n {\n hasLocalMutations: true\n },\n this.value\n );\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n return null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof SetMutation &&\n this.key.isEqual(other.key) &&\n this.value.isEqual(other.value) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n}\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 */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults == null,\n 'Transform results received by PatchMutation.'\n );\n\n if (!this.precondition.isValidFor(maybeDoc)) {\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 return an UnknownDocument with the\n // known updateTime.\n return new UnknownDocument(this.key, mutationResult.version);\n }\n\n const newData = this.patchDocument(maybeDoc);\n return new Document(\n this.key,\n mutationResult.version,\n {\n hasCommittedMutations: true\n },\n newData\n );\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n const version = Mutation.getPostMutationVersion(maybeDoc);\n const newData = this.patchDocument(maybeDoc);\n return new Document(\n this.key,\n version,\n {\n hasLocalMutations: true\n },\n newData\n );\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n return null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof PatchMutation &&\n this.key.isEqual(other.key) &&\n this.fieldMask.isEqual(other.fieldMask) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n private patchDocument(maybeDoc: MaybeDocument | null): ObjectValue {\n let data: ObjectValue;\n if (maybeDoc instanceof Document) {\n data = maybeDoc.data();\n } else {\n data = ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n }\n\n private patchObject(data: ObjectValue): ObjectValue {\n this.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = this.data.field(fieldPath);\n if (newValue !== null) {\n data = data.set(fieldPath, newValue);\n } else {\n data = data.delete(fieldPath);\n }\n }\n });\n return data;\n }\n}\n\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nexport class TransformMutation extends Mutation {\n readonly type: MutationType = MutationType.Transform;\n\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n readonly precondition = Precondition.exists(true);\n\n constructor(\n readonly key: DocumentKey,\n readonly fieldTransforms: FieldTransform[]\n ) {\n super();\n }\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults != null,\n 'Transform results missing for TransformMutation.'\n );\n\n if (!this.precondition.isValidFor(maybeDoc)) {\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 return an UnknownDocument with the\n // known updateTime.\n return new UnknownDocument(this.key, mutationResult.version);\n }\n\n const doc = this.requireDocument(maybeDoc);\n const transformResults = this.serverTransformResults(\n maybeDoc,\n mutationResult.transformResults!\n );\n\n const version = mutationResult.version;\n const newData = this.transformObject(doc.data(), transformResults);\n return new Document(\n this.key,\n version,\n {\n hasCommittedMutations: true\n },\n newData\n );\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n const doc = this.requireDocument(maybeDoc);\n const transformResults = this.localTransformResults(\n localWriteTime,\n maybeDoc,\n baseDoc\n );\n const newData = this.transformObject(doc.data(), transformResults);\n return new Document(\n this.key,\n doc.version,\n {\n hasLocalMutations: true\n },\n newData\n );\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of this.fieldTransforms) {\n const existingValue =\n maybeDoc instanceof Document\n ? maybeDoc.field(fieldTransform.field)\n : undefined;\n const coercedValue = fieldTransform.transform.computeBaseValue(\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject == null) {\n baseObject = ObjectValue.EMPTY.set(\n fieldTransform.field,\n coercedValue\n );\n } else {\n baseObject = baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n }\n return baseObject;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof TransformMutation &&\n this.key.isEqual(other.key) &&\n misc.arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n private requireDocument(maybeDoc: MaybeDocument | null): Document {\n assert(\n maybeDoc instanceof Document,\n 'Unknown MaybeDocument type ' + maybeDoc\n );\n assert(\n maybeDoc.key.isEqual(this.key),\n 'Can only transform a document with the same key'\n );\n return maybeDoc;\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\n * TransformMutation has been acknowledged by the server.\n *\n * @param baseDoc The document prior to applying this mutation batch.\n * @param serverTransformResults The transform results received by the server.\n * @return The transform results list.\n */\n private serverTransformResults(\n baseDoc: MaybeDocument | null,\n serverTransformResults: Array<FieldValue | null>\n ): FieldValue[] {\n const transformResults = [] as FieldValue[];\n assert(\n this.fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${this.fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = this.fieldTransforms[i];\n const transform = fieldTransform.transform;\n let previousValue: FieldValue | null = null;\n if (baseDoc instanceof Document) {\n previousValue = baseDoc.field(fieldTransform.field);\n }\n transformResults.push(\n transform.applyToRemoteDocument(\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\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 * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @param maybeDoc The current state of the document after applying all\n * previous mutations.\n * @param baseDoc The document prior to applying this mutation batch.\n * @return The transform results list.\n */\n private localTransformResults(\n localWriteTime: Timestamp,\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null\n ): FieldValue[] {\n const transformResults = [] as FieldValue[];\n for (const fieldTransform of this.fieldTransforms) {\n const transform = fieldTransform.transform;\n\n let previousValue: FieldValue | null = null;\n if (maybeDoc instanceof Document) {\n previousValue = maybeDoc.field(fieldTransform.field);\n }\n\n if (previousValue === null && baseDoc instanceof Document) {\n // If the current document does not contain a value for the mutated\n // field, use the value that existed before applying this mutation\n // batch. This solves an edge case where a PatchMutation clears the\n // values in a nested map before the TransformMutation is applied.\n previousValue = baseDoc.field(fieldTransform.field);\n }\n\n transformResults.push(\n transform.applyToLocalView(previousValue, localWriteTime)\n );\n }\n return transformResults;\n }\n\n private transformObject(\n data: ObjectValue,\n transformResults: FieldValue[]\n ): ObjectValue {\n assert(\n transformResults.length === this.fieldTransforms.length,\n 'TransformResults length mismatch.'\n );\n\n for (let i = 0; i < this.fieldTransforms.length; i++) {\n const fieldTransform = this.fieldTransforms[i];\n const fieldPath = fieldTransform.field;\n data = data.set(fieldPath, transformResults[i]);\n }\n return data;\n }\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults == null,\n 'Transform results received by DeleteMutation.'\n );\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\n return new NoDocument(this.key, mutationResult.version, {\n hasCommittedMutations: true\n });\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n if (maybeDoc) {\n assert(\n maybeDoc.key.isEqual(this.key),\n 'Can only apply mutation to document with same key'\n );\n }\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n return null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof DeleteMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition)\n );\n }\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 */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n fail('VerifyMutation should only be used in Transactions.');\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n fail('VerifyMutation should only be used in Transactions.');\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n fail('VerifyMutation should only be used in Transactions.');\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof VerifyMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Blob } from '../api/blob';\nimport { SnapshotOptions } from '../api/database';\nimport { GeoPoint } from '../api/geo_point';\nimport { Timestamp } from '../api/timestamp';\nimport { DatabaseId } from '../core/database_info';\nimport { assert, fail } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './mutation';\nimport { FieldPath } from './path';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * Supported data value types:\n * - Null\n * - Boolean\n * - Long\n * - Double\n * - String\n * - Object\n * - Array\n * - Binary\n * - Timestamp\n * - ServerTimestamp (a sentinel used in uncommitted writes)\n * - GeoPoint\n * - (Document) References\n */\n\nexport interface JsonObject<T> {\n [name: string]: T;\n}\n\nexport enum TypeOrder {\n // This order is defined by the backend.\n NullValue = 0,\n BooleanValue = 1,\n NumberValue = 2,\n TimestampValue = 3,\n StringValue = 4,\n BlobValue = 5,\n RefValue = 6,\n GeoPointValue = 7,\n ArrayValue = 8,\n ObjectValue = 9\n}\n\n/** Defines the return value for pending server timestamps. */\nexport enum ServerTimestampBehavior {\n Default,\n Estimate,\n Previous\n}\n\n/** Holds properties that define field value deserialization options. */\nexport class FieldValueOptions {\n constructor(\n readonly serverTimestampBehavior: ServerTimestampBehavior,\n readonly timestampsInSnapshots: boolean\n ) {}\n\n static fromSnapshotOptions(\n options: SnapshotOptions,\n timestampsInSnapshots: boolean\n ): FieldValueOptions {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(\n ServerTimestampBehavior.Estimate,\n timestampsInSnapshots\n );\n case 'previous':\n return new FieldValueOptions(\n ServerTimestampBehavior.Previous,\n timestampsInSnapshots\n );\n case 'none': // Fall-through intended.\n case undefined:\n return new FieldValueOptions(\n ServerTimestampBehavior.Default,\n timestampsInSnapshots\n );\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n }\n}\n\n/**\n * Potential types returned by FieldValue.value(). This could be stricter\n * (instead of using {}), but there's little benefit.\n *\n * Note that currently we use AnyJs (which is identical except includes\n * undefined) for incoming user data as a convenience to the calling code (but\n * we'll throw if the data contains undefined). This should probably be changed\n * to use FieldType, but all consuming code will have to be updated to\n * explicitly handle undefined and then cast to FieldType or similar. Perhaps\n * we should tackle this when adding robust argument validation to the API.\n */\nexport type FieldType = null | boolean | number | string | {};\n\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nexport abstract class FieldValue {\n abstract readonly typeOrder: TypeOrder;\n\n abstract value(options?: FieldValueOptions): FieldType;\n abstract isEqual(other: FieldValue): boolean;\n abstract compareTo(other: FieldValue): number;\n\n /**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\n abstract approximateByteSize(): number;\n\n toString(): string {\n const val = this.value();\n return val === null ? 'null' : val.toString();\n }\n\n defaultCompareTo(other: FieldValue): number {\n assert(\n this.typeOrder !== other.typeOrder,\n 'Default compareTo should not be used for values of same type.'\n );\n const cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n }\n}\n\nexport class NullValue extends FieldValue {\n typeOrder = TypeOrder.NullValue;\n\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n readonly internalValue = null;\n\n private constructor() {\n super();\n }\n\n value(options?: FieldValueOptions): null {\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof NullValue;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return 4;\n }\n\n static INSTANCE = new NullValue();\n}\n\nexport class BooleanValue extends FieldValue {\n typeOrder = TypeOrder.BooleanValue;\n\n private constructor(readonly internalValue: boolean) {\n super();\n }\n\n value(options?: FieldValueOptions): boolean {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof BooleanValue &&\n this.internalValue === other.internalValue\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return 4;\n }\n\n static of(value: boolean): BooleanValue {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n }\n\n static TRUE = new BooleanValue(true);\n static FALSE = new BooleanValue(false);\n}\n\n/** Base class for IntegerValue and DoubleValue. */\nexport abstract class NumberValue extends FieldValue {\n typeOrder = TypeOrder.NumberValue;\n\n constructor(readonly internalValue: number) {\n super();\n }\n\n value(options?: FieldValueOptions): number {\n return this.internalValue;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return 8;\n }\n}\n\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left: number, right: number): number {\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n } else if (left === right) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left: number, right: number): boolean {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n } else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\n\nexport class IntegerValue extends NumberValue {\n isEqual(other: FieldValue): boolean {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n } else {\n return false;\n }\n }\n\n // NOTE: compareTo() is implemented in NumberValue.\n}\n\nexport class DoubleValue extends NumberValue {\n static NAN = new DoubleValue(NaN);\n static POSITIVE_INFINITY = new DoubleValue(Infinity);\n static NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n\n isEqual(other: FieldValue): boolean {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n } else {\n return false;\n }\n }\n\n // NOTE: compareTo() is implemented in NumberValue.\n}\n\n// TODO(b/37267885): Add truncation support\nexport class StringValue extends FieldValue {\n typeOrder = TypeOrder.StringValue;\n\n constructor(readonly internalValue: string) {\n super();\n }\n\n value(options?: FieldValueOptions): string {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof StringValue && this.internalValue === other.internalValue\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return this.internalValue.length * 2;\n }\n}\n\nexport class TimestampValue extends FieldValue {\n typeOrder = TypeOrder.TimestampValue;\n\n constructor(readonly internalValue: Timestamp) {\n super();\n }\n\n value(options?: FieldValueOptions): Date | Timestamp {\n if (!options || options.timestampsInSnapshots) {\n return this.internalValue;\n } else {\n return this.internalValue.toDate();\n }\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof TimestampValue &&\n this.internalValue.isEqual(other.internalValue)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof TimestampValue) {\n return this.internalValue._compareTo(other.internalValue);\n } else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n approximateByteSize(): number {\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n }\n}\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * 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 */\nexport class ServerTimestampValue extends FieldValue {\n typeOrder = TypeOrder.TimestampValue;\n\n constructor(\n readonly localWriteTime: Timestamp,\n readonly previousValue: FieldValue | null\n ) {\n super();\n }\n\n value(options?: FieldValueOptions): FieldType {\n if (\n options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate\n ) {\n return new TimestampValue(this.localWriteTime).value(options);\n } else if (\n options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous\n ) {\n return this.previousValue ? this.previousValue.value(options) : null;\n } else {\n return null;\n }\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ServerTimestampValue &&\n this.localWriteTime.isEqual(other.localWriteTime)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime._compareTo(other.localWriteTime);\n } else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n toString(): string {\n return '<ServerTimestamp localTime=' + this.localWriteTime.toString() + '>';\n }\n\n approximateByteSize(): number {\n return (\n /* localWriteTime */ 16 +\n (this.previousValue ? this.previousValue.approximateByteSize() : 0)\n );\n }\n}\n\nexport class BlobValue extends FieldValue {\n typeOrder = TypeOrder.BlobValue;\n\n constructor(readonly internalValue: Blob) {\n super();\n }\n\n value(options?: FieldValueOptions): Blob {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof BlobValue &&\n this.internalValue.isEqual(other.internalValue)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return this.internalValue._approximateByteSize();\n }\n}\n\nexport class RefValue extends FieldValue {\n typeOrder = TypeOrder.RefValue;\n\n constructor(readonly databaseId: DatabaseId, readonly key: DocumentKey) {\n super();\n }\n\n value(options?: FieldValueOptions): DocumentKey {\n return this.key;\n }\n\n isEqual(other: FieldValue): boolean {\n if (other instanceof RefValue) {\n return (\n this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId)\n );\n } else {\n return false;\n }\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof RefValue) {\n const cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return (\n this.databaseId.projectId.length +\n this.databaseId.database.length +\n this.key.toString().length\n );\n }\n}\n\nexport class GeoPointValue extends FieldValue {\n typeOrder = TypeOrder.GeoPointValue;\n\n constructor(readonly internalValue: GeoPoint) {\n super();\n }\n\n value(options?: FieldValueOptions): GeoPoint {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof GeoPointValue &&\n this.internalValue.isEqual(other.internalValue)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n }\n}\n\nexport class ObjectValue extends FieldValue {\n typeOrder = TypeOrder.ObjectValue;\n\n constructor(readonly internalValue: SortedMap<string, FieldValue>) {\n super();\n }\n\n value(options?: FieldValueOptions): JsonObject<FieldType> {\n const result: JsonObject<FieldType> = {};\n this.internalValue.inorderTraversal((key, val) => {\n result[key] = val.value(options);\n });\n return result;\n }\n\n forEach(action: (key: string, value: FieldValue) => void): void {\n this.internalValue.inorderTraversal(action);\n }\n\n isEqual(other: FieldValue): boolean {\n if (other instanceof ObjectValue) {\n const it1 = this.internalValue.getIterator();\n const it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n const next1 = it1.getNext();\n const next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n\n return !it1.hasNext() && !it2.hasNext();\n }\n\n return false;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof ObjectValue) {\n const it1 = this.internalValue.getIterator();\n const it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n const next1: { key: string; value: FieldValue } = it1.getNext();\n const next2: { key: string; value: FieldValue } = it2.getNext();\n const cmp =\n primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n set(path: FieldPath, to: FieldValue): ObjectValue {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n } else {\n let child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n const newChild = (child as ObjectValue).set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n }\n\n delete(path: FieldPath): ObjectValue {\n assert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n } else {\n // nested field\n const child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n const newChild = child.delete(path.popFirst());\n return new ObjectValue(\n this.internalValue.insert(path.firstSegment(), newChild)\n );\n } else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n }\n\n contains(path: FieldPath): boolean {\n return this.field(path) !== null;\n }\n\n field(path: FieldPath): FieldValue | null {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n let field: FieldValue | null = this;\n path.forEach((pathSegment: string) => {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment);\n } else {\n field = null;\n }\n });\n return field;\n }\n\n /**\n * Returns a FieldMask built from all FieldPaths starting from this ObjectValue,\n * including paths from nested objects.\n */\n fieldMask(): FieldMask {\n let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n this.internalValue.forEach((key, value) => {\n const currentPath = new FieldPath([key]);\n if (value instanceof ObjectValue) {\n const nestedMask = value.fieldMask();\n const nestedFields = nestedMask.fields;\n if (nestedFields.isEmpty()) {\n // Preserve the empty map by adding it to the FieldMask.\n fields = fields.add(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n nestedFields.forEach(nestedPath => {\n fields = fields.add(currentPath.child(nestedPath));\n });\n }\n } else {\n fields = fields.add(currentPath);\n }\n });\n return FieldMask.fromSet(fields);\n }\n\n approximateByteSize(): number {\n let size = 0;\n this.internalValue.inorderTraversal((key, val) => {\n size += key.length + val.approximateByteSize();\n });\n return size;\n }\n\n toString(): string {\n return this.internalValue.toString();\n }\n\n private child(childName: string): FieldValue | undefined {\n return this.internalValue.get(childName) || undefined;\n }\n\n private setChild(childName: string, value: FieldValue): ObjectValue {\n return new ObjectValue(this.internalValue.insert(childName, value));\n }\n\n static EMPTY = new ObjectValue(\n new SortedMap<string, FieldValue>(primitiveComparator)\n );\n}\n\nexport class ArrayValue extends FieldValue {\n typeOrder = TypeOrder.ArrayValue;\n\n constructor(readonly internalValue: FieldValue[]) {\n super();\n }\n\n value(options?: FieldValueOptions): FieldType[] {\n return this.internalValue.map(v => v.value(options));\n }\n\n /**\n * Returns true if the given value is contained in this array.\n */\n contains(value: FieldValue): boolean {\n for (const element of this.internalValue) {\n if (element.isEqual(value)) {\n return true;\n }\n }\n return false;\n }\n\n forEach(action: (value: FieldValue) => void): void {\n this.internalValue.forEach(action);\n }\n\n isEqual(other: FieldValue): boolean {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n\n for (let i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof ArrayValue) {\n const minLength = Math.min(\n this.internalValue.length,\n other.internalValue.length\n );\n\n for (let i = 0; i < minLength; i++) {\n const cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n\n if (cmp) {\n return cmp;\n }\n }\n\n return primitiveComparator(\n this.internalValue.length,\n other.internalValue.length\n );\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n approximateByteSize(): number {\n return this.internalValue.reduce(\n (totalSize, value) => totalSize + value.approximateByteSize(),\n 0\n );\n }\n\n toString(): string {\n const descriptions = this.internalValue.map(v => v.toString());\n return `[${descriptions.join(',')}]`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { FieldValue, JsonObject, ObjectValue } from './field_value';\nimport { FieldPath } from './path';\n\nimport * as api from '../protos/firestore_proto_api';\nimport * as obj from '../util/obj';\n\nexport interface DocumentOptions {\n hasLocalMutations?: boolean;\n hasCommittedMutations?: boolean;\n}\n\n/**\n * The result of a lookup for a given path may be an existing document or a\n * marker that this document does not exist at a given version.\n */\nexport abstract class MaybeDocument {\n constructor(readonly key: DocumentKey, readonly version: SnapshotVersion) {}\n\n static compareByKey(d1: MaybeDocument, d2: MaybeDocument): number {\n return DocumentKey.comparator(d1.key, d2.key);\n }\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n abstract get hasPendingWrites(): boolean;\n\n abstract isEqual(other: MaybeDocument | null | undefined): boolean;\n\n abstract toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport class Document extends MaybeDocument {\n readonly hasLocalMutations: boolean;\n readonly hasCommittedMutations: boolean;\n\n /**\n * A cache of canonicalized FieldPaths to FieldValues that have already been\n * deserialized in `getField()`.\n */\n private fieldValueCache?: Map<string, FieldValue | null>;\n\n constructor(\n key: DocumentKey,\n version: SnapshotVersion,\n options: DocumentOptions,\n private objectValue?: ObjectValue,\n readonly proto?: api.Document,\n private readonly converter?: (value: api.Value) => FieldValue\n ) {\n super(key, version);\n assert(\n this.objectValue !== undefined ||\n (this.proto !== undefined && this.converter !== undefined),\n 'If objectValue is not defined, proto and converter need to be set.'\n );\n\n this.hasLocalMutations = !!options.hasLocalMutations;\n this.hasCommittedMutations = !!options.hasCommittedMutations;\n }\n\n field(path: FieldPath): FieldValue | null {\n if (this.objectValue) {\n return this.objectValue.field(path);\n } else {\n if (!this.fieldValueCache) {\n // TODO(b/136090445): Remove the cache when `getField` is no longer\n // called during Query ordering.\n this.fieldValueCache = new Map<string, FieldValue>();\n }\n\n const canonicalPath = path.canonicalString();\n\n let fieldValue = this.fieldValueCache.get(canonicalPath);\n\n if (fieldValue === undefined) {\n // Instead of deserializing the full Document proto, we only\n // deserialize the value at the requested field path. This speeds up\n // Query execution as query filters can discard documents based on a\n // single field.\n const protoValue = this.getProtoField(path);\n if (protoValue === undefined) {\n fieldValue = null;\n } else {\n fieldValue = this.converter!(protoValue);\n }\n this.fieldValueCache.set(canonicalPath, fieldValue);\n }\n\n return fieldValue!;\n }\n }\n\n data(): ObjectValue {\n if (!this.objectValue) {\n let result = ObjectValue.EMPTY;\n obj.forEach(this.proto!.fields || {}, (key: string, value: api.Value) => {\n result = result.set(new FieldPath([key]), this.converter!(value));\n });\n this.objectValue = result;\n\n // Once objectValue is computed, values inside the fieldValueCache are no\n // longer accessed.\n this.fieldValueCache = undefined;\n }\n\n return this.objectValue;\n }\n\n value(): JsonObject<unknown> {\n return this.data().value();\n }\n\n isEqual(other: MaybeDocument | null | undefined): boolean {\n return (\n other instanceof Document &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.hasLocalMutations === other.hasLocalMutations &&\n this.hasCommittedMutations === other.hasCommittedMutations &&\n this.data().isEqual(other.data())\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${this.data().toString()}, ` +\n `{hasLocalMutations: ${this.hasLocalMutations}}), ` +\n `{hasCommittedMutations: ${this.hasCommittedMutations}})`\n );\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n /**\n * Returns the nested Protobuf value for 'path`. Can only be called if\n * `proto` was provided at construction time.\n */\n private getProtoField(path: FieldPath): api.Value | undefined {\n assert(\n this.proto !== undefined,\n 'Can only call getProtoField() when proto is defined'\n );\n\n let protoValue: api.Value | undefined = this.proto!.fields\n ? this.proto!.fields[path.firstSegment()]\n : undefined;\n for (let i = 1; i < path.length; ++i) {\n if (!protoValue || !protoValue.mapValue || !protoValue.mapValue.fields) {\n return undefined;\n }\n protoValue = protoValue.mapValue.fields[path.get(i)];\n }\n\n return protoValue;\n }\n\n static compareByField(field: FieldPath, d1: Document, d2: Document): number {\n const v1 = d1.field(field);\n const v2 = d2.field(field);\n if (v1 !== null && v2 !== null) {\n return v1.compareTo(v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n }\n}\n\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nexport class NoDocument extends MaybeDocument {\n readonly hasCommittedMutations: boolean;\n\n constructor(\n key: DocumentKey,\n version: SnapshotVersion,\n options?: DocumentOptions\n ) {\n super(key, version);\n this.hasCommittedMutations = !!(options && options.hasCommittedMutations);\n }\n\n toString(): string {\n return `NoDocument(${this.key}, ${this.version})`;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasCommittedMutations;\n }\n\n isEqual(other: MaybeDocument | null | undefined): boolean {\n return (\n other instanceof NoDocument &&\n other.hasCommittedMutations === this.hasCommittedMutations &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key)\n );\n }\n}\n\n/**\n * A class representing an existing document whose data is unknown (e.g. a\n * document that was updated without a known base document).\n */\nexport class UnknownDocument extends MaybeDocument {\n toString(): string {\n return `UnknownDocument(${this.key}, ${this.version})`;\n }\n\n get hasPendingWrites(): boolean {\n return true;\n }\n\n isEqual(other: MaybeDocument | null | undefined): boolean {\n return (\n other instanceof UnknownDocument &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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// Untyped Number alias we can use to check for ES6 methods / properties.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NumberAsAny = Number as any;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport const MIN_SAFE_INTEGER: number =\n NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport const MAX_SAFE_INTEGER: number =\n NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nexport const isInteger: (value: unknown) => boolean =\n NumberAsAny.isInteger ||\n (value =>\n typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value);\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\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 */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n isInteger(value) &&\n (value as number) <= MAX_SAFE_INTEGER &&\n (value as number) >= MIN_SAFE_INTEGER\n );\n}\n\n/**\n * Safely checks if the number is NaN.\n */\nexport function safeIsNaN(value: unknown): boolean {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n } else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { isNullOrUndefined } from '../util/types';\nimport { Bound, Filter, OrderBy } from './query';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport class Target {\n private memoizedCanonicalId: string | null = null;\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 constructor, because `Query` provides an implicit `orderBy`\n * property.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n\n canonicalId(): string {\n if (this.memoizedCanonicalId === null) {\n let canonicalId = this.path.canonicalString();\n if (this.collectionGroup !== null) {\n canonicalId += '|cg:' + this.collectionGroup;\n }\n canonicalId += '|f:';\n for (const filter of this.filters) {\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (const orderBy of this.orderBy) {\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit!;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n }\n\n toString(): string {\n let str = this.path.canonicalString();\n if (this.collectionGroup !== null) {\n str += ' collectionGroup=' + this.collectionGroup;\n }\n if (this.filters.length > 0) {\n str += `, filters: [${this.filters.join(', ')}]`;\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.orderBy.length > 0) {\n str += `, orderBy: [${this.orderBy.join(', ')}]`;\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return `Target(${str})`;\n }\n\n isEqual(other: Target): boolean {\n if (this.limit !== other.limit) {\n return false;\n }\n\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n\n for (let i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n\n if (this.collectionGroup !== other.collectionGroup) {\n return false;\n }\n\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n\n if (\n this.startAt !== null\n ? !this.startAt.isEqual(other.startAt)\n : other.startAt !== null\n ) {\n return false;\n }\n\n return this.endAt !== null\n ? this.endAt.isEqual(other.endAt)\n : other.endAt === null;\n }\n\n isDocumentQuery(): boolean {\n return (\n DocumentKey.isDocumentKey(this.path) &&\n this.collectionGroup === null &&\n this.filters.length === 0\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n ArrayValue,\n DoubleValue,\n FieldValue,\n NullValue,\n RefValue\n} from '../model/field_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\nimport { Target } from './target';\n\nexport enum LimitType {\n First = 'F',\n Last = 'L'\n}\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 */\nexport class Query {\n static atPath(path: ResourcePath): Query {\n return new Query(path);\n }\n\n private memoizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance.\n private memoizedTarget: Target | null = null;\n\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(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n\n get orderBy(): OrderBy[] {\n if (this.memoizedOrderBy === null) {\n const inequalityField = this.getInequalityFilterField();\n const firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\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 if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n } else {\n this.memoizedOrderBy = [\n new OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n } else {\n assert(\n inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.isEqual(firstOrderByField)),\n 'First orderBy should match inequality field.'\n );\n this.memoizedOrderBy = [];\n let foundKeyOrdering = false;\n for (const orderBy of this.explicitOrderBy) {\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n const lastDirection =\n this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(\n lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC\n );\n }\n }\n }\n return this.memoizedOrderBy;\n }\n\n addFilter(filter: Filter): Query {\n assert(\n this.getInequalityFilterField() == null ||\n !(filter instanceof FieldFilter) ||\n !filter.isInequality() ||\n filter.field.isEqual(this.getInequalityFilterField()!),\n 'Query must only have one inequality field.'\n );\n\n assert(!this.isDocumentQuery(), 'No filtering allowed for document query');\n\n const newFilters = this.filters.concat([filter]);\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n newFilters,\n this.limit,\n this.limitType,\n this.startAt,\n this.endAt\n );\n }\n\n addOrderBy(orderBy: OrderBy): Query {\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(\n this.path,\n this.collectionGroup,\n newOrderBy,\n this.filters.slice(),\n this.limit,\n this.limitType,\n this.startAt,\n this.endAt\n );\n }\n\n withLimitToFirst(limit: number | null): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n limit,\n LimitType.First,\n this.startAt,\n this.endAt\n );\n }\n\n withLimitToLast(limit: number | null): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n limit,\n LimitType.Last,\n this.startAt,\n this.endAt\n );\n }\n\n withStartAt(bound: Bound): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n this.limit,\n this.limitType,\n bound,\n this.endAt\n );\n }\n\n withEndAt(bound: Bound): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n this.limit,\n this.limitType,\n this.startAt,\n bound\n );\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 asCollectionQueryAtPath(path: ResourcePath): Query {\n return new Query(\n path,\n /*collectionGroup=*/ null,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n this.limit,\n this.limitType,\n this.startAt,\n this.endAt\n );\n }\n\n /**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\n matchesAllDocuments(): boolean {\n return (\n this.filters.length === 0 &&\n this.limit === null &&\n this.startAt == null &&\n this.endAt == null &&\n (this.explicitOrderBy.length === 0 ||\n (this.explicitOrderBy.length === 1 &&\n this.explicitOrderBy[0].field.isKeyField()))\n );\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.\n canonicalId(): string {\n return `${this.toTarget().canonicalId()}|lt:${this.limitType}`;\n }\n\n toString(): string {\n return `Query(target=${this.toTarget().toString()}; limitType=${\n this.limitType\n })`;\n }\n\n isEqual(other: Query): boolean {\n return (\n this.toTarget().isEqual(other.toTarget()) &&\n this.limitType === other.limitType\n );\n }\n\n docComparator(d1: Document, d2: Document): number {\n let comparedOnKeyField = false;\n for (const orderBy of this.orderBy) {\n const comp = orderBy.compare(d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n }\n\n matches(doc: Document): boolean {\n return (\n this.matchesPathAndCollectionGroup(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc)\n );\n }\n\n hasLimitToFirst(): boolean {\n return !isNullOrUndefined(this.limit) && this.limitType === LimitType.First;\n }\n\n hasLimitToLast(): boolean {\n return !isNullOrUndefined(this.limit) && this.limitType === LimitType.Last;\n }\n\n getFirstOrderByField(): FieldPath | null {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n }\n\n getInequalityFilterField(): FieldPath | null {\n for (const filter of this.filters) {\n if (filter instanceof FieldFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n }\n\n // Checks if any of the provided Operators are included in the query and\n // returns the first one that is, or null if none are.\n findFilterOperator(operators: Operator[]): Operator | null {\n for (const filter of this.filters) {\n if (filter instanceof FieldFilter) {\n if (operators.indexOf(filter.op) >= 0) {\n return filter.op;\n }\n }\n }\n return null;\n }\n\n isDocumentQuery(): boolean {\n return this.toTarget().isDocumentQuery();\n }\n\n isCollectionGroupQuery(): boolean {\n return this.collectionGroup !== null;\n }\n\n /**\n * Converts this `Query` instance to it's corresponding `Target`\n * representation.\n */\n toTarget(): Target {\n if (!this.memoizedTarget) {\n if (this.limitType === LimitType.First) {\n this.memoizedTarget = new Target(\n this.path,\n this.collectionGroup,\n this.orderBy,\n this.filters,\n this.limit,\n this.startAt,\n this.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n const orderBys = [] as OrderBy[];\n for (const orderBy of this.orderBy) {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n orderBys.push(new OrderBy(orderBy.field, dir));\n }\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = this.endAt\n ? new Bound(this.endAt.position, !this.endAt.before)\n : null;\n const endAt = this.startAt\n ? new Bound(this.startAt.position, !this.startAt.before)\n : null;\n\n // Now return as a LimitType.First query.\n this.memoizedTarget = new Target(\n this.path,\n this.collectionGroup,\n orderBys,\n this.filters,\n this.limit,\n startAt,\n endAt\n );\n }\n }\n return this.memoizedTarget!;\n }\n\n private matchesPathAndCollectionGroup(doc: Document): boolean {\n const docPath = doc.key.path;\n if (this.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(this.collectionGroup) &&\n this.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return this.path.isImmediateParentOf(docPath);\n }\n }\n\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n private matchesOrderBy(doc: Document): boolean {\n for (const orderBy of this.explicitOrderBy) {\n // order by key always matches\n if (!orderBy.field.isKeyField() && doc.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n }\n\n private matchesFilters(doc: Document): boolean {\n for (const filter of this.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n private matchesBounds(doc: Document): boolean {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n }\n\n private assertValidBound(bound: Bound): void {\n assert(\n bound.position.length <= this.orderBy.length,\n 'Bound is longer than orderBy'\n );\n }\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n abstract canonicalId(): string;\n abstract isEqual(filter: Filter): boolean;\n}\n\nexport class Operator {\n static LESS_THAN = new Operator('<');\n static LESS_THAN_OR_EQUAL = new Operator('<=');\n static EQUAL = new Operator('==');\n static GREATER_THAN = new Operator('>');\n static GREATER_THAN_OR_EQUAL = new Operator('>=');\n static ARRAY_CONTAINS = new Operator('array-contains');\n static IN = new Operator('in');\n static ARRAY_CONTAINS_ANY = new Operator('array-contains-any');\n\n static fromString(op: string): Operator {\n switch (op) {\n case '<':\n return Operator.LESS_THAN;\n case '<=':\n return Operator.LESS_THAN_OR_EQUAL;\n case '==':\n return Operator.EQUAL;\n case '>=':\n return Operator.GREATER_THAN_OR_EQUAL;\n case '>':\n return Operator.GREATER_THAN;\n case 'array-contains':\n return Operator.ARRAY_CONTAINS;\n case 'in':\n return Operator.IN;\n case 'array-contains-any':\n return Operator.ARRAY_CONTAINS_ANY;\n default:\n return fail('Unknown FieldFilter operator: ' + op);\n }\n }\n\n constructor(public name: string) {}\n\n toString(): string {\n return this.name;\n }\n\n isEqual(other: Operator): boolean {\n return this.name === other.name;\n }\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public field: FieldPath,\n public op: Operator,\n public value: FieldValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: FieldValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN) {\n assert(\n value instanceof ArrayValue,\n 'Comparing on key with IN, but filter value not an ArrayValue'\n );\n assert(\n value.internalValue.every(elem => {\n return elem instanceof RefValue;\n }),\n 'Comparing on key with IN, but an array value was not a RefValue'\n );\n return new KeyFieldInFilter(field, value);\n } else {\n assert(\n value instanceof RefValue,\n 'Comparing on key, but filter value not a RefValue'\n );\n assert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (value.isEqual(NullValue.INSTANCE)) {\n if (op !== Operator.EQUAL) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. Null supports only equality comparisons.'\n );\n }\n return new FieldFilter(field, op, value);\n } else if (value.isEqual(DoubleValue.NAN)) {\n if (op !== Operator.EQUAL) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. NaN supports only equality comparisons.'\n );\n }\n return new FieldFilter(field, op, value);\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n assert(\n value instanceof ArrayValue,\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n assert(\n value instanceof ArrayValue,\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n matches(doc: Document): boolean {\n const other = doc.field(this.field);\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n this.value.typeOrder === other.typeOrder &&\n this.matchesComparison(other.compareTo(this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL\n ].indexOf(this.op) >= 0\n );\n }\n\n canonicalId(): string {\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 (\n this.field.canonicalString() + this.op.toString() + this.value.toString()\n );\n }\n\n isEqual(other: Filter): boolean {\n if (other instanceof FieldFilter) {\n return (\n this.op.isEqual(other.op) &&\n this.field.isEqual(other.field) &&\n this.value.isEqual(other.value)\n );\n } else {\n return false;\n }\n }\n\n toString(): string {\n return `${this.field.canonicalString()} ${this.op} ${this.value.value()}`;\n }\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n matches(doc: Document): boolean {\n const refValue = this.value as RefValue;\n const comparison = DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n constructor(field: FieldPath, public value: ArrayValue) {\n super(field, Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n const arrayValue = this.value;\n return arrayValue.internalValue.some(refValue => {\n return doc.key.isEqual((refValue as RefValue).key);\n });\n }\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: FieldValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.field(this.field);\n return other instanceof ArrayValue && other.contains(this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, public value: ArrayValue) {\n super(field, Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n const arrayValue = this.value;\n const other = doc.field(this.field);\n return other !== null && arrayValue.contains(other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, public value: ArrayValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.field(this.field);\n return (\n other instanceof ArrayValue &&\n other.internalValue.some(lhsElem => {\n return this.value.contains(lhsElem);\n })\n );\n }\n}\n\n/**\n * The direction of sorting in an order by.\n */\nexport class Direction {\n static ASCENDING = new Direction('asc');\n static DESCENDING = new Direction('desc');\n\n private constructor(public name: string) {}\n\n toString(): string {\n return this.name;\n }\n}\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 */\nexport class Bound {\n constructor(readonly position: FieldValue[], readonly before: boolean) {}\n\n canonicalId(): string {\n // TODO(b/29183165): Make this collision robust.\n let canonicalId = this.before ? 'b:' : 'a:';\n for (const component of this.position) {\n canonicalId += component.toString();\n }\n return canonicalId;\n }\n\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n sortsBeforeDocument(orderBy: OrderBy[], doc: Document): boolean {\n assert(\n this.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < this.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(\n component instanceof RefValue,\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(component.key, doc.key);\n } else {\n const docValue = doc.field(orderByComponent.field);\n assert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n }\n\n isEqual(other: Bound | null): boolean {\n if (other === null) {\n return false;\n }\n if (\n this.before !== other.before ||\n this.position.length !== other.position.length\n ) {\n return false;\n }\n for (let i = 0; i < this.position.length; i++) {\n const thisPosition = this.position[i];\n const otherPosition = other.position[i];\n if (!thisPosition.isEqual(otherPosition)) {\n return false;\n }\n }\n return true;\n }\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n readonly dir: Direction;\n private readonly isKeyOrderBy: boolean;\n\n constructor(readonly field: FieldPath, dir?: Direction) {\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n\n compare(d1: Document, d2: Document): number {\n const comparison = this.isKeyOrderBy\n ? Document.compareByKey(d1, d2)\n : Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n }\n\n canonicalId(): string {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n }\n\n toString(): string {\n return `${this.field.canonicalString()} (${this.dir})`;\n }\n\n isEqual(other: OrderBy): boolean {\n return this.dir === other.dir && this.field.isEqual(other.field);\n }\n}\n\nconst KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\nconst KEY_ORDERING_DESC = new OrderBy(\n FieldPath.keyField(),\n Direction.DESCENDING\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, ProtoByteString, TargetId } from '../core/types';\nimport { emptyByteString } from '../platform/platform';\n\n/** An enumeration of the different purposes we have for targets. */\nexport enum TargetPurpose {\n /** A regular, normal query target. */\n Listen,\n\n /**\n * The query target was used to refill a query after an existence filter mismatch.\n */\n ExistenceFilterMismatch,\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\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 readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.MIN,\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.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 */\n readonly resumeToken: ProtoByteString = emptyByteString()\n ) {}\n\n /** Creates a new target data instance with an updated sequence number. */\n withSequenceNumber(sequenceNumber: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ProtoByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken\n );\n }\n\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */\n withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n lastLimboFreeSnapshotVersion,\n this.resumeToken\n );\n }\n\n isEqual(other: TargetData): boolean {\n return (\n this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.sequenceNumber === other.sequenceNumber &&\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\n this.lastLimboFreeSnapshotVersion.isEqual(\n other.lastLimboFreeSnapshotVersion\n ) &&\n this.resumeToken === other.resumeToken &&\n this.target.isEqual(other.target)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 class ExistenceFilter {\n // TODO(b/33078163): just use simplest form of existence filter for now\n constructor(public count: number) {}\n\n isEqual(other: ExistenceFilter): boolean {\n return other && other.count === this.count;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\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.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\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 */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.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 Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.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 Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\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 */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\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 */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\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 */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\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 log.error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status: number): Code {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\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 */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace('_', '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { TargetId } from '../core/types';\nimport { primitiveComparator } from '../util/misc';\nimport { Document, MaybeDocument } from './document';\nimport { DocumentKey } from './document_key';\n\n/** Miscellaneous collection types / constants. */\nexport interface DocumentSizeEntry {\n maybeDocument: MaybeDocument;\n size: number;\n}\n\nexport type MaybeDocumentMap = SortedMap<DocumentKey, MaybeDocument>;\nconst EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap<DocumentKey, MaybeDocument>(\n DocumentKey.comparator\n);\nexport function maybeDocumentMap(): MaybeDocumentMap {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\n\nexport type NullableMaybeDocumentMap = SortedMap<\n DocumentKey,\n MaybeDocument | null\n>;\n\nexport function nullableMaybeDocumentMap(): NullableMaybeDocumentMap {\n return maybeDocumentMap();\n}\n\nexport interface DocumentSizeEntries {\n maybeDocuments: NullableMaybeDocumentMap;\n sizeMap: SortedMap<DocumentKey, number>;\n}\n\nexport type DocumentMap = SortedMap<DocumentKey, Document>;\nconst EMPTY_DOCUMENT_MAP = new SortedMap<DocumentKey, Document>(\n DocumentKey.comparator\n);\nexport function documentMap(): DocumentMap {\n return EMPTY_DOCUMENT_MAP;\n}\n\nexport type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap<DocumentKey, SnapshotVersion>(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet<DocumentKey>;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n let set = EMPTY_DOCUMENT_KEY_SET;\n for (const key of keys) {\n set = set.add(key);\n }\n return set;\n}\n\nexport type TargetIdSet = SortedSet<TargetId>;\nconst EMPTY_TARGET_ID_SET = new SortedSet<TargetId>(primitiveComparator);\nexport function targetIdSet(): SortedSet<TargetId> {\n return EMPTY_TARGET_ID_SET;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SortedMap } from '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\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 */\n\nexport class DocumentSet {\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n static emptySet(oldSet: DocumentSet): DocumentSet {\n return new DocumentSet(oldSet.comparator);\n }\n\n private comparator: DocumentComparator;\n private keyedMap: SortedMap<DocumentKey, Document>;\n private sortedSet: SortedMap<Document, null>;\n\n /** The default ordering is by key if the comparator is omitted */\n constructor(comp?: DocumentComparator) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = (d1: Document, d2: Document) =>\n comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n } else {\n this.comparator = (d1: Document, d2: Document) =>\n DocumentKey.comparator(d1.key, d2.key);\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap<Document, null>(this.comparator);\n }\n\n has(key: DocumentKey): boolean {\n return this.keyedMap.get(key) != null;\n }\n\n get(key: DocumentKey): Document | null {\n return this.keyedMap.get(key);\n }\n\n first(): Document | null {\n return this.sortedSet.minKey();\n }\n\n last(): Document | null {\n return this.sortedSet.maxKey();\n }\n\n isEmpty(): boolean {\n return this.sortedSet.isEmpty();\n }\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 */\n indexOf(key: DocumentKey): number {\n const doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n }\n\n get size(): number {\n return this.sortedSet.size;\n }\n\n /** Iterates documents in order defined by \"comparator\" */\n forEach(cb: (doc: Document) => void): void {\n this.sortedSet.inorderTraversal((k, v) => {\n cb(k);\n return false;\n });\n }\n\n /** Inserts or updates a document with the same key */\n add(doc: Document): DocumentSet {\n // First remove the element if we have it.\n const set = this.delete(doc.key);\n return set.copy(\n set.keyedMap.insert(doc.key, doc),\n set.sortedSet.insert(doc, null)\n );\n }\n\n /** Deletes a document with a given key */\n delete(key: DocumentKey): DocumentSet {\n const doc = this.get(key);\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n }\n\n isEqual(other: DocumentSet | null | undefined): boolean {\n if (!(other instanceof DocumentSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.sortedSet.getIterator();\n const otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n const thisDoc = thisIt.getNext().key;\n const otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) {\n return false;\n }\n }\n return true;\n }\n\n toString(): string {\n const docStrings: string[] = [];\n this.forEach(doc => {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n }\n\n private copy(\n keyedMap: SortedMap<DocumentKey, Document>,\n sortedSet: SortedMap<Document, null>\n ): DocumentSet {\n const newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Query } from './query';\n\nexport enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport enum SyncState {\n Local,\n Synced\n}\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 */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap<DocumentKey, DocumentViewChange>(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\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 fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean\n ) {}\n\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n static fromInitialDocuments(\n query: Query,\n documents: DocumentSet,\n mutatedKeys: DocumentKeySet,\n fromCache: boolean\n ): ViewSnapshot {\n const changes: DocumentViewChange[] = [];\n documents.forEach(doc => {\n changes.push({ type: ChangeType.Added, doc });\n });\n\n return new ViewSnapshot(\n query,\n documents,\n DocumentSet.emptySet(documents),\n changes,\n mutatedKeys,\n fromCache,\n /* syncStateChanged= */ true,\n /* excludesMetadataChanges= */ false\n );\n }\n\n get hasPendingWrites(): boolean {\n return !this.mutatedKeys.isEmpty();\n }\n\n isEqual(other: ViewSnapshot): boolean {\n if (\n this.fromCache !== other.fromCache ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !this.query.isEqual(other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)\n ) {\n return false;\n }\n const changes: DocumentViewChange[] = this.docChanges;\n const otherChanges: DocumentViewChange[] = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (let i = 0; i < changes.length; i++) {\n if (\n changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)\n ) {\n return false;\n }\n }\n return true;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { ProtoByteString, TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n maybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { emptyByteString } from '../platform/platform';\nimport { assert, fail } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { debug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { ExistenceFilter } from './existence_filter';\nimport { RemoteEvent, TargetChange } from './remote_event';\n\n/**\n * Internal representation of the watcher API protocol buffers.\n */\nexport type WatchChange =\n | DocumentWatchChange\n | WatchTargetChange\n | ExistenceFilterChange;\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 */\nexport class DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n public updatedTargetIds: TargetId[],\n /** The new document is removed from all of these targets. */\n public removedTargetIds: TargetId[],\n /** The key of the document for this change. */\n public key: DocumentKey,\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 public newDoc: MaybeDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\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 public resumeToken: ProtoByteString = emptyByteString(),\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\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 private pendingResponses = 0;\n\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 private documentChanges: SortedMap<\n DocumentKey,\n ChangeType\n > = snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ProtoByteString = emptyByteString();\n private _current = false;\n\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 private _hasPendingChanges = true;\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 */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ProtoByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ProtoByteString): void {\n if (resumeToken.length > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\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 */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n }\n\n markCurrent(): void {\n this._hasPendingChanges = true;\n this._current = true;\n }\n}\n\n/**\n * Interface implemented by RemoteStore to expose target metadata to the\n * WatchChangeAggregator.\n */\nexport interface TargetMetadataProvider {\n /**\n * Returns the set of remote document keys for the given target ID as of the\n * last raised snapshot.\n */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;\n\n /**\n * Returns the TargetData for an active target ID or 'null' if this target\n * has become inactive\n */\n getTargetDataForTarget(targetId: TargetId): TargetData | null;\n}\n\nconst LOG_TAG = 'WatchChangeAggregator';\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nexport class WatchChangeAggregator {\n constructor(private metadataProvider: TargetMetadataProvider) {}\n\n /** The internal state of all tracked targets. */\n private targetStates: { [targetId: number]: TargetState } = {};\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = maybeDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\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 private pendingTargetResets = new SortedSet<TargetId>(primitiveComparator);\n\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */\n handleDocumentChange(docChange: DocumentWatchChange): void {\n for (const targetId of docChange.updatedTargetIds) {\n if (docChange.newDoc instanceof Document) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else if (docChange.newDoc instanceof NoDocument) {\n this.removeDocumentFromTarget(\n targetId,\n docChange.key,\n docChange.newDoc\n );\n }\n }\n\n for (const targetId of docChange.removedTargetIds) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n handleTargetChange(targetChange: WatchTargetChange): void {\n this.forEachTarget(targetChange, targetId => {\n const targetState = this.ensureTargetState(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\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 targetState.clearPendingChanges();\n }\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n case 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 targetState.recordTargetResponse();\n if (!targetState.isPending) {\n this.removeTarget(targetId);\n }\n assert(\n !targetChange.cause,\n 'WatchChangeAggregator does not handle errored targets'\n );\n break;\n case WatchTargetChangeState.Current:\n if (this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (this.isActiveTarget(targetId)) {\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.resetTarget(targetId);\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\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 */\n forEachTarget(\n targetChange: WatchTargetChange,\n fn: (targetId: TargetId) => void\n ): void {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n objUtils.forEachNumber(this.targetStates, fn);\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 */\n handleExistenceFilter(watchChange: ExistenceFilterChange): void {\n const targetId = watchChange.targetId;\n const expectedCount = watchChange.existenceFilter.count;\n\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n const target = targetData.target;\n if (target.isDocumentQuery()) {\n if (expectedCount === 0) {\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 key = new DocumentKey(target.path);\n this.removeDocumentFromTarget(\n targetId,\n key,\n new NoDocument(key, SnapshotVersion.forDeletedDoc())\n );\n } else {\n assert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n if (currentSize !== expectedCount) {\n // Existence filter mismatch: We reset the mapping and raise a new\n // snapshot with `isFromCache:true`.\n this.resetTarget(targetId);\n this.pendingTargetResets = this.pendingTargetResets.add(targetId);\n }\n }\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 */\n createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent {\n const targetChanges: { [targetId: number]: TargetChange } = {};\n\n objUtils.forEachNumber(this.targetStates, (targetId, targetState) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetData.target.isDocumentQuery()) {\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 //\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 key = new DocumentKey(targetData.target.path);\n if (\n this.pendingDocumentUpdates.get(key) === null &&\n !this.targetContainsDocument(targetId, key)\n ) {\n this.removeDocumentFromTarget(\n targetId,\n key,\n new NoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges[targetId] = targetState.toTargetChange();\n targetState.clearPendingChanges();\n }\n }\n });\n\n let resolvedLimboDocuments = documentKeySet();\n\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.pendingDocumentTargetMapping.forEach((key, targets) => {\n let isOnlyLimboTarget = true;\n\n targets.forEachWhile(targetId => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (\n targetData &&\n targetData.purpose !== TargetPurpose.LimboResolution\n ) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = maybeDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedSet<TargetId>(primitiveComparator);\n\n return remoteEvent;\n }\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 addDocumentToTarget(targetId: TargetId, document: MaybeDocument): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const changeType = this.targetContainsDocument(targetId, document.key)\n ? ChangeType.Modified\n : ChangeType.Added;\n\n const targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n document.key,\n document\n );\n\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(\n document.key,\n this.ensureDocumentTargetMapping(document.key).add(targetId)\n );\n }\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 removeDocumentFromTarget(\n targetId: TargetId,\n key: DocumentKey,\n updatedDocument: MaybeDocument | null\n ): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const targetState = this.ensureTargetState(targetId);\n if (this.targetContainsDocument(targetId, key)) {\n targetState.addDocumentChange(key, ChangeType.Removed);\n } else {\n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n targetState.removeDocumentChange(key);\n }\n\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).delete(targetId)\n );\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n key,\n updatedDocument\n );\n }\n }\n\n removeTarget(targetId: TargetId): void {\n delete this.targetStates[targetId];\n }\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 */\n private getCurrentDocumentCountForTarget(targetId: TargetId): number {\n const targetState = this.ensureTargetState(targetId);\n const targetChange = targetState.toTargetChange();\n return (\n this.metadataProvider.getRemoteKeysForTarget(targetId).size +\n targetChange.addedDocuments.size -\n targetChange.removedDocuments.size\n );\n }\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 */\n recordPendingTargetRequest(targetId: TargetId): void {\n // For each request we get we need to record we need a response for it.\n const targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n }\n\n private ensureTargetState(targetId: TargetId): TargetState {\n if (!this.targetStates[targetId]) {\n this.targetStates[targetId] = new TargetState();\n }\n\n return this.targetStates[targetId];\n }\n\n private ensureDocumentTargetMapping(key: DocumentKey): SortedSet<TargetId> {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet<TargetId>(primitiveComparator);\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(\n key,\n targetMapping\n );\n }\n\n return targetMapping;\n }\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 */\n protected isActiveTarget(targetId: TargetId): boolean {\n const targetActive = this.targetDataForActiveTarget(targetId) !== null;\n if (!targetActive) {\n debug(LOG_TAG, 'Detected inactive target', targetId);\n }\n return targetActive;\n }\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 */\n protected targetDataForActiveTarget(targetId: TargetId): TargetData | null {\n const targetState = this.targetStates[targetId];\n return targetState && targetState.isPending\n ? null\n : this.metadataProvider.getTargetDataForTarget(targetId);\n }\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 */\n private resetTarget(targetId: TargetId): void {\n assert(\n !this.targetStates[targetId].isPending,\n 'Should only reset active targets'\n );\n this.targetStates[targetId] = new TargetState();\n\n // Trigger removal for any documents currently mapped to this target.\n // These removals will be part of the initial snapshot if Watch does not\n // resend these documents.\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(key => {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n });\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */\n private targetContainsDocument(\n targetId: TargetId,\n key: DocumentKey\n ): boolean {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n }\n}\n\nfunction documentTargetMap(): SortedMap<DocumentKey, SortedSet<TargetId>> {\n return new SortedMap<DocumentKey, SortedSet<TargetId>>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap<DocumentKey, ChangeType> {\n return new SortedMap<DocumentKey, ChangeType>(DocumentKey.comparator);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { ProtoByteString, TargetId } from '../core/types';\nimport {\n documentKeySet,\n DocumentKeySet,\n maybeDocumentMap,\n MaybeDocumentMap,\n targetIdSet\n} from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\nimport { SortedSet } from '../util/sorted_set';\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 */\nexport class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n readonly snapshotVersion: SnapshotVersion,\n /**\n * A map from target to changes to the target. See TargetChange.\n */\n readonly targetChanges: { [targetId: number]: TargetChange },\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 readonly targetMismatches: SortedSet<TargetId>,\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 readonly documentUpdates: MaybeDocumentMap,\n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n readonly resolvedLimboDocuments: DocumentKeySet\n ) {}\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(\n targetId: TargetId,\n current: boolean\n ): RemoteEvent {\n const targetChanges = {\n [targetId]: TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current\n )\n };\n return new RemoteEvent(\n SnapshotVersion.MIN,\n targetChanges,\n targetIdSet(),\n maybeDocumentMap(),\n documentKeySet()\n );\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 */\nexport class TargetChange {\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 readonly resumeToken: ProtoByteString,\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 readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\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 */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean\n ): TargetChange {\n return new TargetChange(\n emptyByteString(),\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Blob } from '../api/blob';\nimport { GeoPoint } from '../api/geo_point';\nimport { Timestamp } from '../api/timestamp';\nimport { DatabaseId } from '../core/database_info';\nimport {\n Bound,\n Direction,\n FieldFilter,\n Filter,\n LimitType,\n Operator,\n OrderBy,\n Query\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ProtoByteString, TargetId } from '../core/types';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport * as fieldValue from '../model/field_value';\nimport {\n DeleteMutation,\n FieldMask,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n TransformMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as obj from '../util/obj';\nimport * as typeUtils from '../util/types';\n\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { ExistenceFilter } from './existence_filter';\nimport { mapCodeFromRpcCode, mapRpcCodeFromCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: api.OrderDirection } = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: api.FieldFilterOp } = {};\n ops[Operator.LESS_THAN.name] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN.name] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL.name] = 'EQUAL';\n ops[Operator.ARRAY_CONTAINS.name] = 'ARRAY_CONTAINS';\n ops[Operator.IN.name] = 'IN';\n ops[Operator.ARRAY_CONTAINS_ANY.name] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_REG_EXP = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n assert(!typeUtils.isNullOrUndefined(value), description + ' is missing');\n}\n\nfunction parseInt64(value: number | string): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return fail(\"can't parse \" + value);\n }\n}\n\n// This is a supplement to the generated proto interfaces, which fail to account\n// for the fact that a timestamp may be encoded as either a string OR this.\ninterface TimestampProto {\n seconds?: string;\n nanos?: number;\n}\n\nexport interface SerializerOptions {\n /**\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting this flag to true, the serializer will use the Proto3 JSON format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n */\n useProto3Json: boolean;\n}\n\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer {\n constructor(\n private databaseId: DatabaseId,\n private options: SerializerOptions\n ) {}\n\n private emptyByteString(): ProtoByteString {\n if (this.options.useProto3Json) {\n return '';\n } else {\n return new Uint8Array(0);\n }\n }\n\n private unsafeCastProtoByteString(byteString: ProtoByteString): string {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString as string;\n }\n\n fromRpcStatus(status: api.Status): FirestoreError {\n const code =\n status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n }\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 */\n private toInt32Value(val: number | null): number | null {\n if (this.options.useProto3Json || typeUtils.isNullOrUndefined(val)) {\n return val;\n } else {\n // ProtobufJS requires that we wrap Int32Values.\n // Use any because we need to match generated Proto types.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { value: val } as any;\n }\n }\n\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as accepting \"number\" because that's what\n * our generated proto interfaces say Int32Value must be, but it actually\n * accepts { value: number } to match our serialization in toInt32Value().\n */\n private fromInt32Value(val: number | undefined): number | null {\n let result;\n if (typeof val === 'object') {\n // Use any because we need to match generated Proto types.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n result = (val as any).value;\n } else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n return typeUtils.isNullOrUndefined(result) ? null : result;\n }\n\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n private toTimestamp(timestamp: Timestamp): string {\n if (this.options.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n }\n\n private fromTimestamp(date: string | TimestampProto): Timestamp {\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 (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return this.fromIso8601String(date);\n } else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = parseInt64(date.seconds || '0');\n const nanos = date.nanos || 0;\n return new Timestamp(seconds, nanos);\n }\n }\n\n private fromIso8601String(utc: string): Timestamp {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_REG_EXP.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const date = new Date(utc);\n const seconds = Math.floor(date.getTime() / 1000);\n\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n private toBytes(bytes: Blob): string {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n } else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n }\n\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n private fromBlob(blob: string | Uint8Array): Blob {\n if (typeof blob === 'string') {\n assert(\n this.options.useProto3Json,\n 'Expected bytes to be passed in as Uint8Array, but got a string instead.'\n );\n return Blob.fromBase64String(blob);\n } else {\n assert(\n !this.options.useProto3Json,\n 'Expected bytes to be passed in as Uint8Array, but got a string instead.'\n );\n return Blob.fromUint8Array(blob);\n }\n }\n\n toVersion(version: SnapshotVersion): string {\n return this.toTimestamp(version.toTimestamp());\n }\n\n fromVersion(version: string): SnapshotVersion {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n }\n\n toResourceName(databaseId: DatabaseId, path: ResourcePath): string {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n }\n\n fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n assert(\n this.isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n }\n\n toName(key: DocumentKey): string {\n return this.toResourceName(this.databaseId, key.path);\n }\n\n fromName(name: string): DocumentKey {\n const resource = this.fromResourceName(name);\n assert(\n resource.get(1) === this.databaseId.projectId,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId\n );\n assert(\n (!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database\n );\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\n }\n\n toQueryPath(path: ResourcePath): string {\n return this.toResourceName(this.databaseId, path);\n }\n\n fromQueryPath(name: string): ResourcePath {\n const resourceName = this.fromResourceName(name);\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 if (resourceName.length === 4) {\n return ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n }\n\n get encodedDatabaseId(): string {\n const path = new ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n }\n\n private fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n }\n\n private extractLocalPathFromResourceName(\n resourceName: ResourcePath\n ): ResourcePath {\n assert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n }\n\n private isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n }\n\n toValue(val: fieldValue.FieldValue): api.Value {\n if (val instanceof fieldValue.NullValue) {\n return { nullValue: 'NULL_VALUE' };\n } else if (val instanceof fieldValue.BooleanValue) {\n return { booleanValue: val.value() };\n } else if (val instanceof fieldValue.IntegerValue) {\n return { integerValue: '' + val.value() };\n } else if (val instanceof fieldValue.DoubleValue) {\n const doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' } as {};\n } else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' } as {};\n } else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' } as {};\n }\n }\n return { doubleValue: val.value() };\n } else if (val instanceof fieldValue.StringValue) {\n return { stringValue: val.value() };\n } else if (val instanceof fieldValue.ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n } else if (val instanceof fieldValue.ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n } else if (val instanceof fieldValue.TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n } else if (val instanceof fieldValue.GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n } else if (val instanceof fieldValue.BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n } else if (val instanceof fieldValue.RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n } else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n }\n\n fromValue(obj: api.Value): fieldValue.FieldValue {\n if ('nullValue' in obj) {\n return fieldValue.NullValue.INSTANCE;\n } else if ('booleanValue' in obj) {\n return fieldValue.BooleanValue.of(obj.booleanValue!);\n } else if ('integerValue' in obj) {\n return new fieldValue.IntegerValue(parseInt64(obj.integerValue!));\n } else if ('doubleValue' in obj) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if ((obj.doubleValue as {}) === 'NaN') {\n return fieldValue.DoubleValue.NAN;\n } else if ((obj.doubleValue as {}) === 'Infinity') {\n return fieldValue.DoubleValue.POSITIVE_INFINITY;\n } else if ((obj.doubleValue as {}) === '-Infinity') {\n return fieldValue.DoubleValue.NEGATIVE_INFINITY;\n }\n }\n\n return new fieldValue.DoubleValue(obj.doubleValue!);\n } else if ('stringValue' in obj) {\n return new fieldValue.StringValue(obj.stringValue!);\n } else if ('mapValue' in obj) {\n return this.fromFields(obj.mapValue!.fields || {});\n } else if ('arrayValue' in obj) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n const values = obj.arrayValue.values || [];\n return new fieldValue.ArrayValue(values.map(v => this.fromValue(v)));\n } else if ('timestampValue' in obj) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new fieldValue.TimestampValue(\n this.fromTimestamp(obj.timestampValue!)\n );\n } else if ('geoPointValue' in obj) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n const latitude = obj.geoPointValue.latitude || 0;\n const longitude = obj.geoPointValue.longitude || 0;\n return new fieldValue.GeoPointValue(new GeoPoint(latitude, longitude));\n } else if ('bytesValue' in obj) {\n assertPresent(obj.bytesValue, 'bytesValue');\n const blob = this.fromBlob(obj.bytesValue);\n return new fieldValue.BlobValue(blob);\n } else if ('referenceValue' in obj) {\n assertPresent(obj.referenceValue, 'referenceValue');\n const resourceName = this.fromResourceName(obj.referenceValue);\n const dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\n const key = new DocumentKey(\n this.extractLocalPathFromResourceName(resourceName)\n );\n return new fieldValue.RefValue(dbId, key);\n } else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n }\n\n /** Creates an api.Document from key and fields (but no create/update time) */\n toMutationDocument(\n key: DocumentKey,\n fields: fieldValue.ObjectValue\n ): api.Document {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n }\n\n toDocument(document: Document): api.Document {\n assert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data()),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n }\n\n fromDocument(\n document: api.Document,\n hasCommittedMutations?: boolean\n ): Document {\n const key = this.fromName(document.name!);\n const version = this.fromVersion(document.updateTime!);\n return new Document(\n key,\n version,\n { hasCommittedMutations: !!hasCommittedMutations },\n undefined,\n document,\n v => this.fromValue(v)\n );\n }\n\n toFields(fields: fieldValue.ObjectValue): { [key: string]: api.Value } {\n const result: { [key: string]: api.Value } = {};\n fields.forEach((key, value) => {\n result[key] = this.toValue(value);\n });\n return result;\n }\n\n fromFields(object: {}): fieldValue.ObjectValue {\n // Proto map<string, Value> gets mapped to Object, so cast it.\n const map = object as { [key: string]: api.Value };\n let result = fieldValue.ObjectValue.EMPTY;\n obj.forEach(map, (key, value) => {\n result = result.set(new FieldPath([key]), this.fromValue(value));\n });\n return result;\n }\n\n toMapValue(map: fieldValue.ObjectValue): api.MapValue {\n return {\n fields: this.toFields(map)\n };\n }\n\n toArrayValue(array: fieldValue.ArrayValue): api.ArrayValue {\n const result: api.Value[] = [];\n array.forEach(value => {\n result.push(this.toValue(value));\n });\n return { values: result };\n }\n\n private fromFound(doc: api.BatchGetDocumentsResponse): Document {\n assert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = this.fromName(doc.found.name);\n const version = this.fromVersion(doc.found.updateTime);\n return new Document(key, version, {}, undefined, doc.found, v =>\n this.fromValue(v)\n );\n }\n\n private fromMissing(result: api.BatchGetDocumentsResponse): NoDocument {\n assert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n assert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = this.fromName(result.missing);\n const version = this.fromVersion(result.readTime);\n return new NoDocument(key, version);\n }\n\n fromMaybeDocument(result: api.BatchGetDocumentsResponse): MaybeDocument {\n if ('found' in result) {\n return this.fromFound(result);\n } else if ('missing' in result) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n }\n\n private toWatchTargetChangeState(\n state: WatchTargetChangeState\n ): api.TargetChangeTargetChangeType {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n }\n\n toTestWatchChange(watchChange: WatchChange): api.ListenResponse {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof Document) {\n const doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data()),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n } else if (watchChange.newDoc instanceof NoDocument) {\n const doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n } else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof WatchTargetChange) {\n let cause: api.Status | undefined = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n }\n\n fromWatchChange(change: api.ListenResponse): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = this.fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n const resumeToken =\n change.targetChange.resumeToken || this.emptyByteString();\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = this.fromName(entityChange.document.name);\n const version = this.fromVersion(entityChange.document.updateTime);\n const doc = new Document(\n key,\n version,\n {},\n undefined,\n entityChange.document!,\n v => this.fromValue(v)\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = this.fromName(docDelete.document);\n const version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : SnapshotVersion.forDeletedDoc();\n const doc = new NoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = this.fromName(docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const count = filter.count || 0;\n const existenceFilter = new ExistenceFilter(count);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n }\n\n fromWatchTargetChangeState(\n state: api.TargetChangeTargetChangeType\n ): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n }\n\n versionFromListenResponse(change: api.ListenResponse): SnapshotVersion {\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 change)) {\n return SnapshotVersion.MIN;\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n }\n\n toMutation(mutation: Mutation): api.Write {\n let result: api.Write;\n if (mutation instanceof SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(transform =>\n this.toFieldTransform(transform)\n )\n }\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: this.toName(mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n\n return result;\n }\n\n fromMutation(proto: api.Write): Mutation {\n const precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : Precondition.NONE;\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = this.fromName(proto.update.name);\n const value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n const fieldMask = this.fromDocumentMask(proto.updateMask);\n return new PatchMutation(key, value, fieldMask, precondition);\n } else {\n return new SetMutation(key, value, precondition);\n }\n } else if (proto.delete) {\n const key = this.fromName(proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.transform) {\n const key = this.fromName(proto.transform.document!);\n const fieldTransforms = proto.transform.fieldTransforms!.map(transform =>\n this.fromFieldTransform(transform)\n );\n assert(\n precondition.exists === true,\n 'Transforms only support precondition \"exists == true\"'\n );\n return new TransformMutation(key, fieldTransforms);\n } else if (proto.verify) {\n const key = this.fromName(proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n }\n\n private toPrecondition(precondition: Precondition): api.Precondition {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n }\n\n private fromPrecondition(precondition: api.Precondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.NONE;\n }\n }\n\n private fromWriteResult(\n proto: api.WriteResult,\n commitTime: string\n ): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : this.fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.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 version = this.fromVersion(commitTime);\n }\n\n let transformResults: fieldValue.FieldValue[] | null = null;\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(result =>\n this.fromValue(result)\n );\n }\n return new MutationResult(version, transformResults);\n }\n\n fromWriteResults(\n protos: api.WriteResult[] | undefined,\n commitTime?: string\n ): MutationResult[] {\n if (protos && protos.length > 0) {\n assert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => this.fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n }\n\n private toFieldTransform(fieldTransform: FieldTransform): api.FieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements.map(v => this.toValue(v))\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements.map(v => this.toValue(v))\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: this.toValue(transform.operand)\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n }\n\n private fromFieldTransform(proto: api.FieldTransform): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n assert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = ServerTimestampTransform.instance;\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(\n values.map(v => this.fromValue(v))\n );\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(\n values.map(v => this.fromValue(v))\n );\n } else if ('increment' in proto) {\n const operand = this.fromValue(proto.increment!);\n assert(\n operand instanceof fieldValue.NumberValue,\n 'NUMERIC_ADD transform requires a NumberValue'\n );\n transform = new NumericIncrementTransformOperation(\n operand as fieldValue.NumberValue\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n }\n\n toDocumentsTarget(target: Target): api.DocumentsTarget {\n return { documents: [this.toQueryPath(target.path)] };\n }\n\n fromDocumentsTarget(documentsTarget: api.DocumentsTarget): Target {\n const count = documentsTarget.documents!.length;\n assert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return Query.atPath(this.fromQueryPath(name)).toTarget();\n }\n\n toQueryTarget(target: Target): api.QueryTarget {\n // Dissect the path into parent, collectionId, and optional key filter.\n const result: api.QueryTarget = { structuredQuery: {} };\n const path = target.path;\n if (target.collectionGroup !== null) {\n assert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n result.parent = this.toQueryPath(path);\n result.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n assert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n\n const where = this.toFilter(target.filters);\n if (where) {\n result.structuredQuery!.where = where;\n }\n\n const orderBy = this.toOrder(target.orderBy);\n if (orderBy) {\n result.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = this.toInt32Value(target.limit);\n if (limit !== null) {\n result.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n result.structuredQuery!.startAt = this.toCursor(target.startAt);\n }\n if (target.endAt) {\n result.structuredQuery!.endAt = this.toCursor(target.endAt);\n }\n\n return result;\n }\n\n fromQueryTarget(target: api.QueryTarget): Target {\n let path = this.fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n assert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n\n return new Query(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n ).toTarget();\n }\n\n toListenRequestLabels(\n targetData: TargetData\n ): api.ApiClientObjectMap<string> | null {\n const value = this.toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n }\n\n private toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n }\n\n toTarget(targetData: TargetData): api.Target {\n let result: api.Target;\n const target = targetData.target;\n\n if (target.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(target) };\n } else {\n result = { query: this.toQueryTarget(target) };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(\n targetData.resumeToken\n );\n }\n\n return result;\n }\n\n private toFilter(filters: Filter[]): api.Filter | undefined {\n if (filters.length === 0) {\n return;\n }\n const protos = filters.map(filter => {\n if (filter instanceof FieldFilter) {\n return this.toUnaryOrFieldFilter(filter);\n } else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n }\n\n private fromFilter(filter: api.Filter | undefined): Filter[] {\n if (!filter) {\n return [];\n } else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n } else if (filter.fieldFilter !== undefined) {\n return [this.fromFieldFilter(filter)];\n } else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter\n .filters!.map(f => this.fromFilter(f))\n .reduce((accum, current) => accum.concat(current));\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n }\n\n private toOrder(orderBys: OrderBy[]): api.Order[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => this.toPropertyOrder(order));\n }\n\n private fromOrder(orderBys: api.Order[]): OrderBy[] {\n return orderBys.map(order => this.fromPropertyOrder(order));\n }\n\n private toCursor(cursor: Bound): api.Cursor {\n return {\n before: cursor.before,\n values: cursor.position.map(component => this.toValue(component))\n };\n }\n\n private fromCursor(cursor: api.Cursor): Bound {\n const before = !!cursor.before;\n const position = cursor.values!.map(component => this.fromValue(component));\n return new Bound(position, before);\n }\n\n // visible for testing\n toDirection(dir: Direction): api.OrderDirection {\n return DIRECTIONS[dir.name];\n }\n\n // visible for testing\n fromDirection(dir: api.OrderDirection | undefined): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n }\n\n // visible for testing\n toOperatorName(op: Operator): api.FieldFilterOp {\n return OPERATORS[op.name];\n }\n\n fromOperatorName(op: api.FieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n }\n\n toFieldPathReference(path: FieldPath): api.FieldReference {\n return { fieldPath: path.canonicalString() };\n }\n\n fromFieldPathReference(fieldReference: api.FieldReference): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n }\n\n // visible for testing\n toPropertyOrder(orderBy: OrderBy): api.Order {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n }\n\n fromPropertyOrder(orderBy: api.Order): OrderBy {\n return new OrderBy(\n this.fromFieldPathReference(orderBy.field!),\n this.fromDirection(orderBy.direction)\n );\n }\n\n fromFieldFilter(filter: api.Filter): Filter {\n return FieldFilter.create(\n this.fromFieldPathReference(filter.fieldFilter!.field!),\n this.fromOperatorName(filter.fieldFilter!.op!),\n this.fromValue(filter.fieldFilter!.value!)\n );\n }\n\n // visible for testing\n toUnaryOrFieldFilter(filter: FieldFilter): api.Filter {\n if (filter.op === Operator.EQUAL) {\n if (filter.value.isEqual(fieldValue.DoubleValue.NAN)) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (filter.value.isEqual(fieldValue.NullValue.INSTANCE)) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n\n fromUnaryFilter(filter: api.Filter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = this.fromFieldPathReference(\n filter.unaryFilter!.field!\n );\n return FieldFilter.create(\n nanField,\n Operator.EQUAL,\n fieldValue.DoubleValue.NAN\n );\n case 'IS_NULL':\n const nullField = this.fromFieldPathReference(\n filter.unaryFilter!.field!\n );\n return FieldFilter.create(\n nullField,\n Operator.EQUAL,\n fieldValue.NullValue.INSTANCE\n );\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n }\n\n toDocumentMask(fieldMask: FieldMask): api.DocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n }\n\n fromDocumentMask(proto: api.DocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n const fields = paths.map(path => FieldPath.fromServerFormat(path));\n return FieldMask.fromArray(fields);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { ProtoByteString } from '../core/types';\nimport { Connection } from '../remote/connection';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { ConnectivityMonitor } from './../remote/connectivity_monitor';\n\n/**\n * Provides a common interface to load anything platform dependent, e.g.\n * the connection implementation.\n *\n * An implementation of this must be provided at compile time for the platform.\n */\n// TODO: Consider only exposing the APIs of 'document' and 'window' that we\n// use in our client.\nexport interface Platform {\n loadConnection(databaseInfo: DatabaseInfo): Promise<Connection>;\n newConnectivityMonitor(): ConnectivityMonitor;\n newSerializer(databaseId: DatabaseId): JsonProtoSerializer;\n\n /** Formats an object as a JSON string, suitable for logging. */\n formatJSON(value: unknown): string;\n\n /** Converts a Base64 encoded string to a binary string. */\n atob(encoded: string): string;\n\n /** Converts a binary string to a Base64 encoded string. */\n btoa(raw: string): string;\n\n /** The Platform's 'window' implementation or null if not available. */\n readonly window: Window | null;\n\n /** The Platform's 'document' implementation or null if not available. */\n readonly document: Document | null;\n\n /** True if and only if the Base64 conversion functions are available. */\n readonly base64Available: boolean;\n\n readonly emptyByteString: ProtoByteString;\n}\n\n/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nexport class PlatformSupport {\n private static platform: Platform;\n static setPlatform(platform: Platform): void {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n }\n\n static getPlatform(): Platform {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n }\n}\n\n/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nexport function emptyByteString(): ProtoByteString {\n return PlatformSupport.getPlatform().emptyByteString;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Code, FirestoreError } from './error';\n\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nexport function makeConstructorPrivate<T extends Function>(\n cls: T,\n optionalMessage?: string\n): T {\n function PublicConstructor(): never {\n let error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n\n // Copy any static methods/members\n for (const staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (PublicConstructor as any)[staticProperty] = (cls as any)[staticProperty];\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return PublicConstructor as any;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n invalidClassError,\n validateArgType,\n validateExactNumberOfArgs\n} from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable(): void {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(\n Code.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 (!PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'Blobs are unavailable in Firestore in this environment.'\n );\n }\n}\n\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nexport class Blob {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion.\n // A binary string is a string with each char as Unicode code point in the\n // range of [0, 255], essentially simulating a byte array.\n private _binaryString: string;\n\n private constructor(binaryString: string) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n\n static fromBase64String(base64: string): Blob {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n const binaryString = PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct Blob from Base64 string: ' + e\n );\n }\n }\n\n static fromUint8Array(array: Uint8Array): Blob {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n const binaryString = Array.prototype.map\n .call(array, (char: number) => {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n }\n\n toBase64(): string {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n }\n\n toUint8Array(): Uint8Array {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n const buffer = new Uint8Array(this._binaryString.length);\n for (let i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n }\n\n toString(): string {\n return 'Blob(base64: ' + this.toBase64() + ')';\n }\n\n isEqual(other: Blob): boolean {\n return this._binaryString === other._binaryString;\n }\n\n _approximateByteSize(): number {\n // Assume UTF-16 encoding in memory (see StringValue.approximateByteSize())\n return this._binaryString.length * 2;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: Blob): number {\n return primitiveComparator(this._binaryString, other._binaryString);\n }\n}\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\nexport const PublicBlob = makeConstructorPrivate(\n Blob,\n 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.'\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 Resolver<R> {\n (value?: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport interface CancelablePromise<T> extends Promise<T> {\n cancel(): void;\n}\n\nexport class Deferred<R> {\n promise: Promise<R>;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver<R>;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver<R>, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence<T>(\n values: T[],\n fn: (value: T) => Promise<void>\n): Promise<void> {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Equatable } from './misc';\nimport * as objUtil from './obj';\n\ntype Entry<K, V> = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap<KeyType extends Equatable<KeyType>, ValueType> {\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array<Entry<KeyType, ValueType>>;\n } = {};\n\n constructor(private mapKeyFn: (key: KeyType) => string) {}\n\n /** Get a value for this key, or undefined if it does not exist. */\n get(key: KeyType): ValueType | undefined {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (const [otherKey, value] of matches) {\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n return undefined;\n }\n\n has(key: KeyType): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Put this key and value in the map. */\n set(key: KeyType, value: ValueType): void {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n }\n\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n delete(key: KeyType): boolean {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n objUtil.forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return objUtil.isEmpty(this.inner);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId, ProtoByteString } from '../core/types';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentVersionMap,\n documentVersionMap,\n MaybeDocumentMap\n} from './collections';\nimport { MaybeDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation, MutationResult } from './mutation';\n\nexport const BATCHID_UNKNOWN = -1;\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\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(\n public batchId: BatchId,\n public localWriteTime: Timestamp,\n public baseMutations: Mutation[],\n public mutations: Mutation[]\n ) {\n assert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n docKey: DocumentKey,\n maybeDoc: MaybeDocument | null,\n batchResult: MutationBatchResult\n ): MaybeDocument | null {\n if (maybeDoc) {\n assert(\n maybeDoc.key.isEqual(docKey),\n `applyToRemoteDocument: key ${docKey} should match maybeDoc key\n ${maybeDoc.key}`\n );\n }\n\n const mutationResults = batchResult.mutationResults;\n assert(\n mutationResults.length === this.mutations.length,\n `Mismatch between mutations length\n (${this.mutations.length}) and mutation results length\n (${mutationResults.length}).`\n );\n\n for (let i = 0; i < this.mutations.length; i++) {\n const mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n const mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n applyToLocalView(\n docKey: DocumentKey,\n maybeDoc: MaybeDocument | null\n ): MaybeDocument | null {\n if (maybeDoc) {\n assert(\n maybeDoc.key.isEqual(docKey),\n `applyToLocalDocument: key ${docKey} should match maybeDoc key\n ${maybeDoc.key}`\n );\n }\n\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const mutation of this.baseMutations) {\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(\n maybeDoc,\n maybeDoc,\n this.localWriteTime\n );\n }\n }\n\n const baseDoc = maybeDoc;\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(\n maybeDoc,\n baseDoc,\n this.localWriteTime\n );\n }\n }\n return maybeDoc;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch.\n */\n applyToLocalDocumentSet(maybeDocs: MaybeDocumentMap): MaybeDocumentMap {\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 let mutatedDocuments = maybeDocs;\n this.mutations.forEach(m => {\n const mutatedDocument = this.applyToLocalView(\n m.key,\n maybeDocs.get(m.key)\n );\n if (mutatedDocument) {\n mutatedDocuments = mutatedDocuments.insert(m.key, mutatedDocument);\n }\n });\n return mutatedDocuments;\n }\n\n keys(): DocumentKeySet {\n return this.mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n }\n\n isEqual(other: MutationBatch): boolean {\n return (\n this.batchId === other.batchId &&\n misc.arrayEquals(this.mutations, other.mutations) &&\n misc.arrayEquals(this.baseMutations, other.baseMutations)\n );\n }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n private constructor(\n readonly batch: MutationBatch,\n readonly commitVersion: SnapshotVersion,\n readonly mutationResults: MutationResult[],\n readonly streamToken: ProtoByteString,\n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n readonly docVersions: DocumentVersionMap\n ) {}\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=>version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[],\n streamToken: ProtoByteString\n ): MutationBatchResult {\n assert(\n batch.mutations.length === results.length,\n 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length\n );\n\n let versionMap = documentVersionMap();\n const mutations = batch.mutations;\n for (let i = 0; i < mutations.length; i++) {\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\n }\n\n return new MutationBatchResult(\n batch,\n commitVersion,\n results,\n streamToken,\n versionMap\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\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 */\nexport class ReferenceSet {\n // A set of outstanding references to a document sorted by key.\n private refsByKey = new SortedSet(DocReference.compareByKey);\n\n // A set of outstanding references to a document sorted by target id.\n private refsByTarget = new SortedSet(DocReference.compareByTargetId);\n\n /** Returns true if the reference set contains no references. */\n isEmpty(): boolean {\n return this.refsByKey.isEmpty();\n }\n\n /** Adds a reference to the given document key for the given ID. */\n addReference(key: DocumentKey, id: TargetId | BatchId): void {\n const ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n }\n\n /** Add references to the given document keys for the given ID. */\n addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.addReference(key, id));\n }\n\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n removeReference(key: DocumentKey, id: TargetId | BatchId): void {\n this.removeRef(new DocReference(key, id));\n }\n\n removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.removeReference(key, id));\n }\n\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n removeReferencesForId(id: TargetId | BatchId): DocumentKey[] {\n const emptyKey = DocumentKey.EMPTY;\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n const keys: DocumentKey[] = [];\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n this.removeRef(ref);\n keys.push(ref.key);\n });\n return keys;\n }\n\n removeAllReferences(): void {\n this.refsByKey.forEach(ref => this.removeRef(ref));\n }\n\n private removeRef(ref: DocReference): void {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n }\n\n referencesForId(id: TargetId | BatchId): DocumentKeySet {\n const emptyKey = DocumentKey.EMPTY;\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n let keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n keys = keys.add(ref.key);\n });\n return keys;\n }\n\n containsKey(key: DocumentKey): boolean {\n const ref = new DocReference(key, 0);\n const firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n }\n}\n\nexport class DocReference {\n constructor(\n public key: DocumentKey,\n public targetOrBatchId: TargetId | BatchId\n ) {}\n\n /** Compare by key then by ID */\n static compareByKey(left: DocReference, right: DocReference): number {\n return (\n DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)\n );\n }\n\n /** Compare by ID then by key */\n static compareByTargetId(left: DocReference, right: DocReference): number {\n return (\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { fail } from '../util/assert';\n\nexport type FulfilledHandler<T, R> =\n | ((result: T) => R | PersistencePromise<R>)\n | null;\nexport type RejectedHandler<R> =\n | ((reason: Error) => R | PersistencePromise<R>)\n | null;\nexport type Resolver<T> = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\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 */\nexport class PersistencePromise<T> {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n private nextCallback: FulfilledHandler<T, unknown> = null;\n private catchCallback: RejectedHandler<unknown> = null;\n\n // When the operation resolves, we'll set result or error and mark isDone.\n private result: T | undefined = undefined;\n private error: Error | undefined = undefined;\n private isDone = false;\n\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n private callbackAttached = false;\n\n constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void) {\n callback(\n value => {\n this.isDone = true;\n this.result = value;\n if (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(value!);\n }\n },\n error => {\n this.isDone = true;\n this.error = error;\n if (this.catchCallback) {\n this.catchCallback(error);\n }\n }\n );\n }\n\n catch<R>(\n fn: (error: Error) => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n return this.next(undefined, fn);\n }\n\n next<R>(\n nextFn?: FulfilledHandler<T, R>,\n catchFn?: RejectedHandler<R>\n ): PersistencePromise<R> {\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result!);\n } else {\n return this.wrapFailure(catchFn, this.error);\n }\n } else {\n return new PersistencePromise<R>((resolve, reject) => {\n this.nextCallback = (value: T) => {\n this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n this.catchCallback = (error: Error) => {\n this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n }\n\n toPromise(): Promise<T> {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction<R>(\n fn: () => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n try {\n const result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject<R>(e);\n }\n }\n\n private wrapSuccess<R>(\n nextFn: FulfilledHandler<T, R> | undefined,\n value: T\n ): PersistencePromise<R> {\n if (nextFn) {\n return this.wrapUserFunction(() => nextFn(value));\n } else {\n // If there's no nextFn, then R must be the same as T\n return PersistencePromise.resolve<R>((value as unknown) as R);\n }\n }\n\n private wrapFailure<R>(\n catchFn: RejectedHandler<R> | undefined,\n error: Error\n ): PersistencePromise<R> {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject<R>(error);\n }\n }\n\n static resolve(): PersistencePromise<void>;\n static resolve<R>(result: R): PersistencePromise<R>;\n static resolve<R>(result?: R): PersistencePromise<R | void> {\n return new PersistencePromise<R | void>((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject<R>(error: Error): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n reject(error);\n });\n }\n\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n all: { forEach: (cb: (el: PersistencePromise<any>) => void) => void }\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n let expectedCount = 0;\n let resolvedCount = 0;\n let done = false;\n\n all.forEach(element => {\n ++expectedCount;\n element.next(\n () => {\n ++resolvedCount;\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n },\n err => reject(err)\n );\n });\n\n done = true;\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\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 */\n static or(\n predicates: Array<() => PersistencePromise<boolean>>\n ): PersistencePromise<boolean> {\n let p: PersistencePromise<boolean> = PersistencePromise.resolve<boolean>(\n false\n );\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve<boolean>(isTrue);\n } else {\n return predicate();\n }\n });\n }\n return p;\n }\n\n /**\n * Given an iterable, call the given function on each element in the\n * collection and wait for all of the resulting concurrent PersistencePromises\n * to resolve.\n */\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise<void>)\n | ((r: R) => PersistencePromise<void>)\n ): PersistencePromise<void>;\n static forEach<R>(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise<void>\n ): PersistencePromise<void>;\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise<void>\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n collection.forEach((r, s) => {\n promises.push(f.call(this, r, s));\n });\n return this.waitFor(promises);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { DocumentKeySet, NullableMaybeDocumentMap } from '../model/collections';\nimport { MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { assert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SnapshotVersion } from '../core/snapshot_version';\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 */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written (or null if any\n // existing cache entry should be removed).\n protected changes: ObjectMap<\n DocumentKey,\n MaybeDocument | null\n > = new ObjectMap(key => key.toString());\n\n // The read time to use for all added documents in this change buffer.\n private _readTime: SnapshotVersion | undefined;\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null>;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap>;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void>;\n\n protected set readTime(value: SnapshotVersion) {\n // Right now (for simplicity) we just track a single readTime for all the\n // added entries since we expect them to all be the same, but we could\n // rework to store per-entry readTimes if necessary.\n assert(\n this._readTime === undefined || this._readTime.isEqual(value),\n 'All changes in a RemoteDocumentChangeBuffer must have the same read time'\n );\n this._readTime = value;\n }\n\n protected get readTime(): SnapshotVersion {\n assert(\n this._readTime !== undefined,\n 'Read time is not set. All removeEntry() calls must include a readTime if `trackRemovals` is used.'\n );\n return this._readTime;\n }\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 */\n addEntry(maybeDocument: MaybeDocument, readTime: SnapshotVersion): void {\n this.assertNotApplied();\n this.readTime = readTime;\n this.changes.set(maybeDocument.key, maybeDocument);\n }\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 */\n removeEntry(key: DocumentKey, readTime?: SnapshotVersion): void {\n this.assertNotApplied();\n if (readTime) {\n this.readTime = readTime;\n }\n this.changes.set(key, null);\n }\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 * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve<MaybeDocument | null>(bufferedEntry);\n } else {\n return this.getFromCache(transaction, documentKey);\n }\n }\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 * @return A map of cached `Document`s or `NoDocument`s, indexed by key. If an\n * entry cannot be found, the corresponding key will be mapped to a null\n * value.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n return this.getAllFromCache(transaction, documentKeys);\n }\n\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n apply(transaction: PersistenceTransaction): PersistencePromise<void> {\n this.assertNotApplied();\n this.changesApplied = true;\n return this.applyChanges(transaction);\n }\n\n /** Helper to assert this.changes is not null */\n protected assertNotApplied(): void {\n assert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { User } from '../auth/user';\n\nimport { ListenSequenceNumber } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetCache } from './target_cache';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { ClientId } from './shared_client_state';\nimport { TargetData } from './target_data';\n\nexport const PRIMARY_LEASE_LOST_ERROR_MSG =\n 'The current tab is not in the required state to perform this operation. ' +\n '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 */\nexport abstract class PersistenceTransaction {\n private readonly onCommittedListeners: Array<() => void> = [];\n\n abstract readonly currentSequenceNumber: ListenSequenceNumber;\n\n addOnCommittedListener(listener: () => void): void {\n this.onCommittedListeners.push(listener);\n }\n\n raiseOnCommittedEvent(): void {\n this.onCommittedListeners.forEach(listener => listener());\n }\n}\n\n/** The different modes supported by `IndexedDbPersistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary'\n | 'readonly-idempotent'\n | 'readwrite-idempotent'\n | 'readwrite-primary-idempotent';\n\n/**\n * Callback type for primary state notifications. This callback can be\n * registered with the persistence layer to get notified when we transition from\n * primary to secondary state and vice versa.\n *\n * Note: Instances can only toggle between Primary and Secondary state if\n * IndexedDB persistence is enabled and multiple clients are active. If this\n * listener is registered with MemoryPersistence, the callback will be called\n * exactly once marking the current instance as Primary.\n */\nexport type PrimaryStateListener = (isPrimary: boolean) => Promise<void>;\n\n/**\n * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This\n * includes being added to a target, being removed from a target, being subject to mutation, and\n * being mutated by the user.\n *\n * Different implementations may do different things with each of these events. Not every\n * implementation needs to do something with every lifecycle hook.\n *\n * PORTING NOTE: since sequence numbers are attached to transactions in this\n * client, the ReferenceDelegate does not need to deal in transactional\n * semantics (onTransactionStarted/Committed()), nor does it need to track and\n * generate sequence numbers (getCurrentSequenceNumber()).\n */\nexport interface ReferenceDelegate {\n /**\n * Registers a ReferenceSet of documents that should be considered 'referenced' and not eligible\n * for removal during garbage collection.\n */\n setInMemoryPins(pins: ReferenceSet): void;\n\n /** Notify the delegate that the given document was added to a target. */\n addReference(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n\n /** Notify the delegate that the given document was removed from a target. */\n removeReference(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n\n /**\n * Notify the delegate that a target was removed. The delegate may, but is not obligated to,\n * actually delete the target and associated data.\n */\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void>;\n\n /** Notify the delegate that a document is no longer being mutated by the user. */\n removeMutationReference(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n\n /** Notify the delegate that a limbo document was updated. */\n updateLimboDocument(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n}\n\n/**\n * Persistence is the lowest-level shared interface to persistent storage in\n * Firestore.\n *\n * Persistence is used to create MutationQueue and RemoteDocumentCache\n * instances backed by persistence (which might be in-memory or LevelDB).\n *\n * Persistence also exposes an API to create and run PersistenceTransactions\n * against persistence. All read / write operations must be wrapped in a\n * transaction. Implementations of PersistenceTransaction / Persistence only\n * need to guarantee that writes made against the transaction are not made to\n * durable storage until the transaction resolves its PersistencePromise.\n * Since memory-only storage components do not alter durable storage, they are\n * free to ignore the transaction.\n *\n * This contract is enough to allow the LocalStore be be written\n * independently of whether or not the stored state actually is durably\n * persisted. If persistent storage is enabled, writes are grouped together to\n * avoid inconsistent state that could cause crashes.\n *\n * Concretely, when persistent storage is enabled, the persistent versions of\n * MutationQueue, RemoteDocumentCache, and others (the mutators) will\n * defer their writes into a transaction. Once the local store has completed\n * one logical operation, it commits the transaction.\n *\n * When persistent storage is disabled, the non-persistent versions of the\n * mutators ignore the transaction. This short-cut is allowed because\n * memory-only storage leaves no state so it cannot be inconsistent.\n *\n * This simplifies the implementations of the mutators and allows memory-only\n * implementations to supplement the persistent ones without requiring any\n * special dual-store implementation of Persistence. The cost is that the\n * LocalStore needs to be slightly careful about the order of its reads and\n * writes in order to avoid relying on being able to read back uncommitted\n * writes.\n */\nexport interface Persistence {\n /**\n * Whether or not this persistence instance has been started.\n */\n readonly started: boolean;\n\n readonly referenceDelegate: ReferenceDelegate;\n\n /**\n * Releases any resources held during eager shutdown.\n */\n shutdown(): Promise<void>;\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 */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise<void>;\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 */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise<void>\n ): void;\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 */\n setNetworkEnabled(networkEnabled: boolean): void;\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 */\n getActiveClients(): Promise<ClientId[]>;\n\n /**\n * Returns a MutationQueue representing the persisted mutations for the\n * given user.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called for a given user. In particular, the memory-backed\n * implementation does this to emulate the persisted implementation to the\n * extent possible (e.g. in the case of uid switching from\n * sally=>jack=>sally, sally's mutation queue will be preserved).\n */\n getMutationQueue(user: User): MutationQueue;\n\n /**\n * Returns a TargetCache representing the persisted cache of targets.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called. In particular, the memory-backed implementation does this\n * to emulate the persisted implementation to the extent possible.\n */\n getTargetCache(): TargetCache;\n\n /**\n * Returns a RemoteDocumentCache representing the persisted cache of remote\n * documents.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called. In particular, the memory-backed implementation does this\n * to emulate the persisted implementation to the extent possible.\n */\n getRemoteDocumentCache(): RemoteDocumentCache;\n\n /**\n * Returns an IndexManager instance that manages our persisted query indexes.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called. In particular, the memory-backed implementation does this\n * to emulate the persisted implementation to the extent possible.\n */\n getIndexManager(): IndexManager;\n\n /**\n * Performs an operation inside a persistence transaction. Any reads or writes\n * against persistence must be performed within a transaction. Writes will be\n * committed atomically once the transaction completes.\n *\n * Persistence operations are asynchronous and therefore the provided\n * transactionOperation must return a PersistencePromise. When it is resolved,\n * the transaction will be committed and the Promise returned by this method\n * will resolve.\n *\n * @param action A description of the action performed by this transaction,\n * used for logging.\n * @param mode The underlying mode of the IndexedDb transaction. Can be\n * 'readonly`, 'readwrite' or 'readwrite-primary'. Transactions marked\n * 'readwrite-primary' can only be executed by the primary client. In this\n * mode, the transactionOperation will not be run if the primary lease cannot\n * be acquired and the returned promise will be rejected with a\n * FAILED_PRECONDITION error.\n * @param transactionOperation The operation to run inside a transaction.\n * @return A promise that is resolved once the transaction completes.\n */\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T>;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Query } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap,\n documentMap,\n MaybeDocumentMap,\n maybeDocumentMap,\n NullableMaybeDocumentMap,\n nullableMaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\n\nimport { assert } from '../util/assert';\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { PatchMutation } from '../model/mutation';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { RemoteDocumentCache } from './remote_document_cache';\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 */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, key)\n .next(batches => this.getDocumentInternal(transaction, key, batches));\n }\n\n /** Internal version of `getDocument` that allows reusing batches. */\n private getDocumentInternal(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n inBatches: MutationBatch[]\n ): PersistencePromise<MaybeDocument | null> {\n return this.remoteDocumentCache.getEntry(transaction, key).next(doc => {\n for (const batch of inBatches) {\n doc = batch.applyToLocalView(key, doc);\n }\n return doc;\n });\n }\n\n // Returns the view of the given `docs` as they would appear after applying\n // all mutations in the given `batches`.\n private applyLocalMutationsToDocuments(\n transaction: PersistenceTransaction,\n docs: NullableMaybeDocumentMap,\n batches: MutationBatch[]\n ): NullableMaybeDocumentMap {\n let results = nullableMaybeDocumentMap();\n docs.forEach((key, localView) => {\n for (const batch of batches) {\n localView = batch.applyToLocalView(key, localView);\n }\n results = results.insert(key, localView);\n });\n return results;\n }\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 */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise<MaybeDocumentMap> {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs => this.getLocalViewOfDocuments(transaction, docs));\n }\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 getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n baseDocs: NullableMaybeDocumentMap\n ): PersistencePromise<MaybeDocumentMap> {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, baseDocs)\n .next(batches => {\n const docs = this.applyLocalMutationsToDocuments(\n transaction,\n baseDocs,\n batches\n );\n let results = maybeDocumentMap();\n docs.forEach((key, maybeDoc) => {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n });\n\n return results;\n });\n }\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 sinceReadTime If not set to SnapshotVersion.MIN, return only\n * documents that have been read since this snapshot version (exclusive).\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n if (query.isDocumentQuery()) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (query.isCollectionGroupQuery()) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n sinceReadTime\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n sinceReadTime\n );\n }\n }\n\n private getDocumentsMatchingDocumentQuery(\n transaction: PersistenceTransaction,\n docPath: ResourcePath\n ): PersistencePromise<DocumentMap> {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(\n maybeDoc => {\n let result = documentMap();\n if (maybeDoc instanceof Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n assert(\n query.path.isEmpty(),\n 'Currently we only support collection group queries at the root.'\n );\n const collectionId = query.collectionGroup!;\n let results = documentMap();\n return this.indexManager\n .getCollectionParents(transaction, collectionId)\n .next(parents => {\n // Perform a collection query against each parent that contains the\n // collectionId and aggregate the results.\n return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n const collectionQuery = query.asCollectionQueryAtPath(\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n sinceReadTime\n ).next(r => {\n r.forEach((key, doc) => {\n results = results.insert(key, doc);\n });\n });\n }).next(() => results);\n });\n }\n\n private getDocumentsMatchingCollectionQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n // Query the remote documents and overlay mutations.\n let results: DocumentMap;\n let mutationBatches: MutationBatch[];\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query, sinceReadTime)\n .next(queryResults => {\n results = queryResults;\n return this.mutationQueue.getAllMutationBatchesAffectingQuery(\n transaction,\n query\n );\n })\n .next(matchingMutationBatches => {\n mutationBatches = matchingMutationBatches;\n // It is possible that a PatchMutation can make a document match a query, even if\n // the version in the RemoteDocumentCache is not a match yet (waiting for server\n // to ack). To handle this, we find all document keys affected by the PatchMutations\n // that are not in `result` yet, and back fill them via `remoteDocumentCache.getEntries`,\n // otherwise those `PatchMutations` will be ignored because no base document can be found,\n // and lead to missing result for the query.\n return this.addMissingBaseDocuments(\n transaction,\n mutationBatches,\n results\n ).next(mergedDocuments => {\n results = mergedDocuments;\n\n for (const batch of mutationBatches) {\n for (const mutation of batch.mutations) {\n const key = mutation.key;\n const baseDoc = results.get(key);\n const mutatedDoc = mutation.applyToLocalView(\n baseDoc,\n baseDoc,\n batch.localWriteTime\n );\n if (mutatedDoc instanceof Document) {\n results = results.insert(key, mutatedDoc);\n } else {\n results = results.remove(key);\n }\n }\n }\n });\n })\n .next(() => {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach((key, doc) => {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n\n return results;\n });\n }\n\n private addMissingBaseDocuments(\n transaction: PersistenceTransaction,\n matchingMutationBatches: MutationBatch[],\n existingDocuments: DocumentMap\n ): PersistencePromise<DocumentMap> {\n let missingBaseDocEntriesForPatching = documentKeySet();\n for (const batch of matchingMutationBatches) {\n for (const mutation of batch.mutations) {\n if (\n mutation instanceof PatchMutation &&\n existingDocuments.get(mutation.key) === null\n ) {\n missingBaseDocEntriesForPatching = missingBaseDocEntriesForPatching.add(\n mutation.key\n );\n }\n }\n }\n\n let mergedDocuments = existingDocuments;\n return this.remoteDocumentCache\n .getEntries(transaction, missingBaseDocEntriesForPatching)\n .next(missingBaseDocs => {\n missingBaseDocs.forEach((key, doc) => {\n if (doc !== null && doc instanceof Document) {\n mergedDocuments = mergedDocuments.insert(key, doc);\n }\n });\n return mergedDocuments;\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { TargetId } from '../core/types';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\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 */\nexport class LocalViewChanges {\n constructor(\n readonly targetId: TargetId,\n readonly fromCache: boolean,\n readonly addedKeys: DocumentKeySet,\n readonly removedKeys: DocumentKeySet\n ) {}\n\n static fromSnapshot(\n targetId: TargetId,\n viewSnapshot: ViewSnapshot\n ): LocalViewChanges {\n let addedKeys = documentKeySet();\n let removedKeys = documentKeySet();\n\n for (const docChange of viewSnapshot.docChanges) {\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n // do nothing\n }\n }\n\n return new LocalViewChanges(\n targetId,\n viewSnapshot.fromCache,\n addedKeys,\n removedKeys\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\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 { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\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 */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert, fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as log from './log';\nimport { CancelablePromise, Deferred } from './promise';\n\n// Accept any return type from setTimeout().\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 4 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n RetryTransaction = 'retry_transaction'\n}\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 */\nclass DelayedOperation<T extends unknown> implements CancelablePromise<T> {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred<T>();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise<T>,\n private readonly removalCallback: (op: DelayedOperation<T>) => void\n ) {\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(err => {});\n }\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 */\n static createAndSchedule<R extends unknown>(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<R>,\n removalCallback: (op: DelayedOperation<R>) => void\n ): DelayedOperation<R> {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\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 */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n // Promise implementation.\n readonly [Symbol.toStringTag]: 'Promise';\n then = this.deferred.promise.then.bind(this.deferred.promise);\n catch = this.deferred.promise.catch.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport class AsyncQueue {\n // The last promise in the queue.\n private tail: Promise<unknown> = Promise.resolve();\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array<DelayedOperation<unknown>> = [];\n\n // visible for testing\n failure: Error | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\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 */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenAfterShutdown<T extends unknown>(\n op: () => Promise<T>\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue.\n */\n private enqueueEvenAfterShutdown<T extends unknown>(\n op: () => Promise<T>\n ): Promise<T> {\n this.verifyNotFailed();\n return this.enqueueInternal(op);\n }\n\n /**\n * Adds a new operation to the queue and initialize the shut down of this queue.\n * Returns a promise that will be resolved when the promise returned by the new\n * operation is (with its value).\n * Once this method is called, the only possible way to request running an operation\n * is through `enqueueAndForgetEvenAfterShutdown`.\n */\n async enqueueAndInitiateShutdown(op: () => Promise<void>): Promise<void> {\n this.verifyNotFailed();\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n await this.enqueueEvenAfterShutdown(op);\n }\n }\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise<T>(resolve => {});\n }\n return this.enqueueInternal(op);\n }\n\n private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = error.stack || error.message || '';\n log.error('INTERNAL UNHANDLED ERROR: ', message);\n\n // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(() => {\n throw error;\n }, 0);\n }\n\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 error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\n * the operation prior to its running.\n */\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): CancelablePromise<T> {\n this.verifyNotFailed();\n\n assert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule<T>(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(\n 'AsyncQueue is already failed: ' +\n (this.failure.stack || this.failure.message)\n );\n }\n }\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void {\n assert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n drain(): Promise<void> {\n // It should still be possible to drain the queue after it is shutting down.\n return this.enqueueEvenAfterShutdown(() => Promise.resolve());\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId Delayed operations up to and including this TimerId will\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\n * all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runDelayedOperationsEarly(lastTimerId: TimerId): Promise<void> {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n assert(\n lastTimerId === TimerId.All ||\n this.containsDelayedOperation(lastTimerId),\n `Attempted to drain to missing operation ${lastTimerId}`\n );\n\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation<unknown>): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n assert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\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 { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { assert } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { CancelablePromise } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetData } from './target_data';\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have reference delegates that\n * implement this interface. This interface defines the operations that the LRU garbage collector\n * needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise<void>;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number>;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void>;\n\n /**\n * Removes all targets that have a sequence number less than or equal to `upperBound`, and are not\n * present in the `activeTargetIds` set.\n *\n * @return the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence number less than or\n * equal to the given `upperBound`.\n *\n * @return the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap<TargetId, unknown>;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\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 */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\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 * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\nconst GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport class LruParams {\n static readonly COLLECTION_DISABLED = -1;\n static readonly MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n static readonly DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LruParams.DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LruParams.COLLECTION_DISABLED,\n 0,\n 0\n );\n\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 readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\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 readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\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 */\nexport class LruScheduler {\n private hasRun: boolean = false;\n private gcTask: CancelablePromise<void> | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n assert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LruParams.COLLECTION_DISABLED\n ) {\n this.scheduleGC();\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(): void {\n assert(this.gcTask === null, 'Cannot schedule GC while a task is pending');\n const delay = this.hasRun ? REGULAR_GC_DELAY_MS : INITIAL_GC_DELAY_MS;\n log.debug(\n 'LruGarbageCollector',\n `Garbage collection scheduled in ${delay}ms`\n );\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n () => {\n this.gcTask = null;\n this.hasRun = true;\n return this.localStore\n .collectGarbage(this.garbageCollector)\n .then(() => this.scheduleGC())\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n );\n }\n}\n\n/** Implements the steps for LRU garbage collection. */\nexport class LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number> {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<ListenSequenceNumber> {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n /**\n * Removes targets with a sequence number equal to or less than the given upper bound, and removes\n * document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n /**\n * Removes documents that have a sequence number equal to or less than the upper bound and are not\n * otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n if (\n this.params.cacheSizeCollectionThreshold === LruParams.COLLECTION_DISABLED\n ) {\n log.debug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n log.debug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n log.debug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect = this.params\n .maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (log.getLogLevel() <= log.LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n log.debug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve<LruResults>({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { User } from '../auth/user';\nimport { Query } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { BatchId, ProtoByteString, TargetId } from '../core/types';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap,\n maybeDocumentMap,\n MaybeDocumentMap\n} from '../model/collections';\nimport { MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation, PatchMutation, Precondition } from '../model/mutation';\nimport {\n BATCHID_UNKNOWN,\n MutationBatch,\n MutationBatchResult\n} from '../model/mutation_batch';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport {\n Persistence,\n PersistenceTransaction,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetCache } from './target_cache';\nimport { QueryEngine } from './query_engine';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { TargetData, TargetPurpose } from './target_data';\n\nconst LOG_TAG = 'LocalStore';\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: MaybeDocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: MaybeDocumentMap;\n readonly removedBatchIds: BatchId[];\n readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n readonly documents: DocumentMap;\n readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nexport class LocalStore {\n /**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\n private static readonly RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationQueue;\n\n /** The set of all cached remote documents. */\n private remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n private localDocuments: LocalDocumentsView;\n\n /**\n * The set of document references maintained by any local views.\n */\n private localViewReferences = new ReferenceSet();\n\n /** Maps a target to its `TargetData`. */\n private targetCache: TargetCache;\n\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 private targetDataByTarget = new SortedMap<TargetId, TargetData>(\n primitiveComparator\n );\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n private targetIdByTarget = new ObjectMap<Target, TargetId>(t =>\n t.canonicalId()\n );\n\n /**\n * The read time of the last entry processed by `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n private lastDocumentChangeReadTime = SnapshotVersion.MIN;\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n private persistence: Persistence,\n private queryEngine: QueryEngine,\n initialUser: User\n ) {\n assert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.persistence.referenceDelegate.setInMemoryPins(\n this.localViewReferences\n );\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.persistence.getIndexManager()\n );\n this.queryEngine.setLocalDocumentsView(this.localDocuments);\n }\n\n /** Starts the LocalStore. */\n start(): Promise<void> {\n return this.synchronizeLastDocumentChangeReadTime();\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.\n async handleUserChange(user: User): Promise<UserChangeResult> {\n let newMutationQueue = this.mutationQueue;\n let newLocalDocuments = this.localDocuments;\n\n const result = await this.persistence.runTransaction(\n 'Handle user change',\n 'readonly-idempotent',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return this.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n\n newMutationQueue = this.persistence.getMutationQueue(user);\n\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n newLocalDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n newMutationQueue,\n this.persistence.getIndexManager()\n );\n return newMutationQueue.getAllMutationBatches(txn);\n })\n .next(newBatches => {\n const removedBatchIds: BatchId[] = [];\n const addedBatchIds: BatchId[] = [];\n\n // Union the old/new changed keys.\n let changedKeys = documentKeySet();\n\n for (const batch of oldBatches) {\n removedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (const batch of newBatches) {\n addedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\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 newLocalDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n this.mutationQueue = newMutationQueue;\n this.localDocuments = newLocalDocuments;\n this.queryEngine.setLocalDocumentsView(this.localDocuments);\n\n return result;\n }\n\n /* Accept locally generated Mutations and commit them to storage. */\n localWrite(mutations: Mutation[]): Promise<LocalWriteResult> {\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n\n let existingDocs: MaybeDocumentMap;\n\n return this.persistence\n .runTransaction(\n 'Locally write mutations',\n 'readwrite-idempotent',\n txn => {\n // Load and apply all existing mutations. This lets us compute the\n // current base state for all non-idempotent transforms before applying\n // any additional user-provided writes.\n return this.localDocuments.getDocuments(txn, keys).next(docs => {\n existingDocs = docs;\n\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 baseMutations: Mutation[] = [];\n\n for (const mutation of mutations) {\n const baseValue = mutation.extractBaseValue(\n existingDocs.get(mutation.key)\n );\n if (baseValue != null) {\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 baseMutations.push(\n new PatchMutation(\n mutation.key,\n baseValue,\n baseValue.fieldMask(),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return this.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n });\n }\n )\n .then(batch => {\n const changes = batch.applyToLocalDocumentSet(existingDocs);\n return { batchId: batch.batchId, changes };\n });\n }\n\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-tab only.\n lookupMutationDocuments(batchId: BatchId): Promise<MaybeDocumentMap | null> {\n return this.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly-idempotent',\n txn => {\n return this.mutationQueue\n .lookupMutationKeys(txn, batchId)\n .next(keys => {\n if (keys) {\n return this.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise<MaybeDocumentMap | null>;\n } else {\n return PersistencePromise.resolve<MaybeDocumentMap | null>(null);\n }\n });\n }\n );\n }\n\n /**\n * Acknowledge 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 */\n acknowledgeBatch(\n batchResult: MutationBatchResult\n ): Promise<MaybeDocumentMap> {\n return this.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary-idempotent',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = this.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(() =>\n this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer)\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => this.mutationQueue.performConsistencyCheck(txn))\n .next(() => this.localDocuments.getDocuments(txn, affected));\n }\n );\n }\n\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n rejectBatch(batchId: BatchId): Promise<MaybeDocumentMap> {\n return this.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary-idempotent',\n txn => {\n let affectedKeys: DocumentKeySet;\n return this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n assert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return this.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => {\n return this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(() => {\n return this.localDocuments.getDocuments(txn, affectedKeys);\n });\n }\n );\n }\n\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending server response.\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\n getHighestUnacknowledgedBatchId(): Promise<BatchId> {\n return this.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly-idempotent',\n txn => {\n return this.mutationQueue.getHighestUnacknowledgedBatchId(txn);\n }\n );\n }\n\n /** Returns the last recorded stream token for the current user. */\n getLastStreamToken(): Promise<ProtoByteString> {\n return this.persistence.runTransaction(\n 'Get last stream token',\n 'readonly-idempotent',\n txn => {\n return this.mutationQueue.getLastStreamToken(txn);\n }\n );\n }\n\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n setLastStreamToken(streamToken: ProtoByteString): Promise<void> {\n return this.persistence.runTransaction(\n 'Set last stream token',\n 'readwrite-primary-idempotent',\n txn => {\n return this.mutationQueue.setLastStreamToken(txn, streamToken);\n }\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 */\n getLastRemoteSnapshotVersion(): Promise<SnapshotVersion> {\n return this.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly-idempotent',\n txn => this.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n }\n\n /**\n * Update 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 */\n applyRemoteEvent(remoteEvent: RemoteEvent): Promise<MaybeDocumentMap> {\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = this.targetDataByTarget;\n\n return this.persistence\n .runTransaction(\n 'Apply remote event',\n 'readwrite-primary-idempotent',\n txn => {\n const documentBuffer = this.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n newTargetDataByTargetMap = this.targetDataByTarget;\n\n const promises = [] as Array<PersistencePromise<void>>;\n objUtils.forEachNumber(\n remoteEvent.targetChanges,\n (targetId: TargetId, change: TargetChange) => {\n const oldTargetData = newTargetDataByTargetMap.get(targetId);\n if (!oldTargetData) {\n return;\n }\n\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 promises.push(\n this.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return this.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n const resumeToken = change.resumeToken;\n // Update the resume token if the change includes one.\n if (resumeToken.length > 0) {\n const newTargetData = oldTargetData\n .withResumeToken(resumeToken, remoteVersion)\n .withSequenceNumber(txn.currentSequenceNumber);\n newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n targetId,\n newTargetData\n );\n\n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n if (\n LocalStore.shouldPersistTargetData(\n oldTargetData,\n newTargetData,\n change\n )\n ) {\n promises.push(\n this.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n }\n }\n );\n\n let changedDocs = maybeDocumentMap();\n let updatedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach((key, doc) => {\n updatedKeys = updatedKeys.add(key);\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all the remote\n // documents in advance in a single call.\n promises.push(\n documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n remoteEvent.documentUpdates.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key);\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 if (\n doc instanceof NoDocument &&\n doc.version.isEqual(SnapshotVersion.MIN)\n ) {\n // NoDocuments with SnapshotVersion.MIN are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n documentBuffer.removeEntry(key, remoteVersion);\n changedDocs = changedDocs.insert(key, doc);\n } else if (\n existingDoc == null ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n assert(\n !SnapshotVersion.MIN.isEqual(remoteVersion),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc, remoteVersion);\n changedDocs = changedDocs.insert(key, doc);\n } else {\n log.debug(\n LOG_TAG,\n 'Ignoring outdated watch update for ',\n key,\n '. Current version:',\n existingDoc.version,\n ' Watch version:',\n doc.version\n );\n }\n\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n this.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n })\n );\n\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 (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\n const updateRemoteVersion = this.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n assert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return this.targetCache.setTargetsMetadata(\n txn,\n txn.currentSequenceNumber,\n remoteVersion\n );\n });\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises)\n .next(() => documentBuffer.apply(txn))\n .next(() => {\n return this.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs\n );\n });\n }\n )\n .then(changedDocs => {\n this.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n }\n\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 private static shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n ): boolean {\n assert(\n newTargetData.resumeToken.length > 0,\n 'Attempted to persist target data with no resume token'\n );\n\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.length === 0) {\n return true;\n }\n\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 const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= this.RESUME_TOKEN_MAX_AGE_MICROS) {\n return true;\n }\n\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 const changes =\n change.addedDocuments.size +\n change.modifiedDocuments.size +\n change.removedDocuments.size;\n return changes > 0;\n }\n\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n notifyLocalViewChanges(viewChanges: LocalViewChanges[]): Promise<void> {\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n this.localViewReferences.addReferences(viewChange.addedKeys, targetId);\n this.localViewReferences.removeReferences(\n viewChange.removedKeys,\n targetId\n );\n\n if (!viewChange.fromCache) {\n const targetData = this.targetDataByTarget.get(targetId);\n assert(\n targetData !== null,\n `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n );\n\n // Advance the last limbo free snapshot version\n const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion\n );\n this.targetDataByTarget = this.targetDataByTarget.insert(\n targetId,\n updatedTargetData\n );\n }\n }\n return this.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite-idempotent',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n this.persistence.referenceDelegate.removeReference(txn, key)\n );\n }\n );\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 */\n nextMutationBatch(afterBatchId?: BatchId): Promise<MutationBatch | null> {\n return this.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly-idempotent',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return this.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n }\n\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n readDocument(key: DocumentKey): Promise<MaybeDocument | null> {\n return this.persistence.runTransaction(\n 'read document',\n 'readonly-idempotent',\n txn => {\n return this.localDocuments.getDocument(txn, key);\n }\n );\n }\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 */\n allocateTarget(target: Target): Promise<TargetData> {\n return this.persistence\n .runTransaction('Allocate target', 'readwrite-idempotent', txn => {\n let targetData: TargetData;\n return this.targetCache\n .getTargetData(txn, target)\n .next((cached: TargetData | null) => {\n if (cached) {\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n targetData = cached;\n return PersistencePromise.resolve(targetData);\n } else {\n return this.targetCache.allocateTargetId(txn).next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return this.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n if (this.targetDataByTarget.get(targetData.targetId) === null) {\n this.targetDataByTarget = this.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n this.targetIdByTarget.set(target, targetData.targetId);\n }\n return targetData;\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 getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n const targetId = this.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve<TargetData | null>(\n this.targetDataByTarget.get(targetId)\n );\n } else {\n return this.targetCache.getTargetData(transaction, target);\n }\n }\n\n /**\n * Unpin 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.\n releaseTarget(\n targetId: number,\n keepPersistedTargetData: boolean\n ): Promise<void> {\n const targetData = this.targetDataByTarget.get(targetId);\n assert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData\n ? 'readwrite-idempotent'\n : 'readwrite-primary-idempotent';\n return this.persistence\n .runTransaction('Release target', mode, txn => {\n // References for documents sent via Watch are automatically removed\n // when we delete a target's data from the reference delegate.\n // Since this does not remove references for locally mutated documents,\n // we have to remove the target associations for these documents\n // manually.\n // This operation needs to be run inside the transaction since EagerGC\n // uses the local view references during the transaction's commit.\n // Fortunately, the operation is safe to be re-run in case the\n // transaction fails since there are no side effects if the target has\n // already been removed.\n const removed = this.localViewReferences.removeReferencesForId(\n targetId\n );\n\n if (!keepPersistedTargetData) {\n return PersistencePromise.forEach(removed, (key: DocumentKey) =>\n this.persistence.referenceDelegate.removeReference(txn, key)\n ).next(() => {\n this.persistence.referenceDelegate.removeTarget(txn, targetData!);\n });\n } else {\n return PersistencePromise.resolve();\n }\n })\n .then(() => {\n this.targetDataByTarget = this.targetDataByTarget.remove(targetId);\n this.targetIdByTarget.delete(targetData!.target);\n });\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 */\n executeQuery(\n query: Query,\n usePreviousResults: boolean\n ): Promise<QueryResult> {\n let lastLimboFreeSnapshotVersion = SnapshotVersion.MIN;\n let remoteKeys = documentKeySet();\n\n return this.persistence.runTransaction(\n 'Execute query',\n 'readonly-idempotent',\n txn => {\n return this.getTargetData(txn, query.toTarget())\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return this.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n this.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.MIN,\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n return { documents, remoteKeys };\n });\n }\n );\n }\n\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n remoteDocumentKeys(targetId: TargetId): Promise<DocumentKeySet> {\n return this.persistence.runTransaction(\n 'Remote document keys',\n 'readonly-idempotent',\n txn => {\n return this.targetCache.getMatchingKeysForTargetId(txn, targetId);\n }\n );\n }\n\n // PORTING NOTE: Multi-tab only.\n getActiveClients(): Promise<ClientId[]> {\n return this.persistence.getActiveClients();\n }\n\n // PORTING NOTE: Multi-tab only.\n removeCachedMutationBatchMetadata(batchId: BatchId): void {\n this.mutationQueue.removeCachedMutationKeys(batchId);\n }\n\n // PORTING NOTE: Multi-tab only.\n setNetworkEnabled(networkEnabled: boolean): void {\n this.persistence.setNetworkEnabled(networkEnabled);\n }\n\n private applyWriteToRemoteDocuments(\n txn: PersistenceTransaction,\n batchResult: MutationBatchResult,\n documentBuffer: RemoteDocumentChangeBuffer\n ): PersistencePromise<void> {\n const batch = batchResult.batch;\n const docKeys = batch.keys();\n let promiseChain = PersistencePromise.resolve();\n docKeys.forEach(docKey => {\n promiseChain = promiseChain\n .next(() => {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next((remoteDoc: MaybeDocument | null) => {\n let doc = remoteDoc;\n const ackVersion = batchResult.docVersions.get(docKey);\n assert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (!doc || doc.version.compareTo(ackVersion!) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(\n !remoteDoc,\n 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null'\n );\n } else {\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 documentBuffer.addEntry(doc, batchResult.commitVersion);\n }\n }\n });\n });\n return promiseChain.next(() =>\n this.mutationQueue.removeMutationBatch(txn, batch)\n );\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults> {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary-idempotent',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n\n // PORTING NOTE: Multi-tab only.\n getTarget(targetId: TargetId): Promise<Target | null> {\n const cachedTargetData = this.targetDataByTarget.get(targetId);\n\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return this.persistence.runTransaction(\n 'Get target data',\n 'readonly-idempotent',\n txn => {\n return this.targetCache\n .getTargetDataForTarget(txn, targetId)\n .next(targetData => (targetData ? targetData.target : null));\n }\n );\n }\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 changes since\n * the point of rejection.\n */\n // PORTING NOTE: Multi-tab only.\n getNewDocumentChanges(): Promise<MaybeDocumentMap> {\n return this.persistence\n .runTransaction('Get new document changes', 'readonly-idempotent', txn =>\n this.remoteDocuments.getNewDocumentChanges(\n txn,\n this.lastDocumentChangeReadTime\n )\n )\n .then(({ changedDocs, readTime }) => {\n this.lastDocumentChangeReadTime = readTime;\n return changedDocs;\n });\n }\n\n /**\n * Reads the newest document change from persistence and forwards the internal\n * synchronization marker so that calls to `getNewDocumentChanges()`\n * only return changes that happened after client initialization.\n */\n // PORTING NOTE: Multi-tab only.\n async synchronizeLastDocumentChangeReadTime(): Promise<void> {\n this.lastDocumentChangeReadTime = await this.persistence.runTransaction(\n 'Synchronize last document change read time',\n 'readonly-idempotent',\n txn => this.remoteDocuments.getLastReadTime(txn)\n );\n }\n}\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 * @return A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n err: FirestoreError\n): Promise<void> {\n if (\n err.code === Code.FAILED_PRECONDITION &&\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n ) {\n log.debug(LOG_TAG, 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * as firestore from '@firebase/firestore-types';\n\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n invalidClassError,\n validateArgType,\n validateNamedArrayAtLeastNumberOfElements\n} from '../util/input_validation';\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 single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nexport class FieldPath implements firestore.FieldPath {\n /** Internal representation of a Firestore field path. */\n _internalPath: InternalFieldPath;\n\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 validateNamedArrayAtLeastNumberOfElements(\n 'FieldPath',\n fieldNames,\n 'fieldNames',\n 1\n );\n\n for (let i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\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 private static readonly _DOCUMENT_ID = new FieldPath(\n InternalFieldPath.keyField().canonicalString()\n );\n\n static documentId(): FieldPath {\n return FieldPath._DOCUMENT_ID;\n }\n\n isEqual(other: firestore.FieldPath): boolean {\n if (!(other instanceof FieldPath)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nexport function fromDotSeparatedString(path: string): FieldPath {\n const found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`\n );\n }\n try {\n return new FieldPath(...path.split('.'));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * as firestore from '@firebase/firestore-types';\n\nimport { makeConstructorPrivate } from '../util/api';\nimport {\n validateArgType,\n validateAtLeastNumberOfArgs,\n validateExactNumberOfArgs,\n validateNoArgs\n} from '../util/input_validation';\n\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\nexport abstract class FieldValueImpl implements firestore.FieldValue {\n protected constructor(readonly _methodName: string) {}\n\n static delete(): FieldValueImpl {\n validateNoArgs('FieldValue.delete', arguments);\n return DeleteFieldValueImpl.instance;\n }\n\n static serverTimestamp(): FieldValueImpl {\n validateNoArgs('FieldValue.serverTimestamp', arguments);\n return ServerTimestampFieldValueImpl.instance;\n }\n\n static arrayUnion(...elements: unknown[]): FieldValueImpl {\n validateAtLeastNumberOfArgs('FieldValue.arrayUnion', arguments, 1);\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we need access to the Firestore instance.\n return new ArrayUnionFieldValueImpl(elements);\n }\n\n static arrayRemove(...elements: unknown[]): FieldValueImpl {\n validateAtLeastNumberOfArgs('FieldValue.arrayRemove', arguments, 1);\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we need access to the Firestore instance.\n return new ArrayRemoveFieldValueImpl(elements);\n }\n\n static increment(n: number): FieldValueImpl {\n validateArgType('FieldValue.increment', 'number', 1, n);\n validateExactNumberOfArgs('FieldValue.increment', arguments, 1);\n return new NumericIncrementFieldValueImpl(n);\n }\n\n isEqual(other: FieldValueImpl): boolean {\n return this === other;\n }\n}\n\nexport class DeleteFieldValueImpl extends FieldValueImpl {\n private constructor() {\n super('FieldValue.delete');\n }\n /** Singleton instance. */\n static instance = new DeleteFieldValueImpl();\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValueImpl {\n private constructor() {\n super('FieldValue.serverTimestamp');\n }\n /** Singleton instance. */\n static instance = new ServerTimestampFieldValueImpl();\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValueImpl {\n constructor(readonly _elements: unknown[]) {\n super('FieldValue.arrayUnion');\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValueImpl {\n constructor(readonly _elements: unknown[]) {\n super('FieldValue.arrayRemove');\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValueImpl {\n constructor(readonly _operand: number) {\n super('FieldValue.increment');\n }\n}\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\nexport const PublicFieldValue = makeConstructorPrivate(\n FieldValueImpl,\n 'Use FieldValue.<field>() instead.'\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 * as firestore from '@firebase/firestore-types';\n\nimport { Timestamp } from '../api/timestamp';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldValue,\n NumberValue,\n ObjectValue,\n ArrayValue,\n BlobValue,\n BooleanValue,\n DoubleValue,\n GeoPointValue,\n IntegerValue,\n NullValue,\n RefValue,\n StringValue,\n TimestampValue\n} from '../model/field_value';\n\nimport {\n FieldMask,\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation,\n TransformMutation\n} from '../model/mutation';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\nimport { Dict, forEach, isEmpty } from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport * as typeUtils from '../util/types';\n\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { SortedSet } from '../util/sorted_set';\nimport { Blob } from './blob';\nimport {\n FieldPath as ExternalFieldPath,\n fromDotSeparatedString\n} from './field_path';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n FieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './field_value';\nimport { GeoPoint } from './geo_point';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutations(key: DocumentKey, precondition: Precondition): Mutation[] {\n const mutations = [] as Mutation[];\n if (this.fieldMask !== null) {\n mutations.push(\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n );\n } else {\n mutations.push(new SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutations(key: DocumentKey, precondition: Precondition): Mutation[] {\n const mutations = [\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n ] as Mutation[];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nenum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: FieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * 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(\n readonly dataSource: UserDataSource,\n readonly methodName: string,\n readonly path: FieldPath | null,\n readonly arrayElement?: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: FieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n childContextForField(field: string): ParseContext {\n const childPath = this.path == null ? null : this.path.child(field);\n const context = new ParseContext(\n this.dataSource,\n this.methodName,\n childPath,\n /*arrayElement=*/ false,\n this.fieldTransforms,\n this.fieldMask\n );\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: FieldPath): ParseContext {\n const childPath = this.path == null ? null : this.path.child(field);\n const context = new ParseContext(\n this.dataSource,\n this.methodName,\n childPath,\n /*arrayElement=*/ false,\n this.fieldTransforms,\n this.fieldMask\n );\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContext {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(\n this.dataSource,\n this.methodName,\n /*path=*/ null,\n /*arrayElement=*/ true,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n createError(reason: string): Error {\n const fieldDescription =\n this.path === null || this.path.isEmpty()\n ? ''\n : ` (found in field ${this.path.toString()})`;\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${this.methodName}() called with invalid data. ` +\n reason +\n fieldDescription\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: FieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n/**\n * An interface that allows arbitrary pre-converting of user data. This\n * abstraction allows for, e.g.:\n * * The public API to convert DocumentReference objects to DocRef objects,\n * avoiding a circular dependency between user_data_converter.ts and\n * database.ts\n * * Tests to convert test-only sentinels (e.g. '<DELETE>') into types\n * compatible with UserDataConverter.\n *\n * Returns the converted value (can return back the input to act as a no-op).\n *\n * It can also throw an Error which will be wrapped into a friendly message.\n */\nexport type DataPreConverter = (input: unknown) => unknown;\n\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nexport class DocumentKeyReference {\n constructor(public databaseId: DatabaseId, public key: DocumentKey) {}\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataConverter {\n constructor(private preConverter: DataPreConverter) {}\n\n /** Parse document data from a non-merge set() call. */\n parseSetData(methodName: string, input: unknown): ParsedSetData {\n const context = new ParseContext(\n UserDataSource.Set,\n methodName,\n FieldPath.EMPTY_PATH\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const updateData = this.parseData(input, context);\n\n return new ParsedSetData(\n updateData as ObjectValue,\n /* fieldMask= */ null,\n context.fieldTransforms\n );\n }\n\n /** Parse document data from a set() call with '{merge:true}'. */\n parseMergeData(\n methodName: string,\n input: unknown,\n fieldPaths?: Array<string | firestore.FieldPath>\n ): ParsedSetData {\n const context = new ParseContext(\n UserDataSource.MergeSet,\n methodName,\n FieldPath.EMPTY_PATH\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const updateData = this.parseData(input, context) as ObjectValue;\n let fieldMask: FieldMask;\n let fieldTransforms: FieldTransform[];\n\n if (!fieldPaths) {\n fieldMask = FieldMask.fromArray(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else {\n let validatedFieldPaths = new SortedSet<FieldPath>(FieldPath.comparator);\n\n for (const stringOrFieldPath of fieldPaths) {\n let fieldPath: FieldPath;\n\n if (stringOrFieldPath instanceof ExternalFieldPath) {\n fieldPath = stringOrFieldPath._internalPath;\n } else if (typeof stringOrFieldPath === 'string') {\n fieldPath = fieldPathFromDotSeparatedString(\n methodName,\n stringOrFieldPath\n );\n } else {\n throw fail(\n 'Expected stringOrFieldPath to be a string or a FieldPath'\n );\n }\n\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n validatedFieldPaths = validatedFieldPaths.add(fieldPath);\n }\n\n fieldMask = FieldMask.fromSet(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask.covers(transform.field)\n );\n }\n return new ParsedSetData(\n updateData as ObjectValue,\n fieldMask,\n fieldTransforms\n );\n }\n\n /** Parse update data from an update() call. */\n parseUpdateData(methodName: string, input: unknown): ParsedUpdateData {\n const context = new ParseContext(\n UserDataSource.Update,\n methodName,\n FieldPath.EMPTY_PATH\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n let fieldMaskPaths = new SortedSet<FieldPath>(FieldPath.comparator);\n let updateData = ObjectValue.EMPTY;\n forEach(input as Dict<unknown>, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key);\n\n const childContext = context.childContextForFieldPath(path);\n value = this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths = fieldMaskPaths.add(path);\n } else {\n const parsedValue = this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths = fieldMaskPaths.add(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = FieldMask.fromSet(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n }\n\n /** Parse update data from a list of field/value arguments. */\n parseUpdateVarargs(\n methodName: string,\n field: string | ExternalFieldPath,\n value: unknown,\n moreFieldsAndValues: unknown[]\n ): ParsedUpdateData {\n const context = new ParseContext(\n UserDataSource.Update,\n methodName,\n FieldPath.EMPTY_PATH\n );\n const keys = [fieldPathFromArgument(methodName, field)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | ExternalFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n let fieldMaskPaths = new SortedSet<FieldPath>(FieldPath.comparator);\n let updateData = ObjectValue.EMPTY;\n\n for (let i = 0; i < keys.length; ++i) {\n const path = keys[i];\n const childContext = context.childContextForFieldPath(path);\n const value = this.runPreConverter(values[i], childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths = fieldMaskPaths.add(path);\n } else {\n const parsedValue = this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths = fieldMaskPaths.add(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n\n const mask = FieldMask.fromSet(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.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 */\n parseQueryValue(\n methodName: string,\n input: unknown,\n allowArrays = false\n ): FieldValue {\n const context = new ParseContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName,\n FieldPath.EMPTY_PATH\n );\n const parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n }\n\n /** Sends data through this.preConverter, handling any thrown errors. */\n private runPreConverter(input: unknown, context: ParseContext): unknown {\n try {\n return this.preConverter(input);\n } catch (e) {\n const message = errorMessage(e);\n throw context.createError(message);\n }\n }\n\n /**\n * Internal helper for parsing user data.\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 * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n private parseData(input: unknown, context: ParseContext): FieldValue | null {\n input = this.runPreConverter(input, context);\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input as Dict<unknown>, context);\n } else if (input instanceof FieldValueImpl) {\n // FieldValues usually parse into transforms (except FieldValue.delete())\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 this.parseSentinelFieldValue(input, context);\n return null;\n } else {\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 if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input 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 (\n context.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return this.parseArray(input as unknown[], context);\n } else {\n return this.parseScalarValue(input, context);\n }\n }\n }\n\n private parseObject(obj: Dict<unknown>, context: ParseContext): FieldValue {\n let result = new SortedMap<string, FieldValue>(primitiveComparator);\n\n if (isEmpty(obj)) {\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 if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = this.parseData(\n val,\n context.childContextForField(key)\n );\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n }\n\n return new ObjectValue(result);\n }\n\n private parseArray(array: unknown[], context: ParseContext): FieldValue {\n const result = [] as FieldValue[];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = this.parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new ArrayValue(result);\n }\n\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n private parseSentinelFieldValue(\n value: FieldValueImpl,\n context: ParseContext\n ): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (context.path === null) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path);\n } else if (context.dataSource === UserDataSource.Update) {\n assert(\n context.path.length > 0,\n 'FieldValue.delete() at the top level should have already' +\n ' been handled.'\n );\n throw context.createError(\n 'FieldValue.delete() can only appear at the top level ' +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n 'FieldValue.delete() cannot be used with set() unless you pass ' +\n '{merge:true}'\n );\n }\n } else if (value instanceof ServerTimestampFieldValueImpl) {\n context.fieldTransforms.push(\n new FieldTransform(context.path, ServerTimestampTransform.instance)\n );\n } else if (value instanceof ArrayUnionFieldValueImpl) {\n const parsedElements = this.parseArrayTransformElements(\n value._methodName,\n value._elements\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n context.fieldTransforms.push(\n new FieldTransform(context.path, arrayUnion)\n );\n } else if (value instanceof ArrayRemoveFieldValueImpl) {\n const parsedElements = this.parseArrayTransformElements(\n value._methodName,\n value._elements\n );\n const arrayRemove = new ArrayRemoveTransformOperation(parsedElements);\n context.fieldTransforms.push(\n new FieldTransform(context.path, arrayRemove)\n );\n } else if (value instanceof NumericIncrementFieldValueImpl) {\n const operand = this.parseQueryValue(\n 'FieldValue.increment',\n value._operand\n ) as NumberValue;\n const numericIncrement = new NumericIncrementTransformOperation(operand);\n context.fieldTransforms.push(\n new FieldTransform(context.path, numericIncrement)\n );\n } else {\n fail('Unknown FieldValue type: ' + value);\n }\n }\n\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @return The parsed value\n */\n private parseScalarValue(value: unknown, context: ParseContext): FieldValue {\n if (value === null) {\n return NullValue.INSTANCE;\n } else if (typeof value === 'number') {\n if (typeUtils.isSafeInteger(value)) {\n return new IntegerValue(value);\n } else {\n return new DoubleValue(value);\n }\n } else if (typeof value === 'boolean') {\n return BooleanValue.of(value);\n } else if (typeof value === 'string') {\n return new StringValue(value);\n } else if (value instanceof Date) {\n return new TimestampValue(Timestamp.fromDate(value));\n } else if (value instanceof Timestamp) {\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 return new TimestampValue(\n new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n )\n );\n } else if (value instanceof GeoPoint) {\n return new GeoPointValue(value);\n } else if (value instanceof Blob) {\n return new BlobValue(value);\n } else if (value instanceof DocumentKeyReference) {\n return new RefValue(value.databaseId, value.key);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n }\n\n private parseArrayTransformElements(\n methodName: string,\n elements: unknown[]\n ): FieldValue[] {\n return elements.map((element, i) => {\n // Although array transforms are used with writes, the actual elements\n // being unioned or removed are not considered writes since they cannot\n // contain any FieldValue sentinels, etc.\n const context = new ParseContext(\n UserDataSource.Argument,\n methodName,\n FieldPath.EMPTY_PATH\n );\n return this.parseData(element, context.childContextForArray(i))!;\n });\n }\n}\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 */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContext,\n input: unknown\n): void {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | ExternalFieldPath\n): FieldPath {\n if (path instanceof ExternalFieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() called with invalid data. ${message}`\n );\n }\n}\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 split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(\n methodName: string,\n path: string\n): FieldPath {\n try {\n return fromDotSeparatedString(path)._internalPath;\n } catch (e) {\n const message = errorMessage(e);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() called with invalid data. ${message}`\n );\n }\n}\n\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error: Error | object): string {\n return error instanceof Error ? error.message : error.toString();\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { AsyncQueue, TimerId } from '../util/async_queue';\nimport * as log from '../util/log';\nimport { CancelablePromise } from '../util/promise';\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\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 */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: CancelablePromise<void> | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\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 private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\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 */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\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 */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\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 */\n backoffAndRun(op: () => Promise<void>): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (this.currentBaseMs > 0) {\n log.debug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { CredentialsProvider, Token } from '../api/credentials';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ProtoByteString, TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\n\nimport { CancelablePromise } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport { JsonProtoSerializer } from './serializer';\nimport { WatchChange } from './watch_change';\nimport { emptyByteString } from '../platform/platform';\n\nconst LOG_TAG = 'PersistentStream';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface ListenRequest extends api.ListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends api.WriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nenum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n */\n Error,\n\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After waiting is complete, the stream will try to open.\n * While in this state isStarted() will return true but isOpen() will return\n * false.\n */\n Backoff\n}\n\n/**\n * Provides a common interface that is shared by the listeners for stream\n * events by the concrete implementation classes.\n */\nexport interface PersistentStreamListener {\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise<void>;\n /**\n * Called after the stream has closed. If there was an error, the\n * FirestoreError will be set.\n */\n onClose: (err?: FirestoreError) => Promise<void>;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\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 */\nexport abstract class PersistentStream<\n SendType,\n ReceiveType,\n ListenerType extends PersistentStreamListener\n> {\n private state = 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 private closeCount = 0;\n\n private idleTimer: CancelablePromise<void> | null = null;\n private stream: Stream<SendType, ReceiveType> | null = null;\n\n protected backoff: ExponentialBackoff;\n\n constructor(\n private queue: AsyncQueue,\n connectionTimerId: TimerId,\n private idleTimerId: TimerId,\n protected connection: Connection,\n private credentialsProvider: CredentialsProvider,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\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 */\n isStarted(): boolean {\n return (\n this.state === PersistentStreamState.Starting ||\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Backoff\n );\n }\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 */\n isOpen(): boolean {\n return this.state === PersistentStreamState.Open;\n }\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 */\n start(): void {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.auth();\n }\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 */\n async stop(): Promise<void> {\n if (this.isStarted()) {\n await this.close(PersistentStreamState.Initial);\n }\n }\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 */\n inhibitBackoff(): void {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n }\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 */\n markIdle(): void {\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 if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(\n this.idleTimerId,\n IDLE_TIMEOUT_MS,\n () => this.handleIdleCloseTimer()\n );\n }\n }\n\n /** Sends a message to the underlying stream. */\n protected sendRequest(msg: SendType): void {\n this.cancelIdleCheck();\n this.stream!.send(msg);\n }\n\n /** Called by the idle timer when the stream should close due to inactivity. */\n private async handleIdleCloseTimer(): Promise<void> {\n if (this.isOpen()) {\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(PersistentStreamState.Initial);\n }\n }\n\n /** Marks the stream as active again. */\n private cancelIdleCheck(): void {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n }\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 */\n private async close(\n finalState: PersistentStreamState,\n error?: FirestoreError\n ): Promise<void> {\n assert(this.isStarted(), 'Only started streams should be closed.');\n assert(\n finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n \"Can't provide an error when not in an error state.\"\n );\n\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.cancelIdleCheck();\n this.backoff.cancel();\n\n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.closeCount++;\n\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n log.error(error.toString());\n log.error(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (error && error.code === Code.UNAUTHENTICATED) {\n // \"unauthenticated\" error means the token was rejected. Try force refreshing it in case it\n // just expired.\n this.credentialsProvider.invalidateToken();\n }\n\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n\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 = finalState;\n\n // Notify the listener that the stream closed.\n await this.listener.onClose(error);\n }\n\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n protected tearDown(): void {}\n\n /**\n * Used by subclasses to start the concrete RPC and return the underlying\n * connection stream.\n */\n protected abstract startRpc(\n token: Token | null\n ): Stream<SendType, ReceiveType>;\n\n /**\n * Called after the stream has received a message. The function will be\n * called on the right queue and must return a Promise.\n * @param message The message received from the stream.\n */\n protected abstract onMessage(message: ReceiveType): Promise<void>;\n\n private auth(): void {\n assert(\n this.state === PersistentStreamState.Initial,\n 'Must be in initial state to auth'\n );\n\n this.state = PersistentStreamState.Starting;\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n const closeCount = this.closeCount;\n\n this.credentialsProvider.getToken().then(\n token => {\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 if (this.closeCount === closeCount) {\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.startStream(token);\n }\n },\n (error: Error) => {\n dispatchIfNotClosed(() => {\n const rpcError = new FirestoreError(\n Code.UNKNOWN,\n 'Fetching auth token failed: ' + error.message\n );\n return this.handleStreamClose(rpcError);\n });\n }\n );\n }\n\n private startStream(token: Token | null): void {\n assert(\n this.state === PersistentStreamState.Starting,\n 'Trying to start stream in a non-starting state'\n );\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n this.stream = this.startRpc(token);\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n assert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n return this.listener!.onOpen();\n });\n });\n this.stream.onClose((error?: FirestoreError) => {\n dispatchIfNotClosed(() => {\n return this.handleStreamClose(error);\n });\n });\n this.stream.onMessage((msg: ReceiveType) => {\n dispatchIfNotClosed(() => {\n return this.onMessage(msg);\n });\n });\n }\n\n private performBackoff(): void {\n assert(\n this.state === PersistentStreamState.Error,\n 'Should only perform backoff when in Error state'\n );\n this.state = PersistentStreamState.Backoff;\n\n this.backoff.backoffAndRun(async () => {\n assert(\n this.state === PersistentStreamState.Backoff,\n 'Backoff elapsed but state is now: ' + this.state\n );\n\n this.state = PersistentStreamState.Initial;\n this.start();\n assert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise<void> {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n log.debug(LOG_TAG, `close with error: ${error}`);\n\n this.stream = null;\n\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 this.close(PersistentStreamState.Error, error);\n }\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 */\n private getCloseGuardedDispatcher(\n startCloseCount: number\n ): (fn: () => Promise<void>) => void {\n return (fn: () => Promise<void>): void => {\n this.queue.enqueueAndForget(() => {\n if (this.closeCount === startCloseCount) {\n return fn();\n } else {\n log.debug(\n LOG_TAG,\n 'stream callback skipped by getCloseGuardedDispatcher.'\n );\n return Promise.resolve();\n }\n });\n };\n }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n /**\n * Called on a watchChange. The snapshot parameter will be MIN if the watch\n * change did not have a snapshot associated with it.\n */\n onWatchChange: (\n watchChange: WatchChange,\n snapshot: SnapshotVersion\n ) => Promise<void>;\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 */\nexport class PersistentListenStream extends PersistentStream<\n api.ListenRequest,\n api.ListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n credentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n connection,\n credentials,\n listener\n );\n }\n\n protected startRpc(\n token: Token | null\n ): Stream<api.ListenRequest, api.ListenResponse> {\n return this.connection.openStream<api.ListenRequest, api.ListenResponse>(\n 'Listen',\n token\n );\n }\n\n protected onMessage(watchChangeProto: api.ListenResponse): Promise<void> {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = this.serializer.fromWatchChange(watchChangeProto);\n const snapshot = this.serializer.versionFromListenResponse(\n watchChangeProto\n );\n return this.listener!.onWatchChange(watchChange, snapshot);\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 */\n watch(targetData: TargetData): void {\n const request: ListenRequest = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(targetData);\n\n const labels = this.serializer.toListenRequestLabels(targetData);\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n }\n\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */\n unwatch(targetId: TargetId): void {\n const request: ListenRequest = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n /**\n * Called by the PersistentWriteStream upon a successful handshake response\n * from the server, which is the receiver's cue to send any pending writes.\n */\n onHandshakeComplete: () => Promise<void>;\n\n /**\n * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n * from the server that contains a mutation result.\n */\n onMutationResult: (\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ) => Promise<void>;\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 */\nexport class PersistentWriteStream extends PersistentStream<\n api.WriteRequest,\n api.WriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n credentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n connection,\n credentials,\n listener\n );\n }\n\n /**\n * The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n *\n * PersistentWriteStream manages propagating this value from responses to the\n * next request.\n */\n lastStreamToken: ProtoByteString = emptyByteString();\n\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get handshakeComplete(): boolean {\n return this.handshakeComplete_;\n }\n\n // Override of PersistentStream.start\n start(): void {\n this.handshakeComplete_ = false;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n token: Token | null\n ): Stream<api.WriteRequest, api.WriteResponse> {\n return this.connection.openStream<api.WriteRequest, api.WriteResponse>(\n 'Write',\n token\n );\n }\n\n protected onMessage(responseProto: api.WriteResponse): Promise<void> {\n // Always capture the last stream token.\n assert(\n !!responseProto.streamToken,\n 'Got a write response without a stream token'\n );\n this.lastStreamToken = responseProto.streamToken;\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(\n !responseProto.writeResults || responseProto.writeResults.length === 0,\n 'Got mutation results for handshake'\n );\n this.handshakeComplete_ = true;\n return this.listener!.onHandshakeComplete();\n } else {\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.backoff.reset();\n\n const results = this.serializer.fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = this.serializer.fromVersion(\n responseProto.commitTime!\n );\n return this.listener!.onMutationResult(commitVersion, results);\n }\n }\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 */\n writeHandshake(): void {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\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 request: WriteRequest = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n assert(\n this.lastStreamToken.length > 0,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n // Protos are typed with string, but we support UInt8Array on Node\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamToken: this.lastStreamToken as any,\n writes: mutations.map(mutation => this.serializer.toMutation(mutation))\n };\n\n this.sendRequest(request);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { CredentialsProvider } from '../api/credentials';\nimport { maybeDocumentMap } from '../model/collections';\nimport { MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { Connection } from './connection';\nimport {\n WatchStreamListener,\n WriteStreamListener,\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\n\nimport { JsonProtoSerializer } from './serializer';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface BatchGetDocumentsRequest extends api.BatchGetDocumentsRequest {\n database?: string;\n}\ninterface CommitRequest extends api.CommitRequest {\n database?: string;\n}\n\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nexport class Datastore {\n constructor(\n private queue: AsyncQueue,\n private connection: Connection,\n private credentials: CredentialsProvider,\n private serializer: JsonProtoSerializer\n ) {}\n\n newPersistentWriteStream(\n listener: WriteStreamListener\n ): PersistentWriteStream {\n return new PersistentWriteStream(\n this.queue,\n this.connection,\n this.credentials,\n this.serializer,\n listener\n );\n }\n\n newPersistentWatchStream(\n listener: WatchStreamListener\n ): PersistentListenStream {\n return new PersistentListenStream(\n this.queue,\n this.connection,\n this.credentials,\n this.serializer,\n listener\n );\n }\n\n commit(mutations: Mutation[]): Promise<MutationResult[]> {\n const params: CommitRequest = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(m => this.serializer.toMutation(m))\n };\n return this.invokeRPC<CommitRequest, api.CommitResponse>(\n 'Commit',\n params\n ).then(response => {\n return this.serializer.fromWriteResults(\n response.writeResults,\n response.commitTime\n );\n });\n }\n\n lookup(keys: DocumentKey[]): Promise<MaybeDocument[]> {\n const params: BatchGetDocumentsRequest = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(k => this.serializer.toName(k))\n };\n return this.invokeStreamingRPC<\n BatchGetDocumentsRequest,\n api.BatchGetDocumentsResponse\n >('BatchGetDocuments', params).then(response => {\n let docs = maybeDocumentMap();\n response.forEach(proto => {\n const doc = this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n const result: MaybeDocument[] = [];\n keys.forEach(key => {\n const doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n }\n\n /** Gets an auth token and invokes the provided RPC. */\n private invokeRPC<Req, Resp>(rpcName: string, request: Req): Promise<Resp> {\n return this.credentials\n .getToken()\n .then(token => {\n return this.connection.invokeRPC<Req, Resp>(rpcName, request, token);\n })\n .catch((error: FirestoreError) => {\n if (error.code === Code.UNAUTHENTICATED) {\n this.credentials.invalidateToken();\n }\n throw error;\n });\n }\n\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n private invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n request: Req\n ): Promise<Resp[]> {\n return this.credentials\n .getToken()\n .then(token => {\n return this.connection.invokeStreamingRPC<Req, Resp>(\n rpcName,\n request,\n token\n );\n })\n .catch((error: FirestoreError) => {\n if (error.code === Code.UNAUTHENTICATED) {\n this.credentials.invalidateToken();\n }\n throw error;\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { ParsedSetData, ParsedUpdateData } from '../api/user_data_converter';\nimport { documentVersionMap } from '../model/collections';\nimport { Document, NoDocument, MaybeDocument } from '../model/document';\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport { Datastore } from '../remote/datastore';\nimport { fail, assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = documentVersionMap();\n private mutations: Mutation[] = [];\n private committed = false;\n\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 private lastWriteError: FirestoreError | null = null;\n\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 private writtenDocs: Set<DocumentKey> = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise<MaybeDocument[]> {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n }\n const docs = await this.datastore.lookup(keys);\n docs.forEach(doc => {\n if (doc instanceof NoDocument || doc instanceof Document) {\n this.recordVersion(doc);\n } else {\n fail('Document in a transaction was a ' + doc.constructor.name);\n }\n });\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutations(key, this.precondition(key)));\n this.writtenDocs.add(key);\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastWriteError = e;\n }\n this.writtenDocs.add(key);\n }\n\n delete(key: DocumentKey): void {\n this.write([new DeleteMutation(key, this.precondition(key))]);\n this.writtenDocs.add(key);\n }\n\n async commit(): Promise<void> {\n this.ensureCommitNotCalled();\n\n if (this.lastWriteError) {\n throw this.lastWriteError;\n }\n let unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten = unwritten.remove(mutation.key);\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((key, _version) => {\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await this.datastore.commit(this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: MaybeDocument): void {\n let docVersion: SnapshotVersion;\n\n if (doc instanceof Document) {\n docVersion = doc.version;\n } else if (doc instanceof NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = SnapshotVersion.forDeletedDoc();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n }\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 */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key);\n if (!this.writtenDocs.has(key) && version) {\n return Precondition.updateTime(version);\n } else {\n return Precondition.NONE;\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key);\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(key) && version) {\n if (version.isEqual(SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n\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\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutations: Mutation[]): void {\n this.ensureCommitNotCalled();\n this.mutations = this.mutations.concat(mutations);\n }\n\n private ensureCommitNotCalled(): void {\n assert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\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 { OnlineState } from '../core/types';\nimport { assert } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { CancelablePromise } from '../util/promise';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\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 */\nexport class OnlineStateTracker {\n /** The current OnlineState. */\n private state = OnlineState.Unknown;\n\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 private watchStreamFailures = 0;\n\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 private onlineStateTimer: CancelablePromise<void> | null = null;\n\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 private shouldWarnClientIsOffline = true;\n\n constructor(\n private asyncQueue: AsyncQueue,\n private onlineStateHandler: (onlineState: OnlineState) => void\n ) {}\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 */\n handleWatchStreamStart(): void {\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n assert(\n this.onlineStateTimer === null,\n `onlineStateTimer shouldn't be started yet`\n );\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n TimerId.OnlineStateTimeout,\n ONLINE_STATE_TIMEOUT_MS,\n () => {\n this.onlineStateTimer = null;\n assert(\n this.state === OnlineState.Unknown,\n 'Timer should be canceled if we transitioned to a different state.'\n );\n this.logClientOfflineWarningIfNecessary(\n `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n `seconds.`\n );\n this.setAndBroadcast(OnlineState.Offline);\n\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n return Promise.resolve();\n }\n );\n }\n }\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 */\n handleWatchStreamFailure(error: FirestoreError): void {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n assert(this.watchStreamFailures === 0, 'watchStreamFailures must be 0');\n assert(this.onlineStateTimer === null, 'onlineStateTimer must be null');\n } else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n\n this.logClientOfflineWarningIfNecessary(\n `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n `times. Most recent error: ${error.toString()}`\n );\n\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n }\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 */\n set(newState: OnlineState): void {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n\n this.setAndBroadcast(newState);\n }\n\n private setAndBroadcast(newState: OnlineState): void {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n }\n\n private logClientOfflineWarningIfNecessary(details: string): void {\n const message =\n `Could not reach Cloud Firestore backend. ${details}\\n` +\n `This typically indicates that your device does not have a healthy ` +\n `Internet connection at the moment. The client will operate in offline ` +\n `mode until it is able to successfully connect to the backend.`;\n if (this.shouldWarnClientIsOffline) {\n log.error(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n log.debug(LOG_TAG, message);\n }\n }\n\n private clearOnlineStateTimer(): void {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { Transaction } from '../core/transaction';\nimport { OnlineState, TargetId } from '../core/types';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport {\n BATCHID_UNKNOWN,\n MutationBatch,\n MutationBatchResult\n} from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\n\nimport { DocumentKeySet } from '../model/collections';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport { Datastore } from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentError, isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n TargetMetadataProvider,\n WatchChange,\n WatchChangeAggregator,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst LOG_TAG = 'RemoteStore';\n\n// TODO(b/35853402): Negotiate this with the stream.\nconst MAX_PENDING_WRITES = 10;\n\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nexport class RemoteStore implements TargetMetadataProvider {\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 private writePipeline: MutationBatch[] = [];\n\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 private listenTargets: { [targetId: number]: TargetData } = {};\n\n private connectivityMonitor: ConnectivityMonitor;\n private watchStream: PersistentListenStream;\n private writeStream: PersistentWriteStream;\n private watchChangeAggregator: WatchChangeAggregator | null = null;\n\n /**\n * Set to true by enableNetwork() and false by disableNetwork() and indicates\n * the user-preferred network state.\n */\n private networkEnabled = false;\n\n private isPrimary = false;\n\n private onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n private localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n private datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((status: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n if (this.canUseNetwork()) {\n log.debug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await this.restartNetwork();\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n\n // Create streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n\n this.writeStream = this.datastore.newPersistentWriteStream({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n }\n\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n syncEngine!: RemoteSyncer;\n\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n start(): Promise<void> {\n return this.enableNetwork();\n }\n\n /** Re-enables the network. Idempotent. */\n async enableNetwork(): Promise<void> {\n this.networkEnabled = true;\n\n if (this.canUseNetwork()) {\n this.writeStream.lastStreamToken = await this.localStore.getLastStreamToken();\n\n if (this.shouldStartWatchStream()) {\n this.startWatchStream();\n } else {\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n\n // This will start the write stream if necessary.\n await this.fillWritePipeline();\n }\n }\n\n /**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\n async disableNetwork(): Promise<void> {\n this.networkEnabled = false;\n await this.disableNetworkInternal();\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n this.onlineStateTracker.set(OnlineState.Offline);\n }\n\n private async disableNetworkInternal(): Promise<void> {\n await this.writeStream.stop();\n await this.watchStream.stop();\n\n if (this.writePipeline.length > 0) {\n log.debug(\n LOG_TAG,\n `Stopping write stream with ${this.writePipeline.length} pending writes`\n );\n this.writePipeline = [];\n }\n\n this.cleanUpWatchStreamState();\n }\n\n async shutdown(): Promise<void> {\n log.debug(LOG_TAG, 'RemoteStore shutting down.');\n this.networkEnabled = false;\n await this.disableNetworkInternal();\n this.connectivityMonitor.shutdown();\n\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n this.onlineStateTracker.set(OnlineState.Unknown);\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 */\n listen(targetData: TargetData): void {\n if (objUtils.contains(this.listenTargets, targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n this.listenTargets[targetData.targetId] = targetData;\n\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n } else if (this.watchStream.isOpen()) {\n this.sendWatchRequest(targetData);\n }\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 */\n unlisten(targetId: TargetId): void {\n assert(\n objUtils.contains(this.listenTargets, targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n delete this.listenTargets[targetId];\n if (this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n }\n\n if (objUtils.isEmpty(this.listenTargets)) {\n if (this.watchStream.isOpen()) {\n this.watchStream.markIdle();\n } else if (this.canUseNetwork()) {\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 this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n }\n\n /** {@link TargetMetadataProvider.getTargetDataForTarget} */\n getTargetDataForTarget(targetId: TargetId): TargetData | null {\n return this.listenTargets[targetId] || null;\n }\n\n /** {@link TargetMetadataProvider.getRemoteKeysForTarget} */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet {\n return this.syncEngine.getRemoteKeysForTarget(targetId);\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 */\n private sendWatchRequest(targetData: TargetData): void {\n this.watchChangeAggregator!.recordPendingTargetRequest(targetData.targetId);\n this.watchStream.watch(targetData);\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 */\n private sendUnwatchRequest(targetId: TargetId): void {\n this.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n }\n\n private startWatchStream(): void {\n assert(\n this.shouldStartWatchStream(),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n\n this.watchChangeAggregator = new WatchChangeAggregator(this);\n this.watchStream.start();\n this.onlineStateTracker.handleWatchStreamStart();\n }\n\n /**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\n private shouldStartWatchStream(): boolean {\n return (\n this.canUseNetwork() &&\n !this.watchStream.isStarted() &&\n !objUtils.isEmpty(this.listenTargets)\n );\n }\n\n canUseNetwork(): boolean {\n return this.isPrimary && this.networkEnabled;\n }\n\n private cleanUpWatchStreamState(): void {\n this.watchChangeAggregator = null;\n }\n\n private async onWatchStreamOpen(): Promise<void> {\n objUtils.forEachNumber(this.listenTargets, (targetId, targetData) => {\n this.sendWatchRequest(targetData);\n });\n }\n\n private async onWatchStreamClose(error?: FirestoreError): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n assert(\n !this.shouldStartWatchStream(),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n this.cleanUpWatchStreamState();\n\n // If we still need the watch stream, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.onlineStateTracker.handleWatchStreamFailure(error!);\n\n this.startWatchStream();\n } else {\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 this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n\n private async onWatchStreamChange(\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n ): Promise<void> {\n // Mark the client as online since we got a message from the server\n this.onlineStateTracker.set(OnlineState.Online);\n\n if (\n watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause\n ) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return this.handleTargetError(watchChange);\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n this.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n this.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n assert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n this.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.MIN)) {\n const lastRemoteSnapshotVersion = await this.localStore.getLastRemoteSnapshotVersion();\n if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 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 this.raiseWatchSnapshot(snapshotVersion);\n }\n }\n }\n\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 private raiseWatchSnapshot(snapshotVersion: SnapshotVersion): Promise<void> {\n assert(\n !snapshotVersion.isEqual(SnapshotVersion.MIN),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent = this.watchChangeAggregator!.createRemoteEvent(\n snapshotVersion\n );\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n objUtils.forEachNumber(remoteEvent.targetChanges, (targetId, change) => {\n if (change.resumeToken.length > 0) {\n const targetData = this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (targetData) {\n this.listenTargets[targetId] = targetData.withResumeToken(\n change.resumeToken,\n snapshotVersion\n );\n }\n }\n });\n\n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n remoteEvent.targetMismatches.forEach(targetId => {\n const targetData = this.listenTargets[targetId];\n if (!targetData) {\n // A watched target might have been removed already.\n return;\n }\n\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n this.listenTargets[targetId] = targetData.withResumeToken(\n emptyByteString(),\n targetData.snapshotVersion\n );\n\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 this.sendUnwatchRequest(targetId);\n\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 requestTargetData = new TargetData(\n targetData.target,\n targetId,\n TargetPurpose.ExistenceFilterMismatch,\n targetData.sequenceNumber\n );\n this.sendWatchRequest(requestTargetData);\n });\n\n // Finally raise remote event\n return this.syncEngine.applyRemoteEvent(remoteEvent);\n }\n\n /** Handles an error on a target */\n private handleTargetError(watchChange: WatchTargetChange): Promise<void> {\n assert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n let promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(targetId => {\n promiseChain = promiseChain.then(async () => {\n // A watched target might have been removed already.\n if (objUtils.contains(this.listenTargets, targetId)) {\n delete this.listenTargets[targetId];\n this.watchChangeAggregator!.removeTarget(targetId);\n return this.syncEngine.rejectListen(targetId, error);\n }\n });\n });\n return promiseChain;\n }\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 */\n async fillWritePipeline(): Promise<void> {\n if (this.canAddToWritePipeline()) {\n const lastBatchIdRetrieved =\n this.writePipeline.length > 0\n ? this.writePipeline[this.writePipeline.length - 1].batchId\n : BATCHID_UNKNOWN;\n const batch = await this.localStore.nextMutationBatch(\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (this.writePipeline.length === 0) {\n this.writeStream.markIdle();\n }\n } else {\n this.addToWritePipeline(batch);\n await this.fillWritePipeline();\n }\n }\n\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\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 */\n private canAddToWritePipeline(): boolean {\n return (\n this.canUseNetwork() && this.writePipeline.length < MAX_PENDING_WRITES\n );\n }\n\n // For testing\n outstandingWrites(): number {\n return this.writePipeline.length;\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 */\n private addToWritePipeline(batch: MutationBatch): void {\n assert(\n this.canAddToWritePipeline(),\n 'addToWritePipeline called when pipeline is full'\n );\n this.writePipeline.push(batch);\n\n if (this.writeStream.isOpen() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n }\n\n private shouldStartWriteStream(): boolean {\n return (\n this.canUseNetwork() &&\n !this.writeStream.isStarted() &&\n this.writePipeline.length > 0\n );\n }\n\n private startWriteStream(): void {\n assert(\n this.shouldStartWriteStream(),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n this.writeStream.start();\n }\n\n private async onWriteStreamOpen(): Promise<void> {\n this.writeStream.writeHandshake();\n }\n\n private onWriteHandshakeComplete(): Promise<void> {\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(() => {\n // Send the write pipeline now that the stream is established.\n for (const batch of this.writePipeline) {\n this.writeStream.writeMutations(batch.mutations);\n }\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n\n private onMutationResult(\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): Promise<void> {\n // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n assert(\n this.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = this.writePipeline.shift()!;\n const success = MutationBatchResult.from(\n batch,\n commitVersion,\n results,\n this.writeStream.lastStreamToken\n );\n return this.syncEngine.applySuccessfulWrite(success).then(() => {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return this.fillWritePipeline();\n });\n }\n\n private async onWriteStreamClose(error?: FirestoreError): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n assert(\n !this.shouldStartWriteStream(),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n if (error && this.writePipeline.length > 0) {\n // A promise that is resolved after we processed the error\n let errorHandling: Promise<void>;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error!);\n } else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error!);\n }\n\n return errorHandling.then(() => {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n });\n }\n // No pending writes, nothing to do\n }\n\n private async handleHandshakeError(error: FirestoreError): Promise<void> {\n // Reset the token if it's a permanent error, signaling the write stream is\n // no longer valid. Note that the handshake does not count as a write: see\n // comments on isPermanentWriteError for details.\n if (isPermanentError(error.code)) {\n log.debug(\n LOG_TAG,\n 'RemoteStore error before completed handshake; resetting stream token: ',\n this.writeStream.lastStreamToken\n );\n this.writeStream.lastStreamToken = emptyByteString();\n\n return this.localStore\n .setLastStreamToken(emptyByteString())\n .catch(ignoreIfPrimaryLeaseLoss);\n } else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n }\n }\n\n private async handleWriteError(error: FirestoreError): Promise<void> {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (isPermanentWriteError(error.code)) {\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 batch = this.writePipeline.shift()!;\n\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 this.writeStream.inhibitBackoff();\n\n return this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(() => {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return this.fillWritePipeline();\n });\n } else {\n // Transient error, just let the retry logic kick in.\n }\n }\n\n createTransaction(): Transaction {\n return new Transaction(this.datastore);\n }\n\n private async restartNetwork(): Promise<void> {\n this.networkEnabled = false;\n await this.disableNetworkInternal();\n this.onlineStateTracker.set(OnlineState.Unknown);\n await this.enableNetwork();\n }\n\n async handleCredentialChange(): Promise<void> {\n if (this.canUseNetwork()) {\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n log.debug(LOG_TAG, 'RemoteStore restarting streams for new credential');\n await this.restartNetwork();\n }\n }\n\n /**\n * Toggles the network state when the client gains or loses its primary lease.\n */\n async applyPrimaryState(isPrimary: boolean): Promise<void> {\n this.isPrimary = isPrimary;\n\n if (isPrimary && this.networkEnabled) {\n await this.enableNetwork();\n } else if (!isPrimary) {\n await this.disableNetworkInternal();\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { QueryTargetState } from './shared_client_state_syncer';\nimport { assert } from '../util/assert';\nimport { ClientId } from './shared_client_state';\nimport { User } from '../auth/user';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients_<persistence_prefix>_<instance_key>\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n assert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\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.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets_<persistence_prefix>_<target_id>\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\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>\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\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>'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\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 { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { Platform } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug, error } from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger } from '../util/types';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n syncEngine: SharedClientStateSyncer | null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(targetId: TargetId): QueryTargetState;\n\n /** Removes the Query Target ID association from the local client. */\n removeLocalQueryTarget(targetId: TargetId): void;\n\n /** Checks whether the target is associated with the local client. */\n isLocalQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Processes an update to a query target.\n *\n * Called by the primary client to notify secondary clients of document\n * changes or state transitions that affect the provided query target.\n */\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void;\n\n /**\n * Removes the target's metadata entry.\n *\n * Called by the primary client when all clients stopped listening to a query\n * target.\n */\n clearQueryState(targetId: TargetId): void;\n\n /**\n * Gets the active Query Targets IDs for all active clients.\n *\n * The implementation for this may require O(n) runtime, where 'n' is the size\n * of the result set.\n */\n // Visible for testing\n getAllActiveQueryTargets(): SortedSet<TargetId>;\n\n /**\n * Checks whether the provided target ID is currently being listened to by\n * any of the active clients.\n *\n * The implementation may require O(n*log m) runtime, where 'n' is the number\n * of clients and 'm' the number of targets.\n */\n isActiveQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Starts the SharedClientState, reads existing client data and registers\n * listeners for updates to new and existing clients.\n */\n start(): Promise<void>;\n\n /** Shuts down the `SharedClientState` and its listeners. */\n shutdown(): void;\n\n /**\n * Changes the active user and removes all existing user-specific data. The\n * user change does not call back into SyncEngine (for example, no mutations\n * will be marked as removed).\n */\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void;\n\n /** Changes the shared online state of all clients. */\n setOnlineState(onlineState: OnlineState): void;\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n}\n\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\nexport class MutationMetadata {\n constructor(\n readonly user: User,\n readonly batchId: BatchId,\n readonly state: MutationBatchState,\n readonly error?: FirestoreError\n ) {\n assert(\n (error !== undefined) === (state === 'rejected'),\n `MutationMetadata must contain an error iff state is 'rejected'`\n );\n }\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 */\n static fromWebStorageEntry(\n user: User,\n batchId: BatchId,\n value: string\n ): MutationMetadata | null {\n const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n let validData =\n typeof mutationBatch === 'object' &&\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n -1 &&\n (mutationBatch.error === undefined ||\n typeof mutationBatch.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && mutationBatch.error) {\n validData =\n typeof mutationBatch.error.message === 'string' &&\n typeof mutationBatch.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n mutationBatch.error.code as Code,\n mutationBatch.error.message\n );\n }\n }\n\n if (validData) {\n return new MutationMetadata(\n user,\n batchId,\n mutationBatch.state,\n firestoreError\n );\n } else {\n error(\n LOG_TAG,\n `Failed to parse mutation state for ID '${batchId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const batchMetadata: MutationMetadataSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n batchMetadata.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(batchMetadata);\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\nexport class QueryTargetMetadata {\n constructor(\n readonly targetId: TargetId,\n readonly state: QueryTargetState,\n readonly error?: FirestoreError\n ) {\n assert(\n (error !== undefined) === (state === 'rejected'),\n `QueryTargetMetadata must contain an error iff state is 'rejected'`\n );\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 */\n static fromWebStorageEntry(\n targetId: TargetId,\n value: string\n ): QueryTargetMetadata | null {\n const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n let validData =\n typeof targetState === 'object' &&\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n -1 &&\n (targetState.error === undefined ||\n typeof targetState.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && targetState.error) {\n validData =\n typeof targetState.error.message === 'string' &&\n typeof targetState.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n targetState.error.code as Code,\n targetState.error.message\n );\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(\n targetId,\n targetState.state,\n firestoreError\n );\n } else {\n error(\n LOG_TAG,\n `Failed to parse target state for ID '${targetId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const targetState: QueryTargetStateSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n targetState.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(targetState);\n }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to.\n */\n// Visible for testing.\nexport interface ClientState {\n readonly activeTargetIds: TargetIdSet;\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 */\nclass RemoteClientState implements ClientState {\n private constructor(\n readonly clientId: ClientId,\n readonly activeTargetIds: TargetIdSet\n ) {}\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 */\n static fromWebStorageEntry(\n clientId: ClientId,\n value: string\n ): RemoteClientState | null {\n const clientState = JSON.parse(value) as ClientStateSchema;\n\n let validData =\n typeof clientState === 'object' &&\n clientState.activeTargetIds instanceof Array;\n\n let activeTargetIdsSet = targetIdSet();\n\n for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(\n clientState.activeTargetIds[i]\n );\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n error(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\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 */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\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 */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n onlineState.onlineState in OnlineState &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n OnlineState[onlineState.onlineState as keyof typeof OnlineState]\n );\n } else {\n error(LOG_TAG, `Failed to parse online state: ${value}`);\n return null;\n }\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.\nexport class LocalClientState implements ClientState {\n activeTargetIds = targetIdSet();\n\n addQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n }\n\n removeQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n }\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 */\n toWebStorageJSON(): string {\n const data: ClientStateSchema = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n return JSON.stringify(data);\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 */\nexport class WebStorageSharedClientState implements SharedClientState {\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n private readonly storage: Storage;\n private readonly localClientStorageKey: string;\n private readonly sequenceNumberKey: string;\n private readonly activeClients: { [key: string]: ClientState } = {};\n private readonly storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private started = false;\n private currentUser: User;\n\n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n private earlyEvents: StorageEvent[] = [];\n\n constructor(\n private readonly queue: AsyncQueue,\n private readonly platform: Platform,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\n ) {\n if (!WebStorageSharedClientState.isAvailable(this.platform)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'LocalStorage is not available on this platform.'\n );\n }\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const escapedPersistenceKey = persistenceKey.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&'\n );\n\n this.storage = this.platform.window!.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = createWebStorageClientStateKey(\n this.persistenceKey,\n this.localClientId\n );\n this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n this.persistenceKey\n );\n this.activeClients[this.localClientId] = new LocalClientState();\n\n this.clientStateKeyRe = new RegExp(\n `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n );\n this.mutationBatchKeyRe = new RegExp(\n `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n );\n this.queryTargetKeyRe = new RegExp(\n `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n );\n\n this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\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.platform.window!.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(platform: Platform): boolean {\n return !!(platform.window && platform.window.localStorage != null);\n }\n\n async start(): Promise<void> {\n assert(!this.started, 'WebStorageSharedClientState already started');\n assert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n assert(\n this.onlineStateHandler !== null,\n 'onlineStateHandler property must be set before calling start()'\n );\n\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const existingClients = await this.syncEngine!.getActiveClients();\n\n for (const clientId of existingClients) {\n if (clientId === this.localClientId) {\n continue;\n }\n\n const storageItem = this.getItem(\n createWebStorageClientStateKey(this.persistenceKey, clientId)\n );\n if (storageItem) {\n const clientState = RemoteClientState.fromWebStorageEntry(\n clientId,\n storageItem\n );\n if (clientState) {\n this.activeClients[clientState.clientId] = clientState;\n }\n }\n }\n\n this.persistClientState();\n\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n if (onlineStateJSON) {\n const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (const event of this.earlyEvents) {\n this.handleWebStorageEvent(event);\n }\n\n this.earlyEvents = [];\n\n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.platform.window!.addEventListener('unload', () => this.shutdown());\n\n this.started = true;\n }\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n let activeTargets = targetIdSet();\n objUtils.forEach(this.activeClients, (key, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n // This is not using `obj.forEach` since `forEach` doesn't support early\n // return.\n for (const clientId in this.activeClients) {\n if (this.activeClients.hasOwnProperty(clientId)) {\n if (this.activeClients[clientId].activeTargetIds.has(targetId)) {\n return true;\n }\n }\n }\n return false;\n }\n\n addPendingMutation(batchId: BatchId): void {\n this.persistMutationState(batchId, 'pending');\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n this.persistMutationState(batchId, state, error);\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.removeMutationState(batchId);\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n let queryState: QueryTargetState = 'not-current';\n\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(targetId)) {\n const storageItem = this.storage.getItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n\n if (storageItem) {\n const metadata = QueryTargetMetadata.fromWebStorageEntry(\n targetId,\n storageItem\n );\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n\n return queryState;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localClientState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n this.removeItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.persistQueryTargetState(targetId, state, error);\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n removedBatchIds.forEach(batchId => {\n this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(batchId => {\n this.addPendingMutation(batchId);\n });\n }\n\n setOnlineState(onlineState: OnlineState): void {\n this.persistOnlineState(onlineState);\n }\n\n shutdown(): void {\n if (this.started) {\n this.platform.window!.removeEventListener(\n 'storage',\n this.storageListener\n );\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n }\n\n private getItem(key: string): string | null {\n const value = this.storage.getItem(key);\n debug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n debug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n debug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: StorageEvent): void {\n if (event.storageArea === this.storage) {\n debug(LOG_TAG, 'EVENT', event.key, event.newValue);\n\n if (event.key === this.localClientStorageKey) {\n error(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueAndForget(async () => {\n if (!this.started) {\n this.earlyEvents.push(event);\n return;\n }\n\n if (event.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(event.key)) {\n if (event.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n event.key,\n event.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(event.key)!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(event.key)) {\n if (event.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n event.key,\n event.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(event.key)) {\n if (event.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n event.key,\n event.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (event.key === this.onlineStateKey) {\n if (event.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(event.newValue);\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (event.key === this.sequenceNumberKey) {\n assert(!!this.sequenceNumberHandler, 'Missing sequenceNumberHandler');\n const sequenceNumber = fromWebStorageSequenceNumber(event.newValue);\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients[this.localClientId] as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState: OnlineState[onlineState]\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */\n private fromWebStorageClientStateKey(key: string): ClientId | null {\n const match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n }\n\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */\n private fromWebStorageClientState(\n key: string,\n value: string\n ): RemoteClientState | null {\n const clientId = this.fromWebStorageClientStateKey(key);\n assert(clientId !== null, `Cannot parse client state key '${key}'`);\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n }\n\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageMutationMetadata(\n key: string,\n value: string\n ): MutationMetadata | null {\n const match = this.mutationBatchKeyRe.exec(key);\n assert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n const batchId = Number(match[1]);\n const userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(\n new User(userId),\n batchId,\n value\n );\n }\n\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageQueryTargetMetadata(\n key: string,\n value: string\n ): QueryTargetMetadata | null {\n const match = this.queryTargetKeyRe.exec(key);\n assert(match !== null, `Cannot parse query target key '${key}'`);\n\n const targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n }\n\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n return SharedOnlineState.fromWebStorageEntry(value);\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise<void> {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n debug(\n LOG_TAG,\n `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n );\n return;\n }\n\n return this.syncEngine!.applyBatchState(\n mutationBatch.batchId,\n mutationBatch.state,\n mutationBatch.error\n );\n }\n\n private handleQueryTargetEvent(\n targetMetadata: QueryTargetMetadata\n ): Promise<void> {\n return this.syncEngine!.applyTargetState(\n targetMetadata.targetId,\n targetMetadata.state,\n targetMetadata.error\n );\n }\n\n private handleClientStateEvent(\n clientId: ClientId,\n clientState: RemoteClientState | null\n ): Promise<void> {\n const existingTargets = this.getAllActiveQueryTargets();\n\n if (clientState) {\n this.activeClients[clientId] = clientState;\n } else {\n delete this.activeClients[clientId];\n }\n\n const newTargets = this.getAllActiveQueryTargets();\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(async targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(async targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n );\n }\n\n private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\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 if (this.activeClients[onlineState.clientId]) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n}\n\nfunction fromWebStorageSequenceNumber(\n seqString: string | null\n): ListenSequenceNumber {\n let sequenceNumber = ListenSequence.INVALID;\n if (seqString != null) {\n try {\n const parsed = JSON.parse(seqString);\n assert(typeof parsed === 'number', 'Found non-numeric sequence number');\n sequenceNumber = parsed;\n } catch (e) {\n error(LOG_TAG, 'Failed to read sequence number from WebStorage', e);\n }\n }\n return sequenceNumber;\n}\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 */\nexport class MemorySharedClientState implements SharedClientState {\n private localState = new LocalClientState();\n private queryState: { [targetId: number]: QueryTargetState } = {};\n\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n addPendingMutation(batchId: BatchId): void {\n // No op.\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n // No op.\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.queryState[targetId] = state;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localState.removeQueryTarget(targetId);\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n delete this.queryState[targetId];\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.localState.activeTargetIds;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n start(): Promise<void> {\n this.localState = new LocalClientState();\n return Promise.resolve();\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n // No op.\n }\n\n setOnlineState(onlineState: OnlineState): void {\n // No op.\n }\n\n shutdown(): void {}\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert } from '../util/assert';\nimport { TargetId } from './types';\n\nconst RESERVED_BITS = 1;\n\nenum GeneratorIds {\n QueryCache = 0, // The target IDs for user-issued queries are even (end in 0).\n SyncEngine = 1 // The target IDs for limbo detection are odd (end in 1).\n}\n\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 query cache (via\n * forQueryCache()), and one for limbo documents (via forSyncEngine()). These\n * two 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 */\n// TODO(mrschmidt): Explore removing this class in favor of generating these IDs\n// directly in SyncEngine and LocalStore.\nexport class TargetIdGenerator {\n // Initialized in the constructor via call to seek().\n private nextId!: TargetId;\n\n /**\n * Instantiates a new TargetIdGenerator. If a seed is provided, the generator\n * will use the seed value as the next target ID.\n */\n constructor(private generatorId: number, seed?: number) {\n assert(\n (generatorId & RESERVED_BITS) === generatorId,\n `Generator ID ${generatorId} contains more than ${RESERVED_BITS} reserved bits`\n );\n this.seek(seed !== undefined ? seed : this.generatorId);\n }\n\n next(): TargetId {\n const nextId = this.nextId;\n this.nextId += 1 << RESERVED_BITS;\n return nextId;\n }\n\n /**\n * Returns the ID that follows the given ID. Subsequent calls to `next()`\n * use the newly returned target ID as their base.\n */\n // PORTING NOTE: Multi-tab only.\n after(targetId: TargetId): TargetId {\n this.seek(targetId + (1 << RESERVED_BITS));\n return this.next();\n }\n\n private seek(targetId: TargetId): void {\n assert(\n (targetId & RESERVED_BITS) === this.generatorId,\n 'Cannot supply target ID from different generator ID'\n );\n this.nextId = targetId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // We seed the query cache generator to return '2' as its first ID, as there\n // is no differentiation in the protocol layer between an unset number and\n // the number '0'. If we were to sent a target with target ID '0', the\n // backend would consider it unset and replace it with its own ID.\n const targetIdGenerator = new TargetIdGenerator(GeneratorIds.QueryCache, 2);\n return targetIdGenerator;\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { QueryResult } from '../local/local_store';\nimport {\n documentKeySet,\n DocumentKeySet,\n MaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\n\nimport { Query } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\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 */\nexport class View {\n private syncState: SyncState | null = null;\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 private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\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 * @return a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: MaybeDocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\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 //\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 lastDocInLimit =\n this.query.hasLimitToFirst() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.hasLimitToLast() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal(\n (key: DocumentKey, newMaybeDoc: MaybeDocument) => {\n const oldDoc = oldDocumentSet.get(key);\n let newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(\n key.isEqual(newDoc.key),\n 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key\n );\n newDoc = this.query.matches(newDoc) ? newDoc : null;\n }\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data().isEqual(newDoc.data());\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.query.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.query.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\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 needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\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 needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n }\n );\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.hasLimitToFirst() || this.query.hasLimitToLast()) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc = this.query.hasLimitToFirst()\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n assert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\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 (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\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 this\n * change.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return 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(\n docChanges: ViewDocumentChanges,\n updateLimboDocuments: boolean,\n targetChange?: TargetChange\n ): ViewChange {\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.query.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n const limboChanges = updateLimboDocuments\n ? this.updateLimboDocuments()\n : [];\n const synced = this.limboDocuments.size === 0 && this.current;\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\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 */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\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 = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* updateLimboDocuments= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\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 */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key =>\n assert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n )\n );\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\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 * @return The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /*updateLimboDocuments=*/ true);\n }\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 computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case 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 case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n MaybeDocumentMap\n} from '../model/collections';\nimport { MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult, BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { RemoteStore } from '../remote/remote_store';\nimport { RemoteSyncer } from '../remote/remote_syncer';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Deferred } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from '../local/shared_client_state_syncer';\nimport * as objUtils from '../util/obj';\nimport { SortedSet } from '../util/sorted_set';\nimport { ListenSequence } from './listen_sequence';\nimport { Query, LimitType } from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\nimport { Transaction } from './transaction';\nimport {\n BatchId,\n MutationBatchState,\n OnlineState,\n OnlineStateSource,\n TargetId\n} from './types';\nimport {\n AddedLimboDocument,\n LimboDocumentChange,\n RemovedLimboDocument,\n View,\n ViewChange,\n ViewDocumentChanges\n} from './view';\nimport { ViewSnapshot } from './view_snapshot';\nimport { AsyncQueue } from '../util/async_queue';\nimport { TransactionRunner } from './transaction_runner';\n\nconst LOG_TAG = 'SyncEngine';\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass QueryView {\n constructor(\n /**\n * The query itself.\n */\n public query: Query,\n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n public targetId: TargetId,\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 public view: View\n ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n constructor(public key: DocumentKey) {}\n\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 receivedDocument: boolean = false;\n}\n\n/**\n * Interface implemented by EventManager to handle notifications from\n * SyncEngine.\n */\nexport interface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError(query: Query, error: Error): void;\n\n /** Handles a change in online state. */\n onOnlineStateChange(onlineState: OnlineState): void;\n}\n\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngines methods should only ever be called by methods running in the\n * global async queue.\n */\nexport class SyncEngine implements RemoteSyncer, SharedClientStateSyncer {\n private syncEngineListener: SyncEngineListener | null = null;\n\n private queryViewsByQuery = new ObjectMap<Query, QueryView>(q =>\n q.canonicalId()\n );\n private queriesByTarget: { [targetId: number]: Query[] } = {};\n private limboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n private limboResolutionsByTarget: {\n [targetId: number]: LimboResolution;\n } = {};\n private limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n private mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap<BatchId, Deferred<void>>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n private pendingWritesCallbacks = new Map<BatchId, Array<Deferred<void>>>();\n private limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\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 private isPrimary: undefined | boolean = undefined;\n private onlineState: OnlineState = OnlineState.Unknown;\n\n constructor(\n private localStore: LocalStore,\n private remoteStore: RemoteStore,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n private sharedClientState: SharedClientState,\n private currentUser: User\n ) {}\n\n // Only used for testing.\n get isPrimaryClient(): boolean {\n return this.isPrimary === true;\n }\n\n /** Subscribes to SyncEngine notifications. Has to be called exactly once. */\n subscribe(syncEngineListener: SyncEngineListener): void {\n assert(syncEngineListener !== null, 'SyncEngine listener cannot be null');\n assert(\n this.syncEngineListener === null,\n 'SyncEngine already has a subscriber.'\n );\n\n this.syncEngineListener = syncEngineListener;\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 targetId of the query.\n */\n async listen(query: Query): Promise<TargetId> {\n this.assertSubscribed('listen()');\n\n let targetId;\n let viewSnapshot;\n\n const queryView = this.queryViewsByQuery.get(query);\n if (queryView) {\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 targetId = queryView.targetId;\n this.sharedClientState.addLocalQueryTarget(targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n const targetData = await this.localStore.allocateTarget(query.toTarget());\n\n const status = this.sharedClientState.addLocalQueryTarget(\n targetData.targetId\n );\n targetId = targetData.targetId;\n viewSnapshot = await this.initializeViewAndComputeSnapshot(\n query,\n targetId,\n status === 'current'\n );\n if (this.isPrimary) {\n this.remoteStore.listen(targetData);\n }\n }\n\n this.syncEngineListener!.onWatchChange([viewSnapshot]);\n return targetId;\n }\n\n /**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\n private async initializeViewAndComputeSnapshot(\n query: Query,\n targetId: TargetId,\n current: boolean\n ): Promise<ViewSnapshot> {\n const queryResult = await this.localStore.executeQuery(\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && this.onlineState !== OnlineState.Offline\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ this.isPrimary === true,\n synthesizedTargetChange\n );\n assert(\n viewChange.limboChanges.length === 0,\n 'View returned limbo docs before target ack from the server.'\n );\n assert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n this.queryViewsByQuery.set(query, data);\n if (!this.queriesByTarget[targetId]) {\n this.queriesByTarget[targetId] = [];\n }\n this.queriesByTarget[targetId].push(query);\n return viewChange.snapshot!;\n }\n\n /**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\n // PORTING NOTE: Multi-tab only.\n private async synchronizeViewAndComputeSnapshot(\n queryView: QueryView\n ): Promise<ViewChange> {\n const queryResult = await this.localStore.executeQuery(\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot = queryView.view.synchronizeWithPersistedState(\n queryResult\n );\n if (this.isPrimary) {\n this.updateTrackedLimbos(queryView.targetId, viewSnapshot.limboChanges);\n }\n return viewSnapshot;\n }\n\n /** Stops listening to the query. */\n async unlisten(query: Query): Promise<void> {\n this.assertSubscribed('unlisten()');\n\n const queryView = this.queryViewsByQuery.get(query)!;\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = this.queriesByTarget[queryView.targetId];\n if (queries.length > 1) {\n this.queriesByTarget[queryView.targetId] = queries.filter(\n q => !q.isEqual(query)\n );\n this.queryViewsByQuery.delete(query);\n return;\n }\n\n // No other queries are mapped to the target, clean up the query and the target.\n if (this.isPrimary) {\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 this.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive = this.sharedClientState.isActiveQueryTarget(\n queryView.targetId\n );\n\n if (!targetRemainsActive) {\n await this.localStore\n .releaseTarget(queryView.targetId, /*keepPersistedTargetData=*/ false)\n .then(() => {\n this.sharedClientState.clearQueryState(queryView.targetId);\n this.remoteStore.unlisten(queryView.targetId);\n this.removeAndCleanupTarget(queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n this.removeAndCleanupTarget(queryView.targetId);\n await this.localStore.releaseTarget(\n queryView.targetId,\n /*keepPersistedTargetData=*/ true\n );\n }\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 */\n async write(batch: Mutation[], userCallback: Deferred<void>): Promise<void> {\n this.assertSubscribed('write()');\n const result = await this.localStore.localWrite(batch);\n this.sharedClientState.addPendingMutation(result.batchId);\n this.addMutationCallback(result.batchId, userCallback);\n await this.emitNewSnapsAndNotifyLocalStore(result.changes);\n await this.remoteStore.fillWritePipeline();\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 *\n * The Deferred input is resolved when the transaction is fully committed.\n */\n runTransaction<T>(\n asyncQueue: AsyncQueue,\n updateFunction: (transaction: Transaction) => Promise<T>,\n deferred: Deferred<T>\n ): void {\n new TransactionRunner<T>(\n asyncQueue,\n this.remoteStore,\n updateFunction,\n deferred\n ).run();\n }\n\n async applyRemoteEvent(remoteEvent: RemoteEvent): Promise<void> {\n this.assertSubscribed('applyRemoteEvent()');\n try {\n const changes = await this.localStore.applyRemoteEvent(remoteEvent);\n // Update `receivedDocument` as appropriate for any limbo targets.\n objUtils.forEach(remoteEvent.targetChanges, (targetId, targetChange) => {\n const limboResolution = this.limboResolutionsByTarget[Number(targetId)];\n if (limboResolution) {\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 assert(\n targetChange.addedDocuments.size +\n targetChange.modifiedDocuments.size +\n targetChange.removedDocuments.size <=\n 1,\n 'Limbo resolution for single document contains multiple changes.'\n );\n if (targetChange.addedDocuments.size > 0) {\n limboResolution.receivedDocument = true;\n } else if (targetChange.modifiedDocuments.size > 0) {\n assert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n assert(\n limboResolution.receivedDocument,\n 'Received remove for limbo target document without add.'\n );\n limboResolution.receivedDocument = false;\n } else {\n // This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n await this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error);\n }\n }\n\n /**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\n applyOnlineStateChange(\n onlineState: OnlineState,\n source: OnlineStateSource\n ): void {\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 (\n (this.isPrimary && source === OnlineStateSource.RemoteStore) ||\n (!this.isPrimary && source === OnlineStateSource.SharedClientState)\n ) {\n this.assertSubscribed('applyOnlineStateChange()');\n const newViewSnapshots = [] as ViewSnapshot[];\n this.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(\n viewChange.limboChanges.length === 0,\n 'OnlineState should not affect limbo documents.'\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n this.syncEngineListener!.onOnlineStateChange(onlineState);\n this.syncEngineListener!.onWatchChange(newViewSnapshots);\n\n this.onlineState = onlineState;\n if (this.isPrimary) {\n this.sharedClientState.setOnlineState(onlineState);\n }\n }\n }\n\n async rejectListen(targetId: TargetId, err: FirestoreError): Promise<void> {\n this.assertSubscribed('rejectListens()');\n\n // PORTING NOTE: Multi-tab only.\n this.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution = this.limboResolutionsByTarget[targetId];\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboResolutionsByTarget[targetId];\n\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\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 documentUpdates = new SortedMap<DocumentKey, MaybeDocument>(\n DocumentKey.comparator\n );\n documentUpdates = documentUpdates.insert(\n limboKey,\n new NoDocument(limboKey, SnapshotVersion.forDeletedDoc())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.MIN,\n /* targetChanges= */ {},\n /* targetMismatches= */ new SortedSet<TargetId>(primitiveComparator),\n documentUpdates,\n resolvedLimboDocuments\n );\n return this.applyRemoteEvent(event);\n } else {\n await this.localStore\n .releaseTarget(targetId, /* keepPersistedTargetData */ false)\n .then(() => this.removeAndCleanupTarget(targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n }\n\n // PORTING NOTE: Multi-tab only\n async applyBatchState(\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n ): Promise<void> {\n this.assertSubscribed('applyBatchState()');\n const documents = await this.localStore.lookupMutationDocuments(batchId);\n\n if (documents === null) {\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 log.debug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n return;\n }\n\n if (batchState === 'pending') {\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 this.remoteStore.fillWritePipeline();\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n this.processUserCallback(batchId, error ? error : null);\n this.localStore.removeCachedMutationBatchMetadata(batchId);\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await this.emitNewSnapsAndNotifyLocalStore(documents);\n }\n\n async applySuccessfulWrite(\n mutationBatchResult: MutationBatchResult\n ): Promise<void> {\n this.assertSubscribed('applySuccessfulWrite()');\n\n const batchId = mutationBatchResult.batch.batchId;\n\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 this.processUserCallback(batchId, /*error=*/ null);\n\n this.triggerPendingWritesCallbacks(batchId);\n\n try {\n const changes = await this.localStore.acknowledgeBatch(\n mutationBatchResult\n );\n this.sharedClientState.updateMutationState(batchId, 'acknowledged');\n await this.emitNewSnapsAndNotifyLocalStore(changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error);\n }\n }\n\n async rejectFailedWrite(\n batchId: BatchId,\n error: FirestoreError\n ): Promise<void> {\n this.assertSubscribed('rejectFailedWrite()');\n\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 this.processUserCallback(batchId, error);\n\n this.triggerPendingWritesCallbacks(batchId);\n\n try {\n const changes = await this.localStore.rejectBatch(batchId);\n this.sharedClientState.updateMutationState(batchId, 'rejected', error);\n await this.emitNewSnapsAndNotifyLocalStore(changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error);\n }\n }\n\n /**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\n async registerPendingWritesCallback(callback: Deferred<void>): Promise<void> {\n if (!this.remoteStore.canUseNetwork()) {\n log.debug(\n LOG_TAG,\n 'The network is disabled. The task returned by ' +\n \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n );\n }\n\n const highestBatchId = await this.localStore.getHighestUnacknowledgedBatchId();\n if (highestBatchId === BATCHID_UNKNOWN) {\n // Trigger the callback right away if there is no pending writes at the moment.\n callback.resolve();\n return;\n }\n\n const callbacks = this.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n this.pendingWritesCallbacks.set(highestBatchId, callbacks);\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 */\n private triggerPendingWritesCallbacks(batchId: BatchId): void {\n (this.pendingWritesCallbacks.get(batchId) || []).forEach(callback => {\n callback.resolve();\n });\n\n this.pendingWritesCallbacks.delete(batchId);\n }\n\n /** Reject all outstanding callbacks waiting for pending writes to complete. */\n private rejectOutstandingPendingWritesCallbacks(errorMessage: string): void {\n this.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n this.pendingWritesCallbacks.clear();\n }\n\n private addMutationCallback(\n batchId: BatchId,\n callback: Deferred<void>\n ): void {\n let newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap<BatchId, Deferred<void>>(\n primitiveComparator\n );\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n private processUserCallback(batchId: BatchId, error: Error | null): void {\n let newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n\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 (newCallbacks) {\n const callback = newCallbacks.get(batchId);\n if (callback) {\n assert(\n batchId === newCallbacks.minKey(),\n 'Mutation callbacks processed out-of-order?'\n );\n if (error) {\n callback.reject(error);\n } else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n }\n\n private removeAndCleanupTarget(\n targetId: number,\n error: Error | null = null\n ): void {\n this.sharedClientState.removeLocalQueryTarget(targetId);\n\n assert(\n this.queriesByTarget[targetId] &&\n this.queriesByTarget[targetId].length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of this.queriesByTarget[targetId]) {\n this.queryViewsByQuery.delete(query);\n if (error) {\n this.syncEngineListener!.onWatchError(query, error);\n }\n }\n\n delete this.queriesByTarget[targetId];\n\n if (this.isPrimary) {\n const limboKeys = this.limboDocumentRefs.referencesForId(targetId);\n this.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced = this.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n this.removeLimboTarget(limboKey);\n }\n });\n }\n }\n\n private removeLimboTarget(key: DocumentKey): void {\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 limboTargetId = this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n this.remoteStore.unlisten(limboTargetId);\n this.limboTargetsByKey = this.limboTargetsByKey.remove(key);\n delete this.limboResolutionsByTarget[limboTargetId];\n }\n\n private updateTrackedLimbos(\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n ): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n log.debug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n const isReferenced = this.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n this.removeLimboTarget(limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n }\n\n private trackLimboChange(limboChange: AddedLimboDocument): void {\n const key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n log.debug(LOG_TAG, 'New document in limbo: ' + key);\n const limboTargetId = this.limboTargetIdGenerator.next();\n const query = Query.atPath(key.path);\n this.limboResolutionsByTarget[limboTargetId] = new LimboResolution(key);\n this.remoteStore.listen(\n new TargetData(\n query.toTarget(),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n this.limboTargetsByKey = this.limboTargetsByKey.insert(\n key,\n limboTargetId\n );\n }\n }\n\n // Visible for testing\n currentLimboDocs(): SortedMap<DocumentKey, TargetId> {\n return this.limboTargetsByKey;\n }\n\n private async emitNewSnapsAndNotifyLocalStore(\n changes: MaybeDocumentMap,\n remoteEvent?: RemoteEvent\n ): Promise<void> {\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array<Promise<void>> = [];\n\n this.queryViewsByQuery.forEach((_, queryView) => {\n queriesProcessed.push(\n Promise.resolve()\n .then(() => {\n const viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\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 return this.localStore\n .executeQuery(queryView.query, /* usePreviousResults= */ false)\n .then(({ documents }) => {\n return queryView.view.computeDocChanges(\n documents,\n viewDocChanges\n );\n });\n })\n .then((viewDocChanges: ViewDocumentChanges) => {\n const targetChange =\n remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ this.isPrimary === true,\n targetChange\n );\n this.updateTrackedLimbos(\n queryView.targetId,\n viewChange.limboChanges\n );\n if (viewChange.snapshot) {\n if (this.isPrimary) {\n this.sharedClientState.updateQueryState(\n queryView.targetId,\n viewChange.snapshot.fromCache ? 'not-current' : 'current'\n );\n }\n\n newSnaps.push(viewChange.snapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewChange.snapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n this.syncEngineListener!.onWatchChange(newSnaps);\n await this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n }\n\n private assertSubscribed(fnName: string): void {\n assert(\n this.syncEngineListener !== null,\n 'Trying to call ' + fnName + ' before calling subscribe().'\n );\n }\n\n async handleCredentialChange(user: User): Promise<void> {\n const userChanged = !this.currentUser.isEqual(user);\n this.currentUser = user;\n\n if (userChanged) {\n // Fails tasks waiting for pending writes requested by previous user.\n this.rejectOutstandingPendingWritesCallbacks(\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n\n const result = await this.localStore.handleUserChange(user);\n // TODO(b/114226417): Consider calling this only in the primary tab.\n this.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await this.emitNewSnapsAndNotifyLocalStore(result.affectedDocuments);\n }\n\n await this.remoteStore.handleCredentialChange();\n }\n\n // PORTING NOTE: Multi-tab only\n async applyPrimaryState(isPrimary: boolean): Promise<void> {\n if (isPrimary === true && this.isPrimary !== true) {\n this.isPrimary = true;\n await this.remoteStore.applyPrimaryState(true);\n\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 activeTargets = this.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await this.synchronizeQueryViewsAndRaiseSnapshots(\n activeTargets.toArray()\n );\n for (const targetData of activeQueries) {\n this.remoteStore.listen(targetData);\n }\n } else if (isPrimary === false && this.isPrimary !== false) {\n this.isPrimary = false;\n\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n objUtils.forEachNumber(this.queriesByTarget, (targetId, _) => {\n if (this.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n this.removeAndCleanupTarget(targetId);\n return this.localStore.releaseTarget(\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n this.remoteStore.unlisten(targetId);\n });\n await p;\n\n await this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets);\n this.resetLimboDocuments();\n await this.remoteStore.applyPrimaryState(false);\n }\n }\n\n // PORTING NOTE: Multi-tab only.\n private resetLimboDocuments(): void {\n objUtils.forEachNumber(this.limboResolutionsByTarget, targetId => {\n this.remoteStore.unlisten(targetId);\n });\n this.limboDocumentRefs.removeAllReferences();\n this.limboResolutionsByTarget = [];\n this.limboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n }\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 // PORTING NOTE: Multi-tab only.\n private async synchronizeQueryViewsAndRaiseSnapshots(\n targets: TargetId[]\n ): Promise<TargetData[]> {\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = this.queriesByTarget[targetId];\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we need to update their state\n // in 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 await this.localStore.releaseTarget(\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n targetData = await this.localStore.allocateTarget(\n queries[0].toTarget()\n );\n\n for (const query of queries) {\n const queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, `No query view found for ${query}`);\n\n const viewChange = await this.synchronizeViewAndComputeSnapshot(\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n assert(\n this.isPrimary === true,\n 'A secondary tab should never have an active target without an active query.'\n );\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 target = await this.localStore.getTarget(targetId);\n assert(!!target, `Target for id ${targetId} not found`);\n targetData = await this.localStore.allocateTarget(target);\n await this.initializeViewAndComputeSnapshot(\n this.synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n this.syncEngineListener!.onWatchChange(newViewSnapshots);\n return activeQueries;\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\n private synthesizeTargetToQuery(target: Target): Query {\n return new Query(\n target.path,\n target.collectionGroup,\n target.orderBy,\n target.filters,\n target.limit,\n LimitType.First,\n target.startAt,\n target.endAt\n );\n }\n\n // PORTING NOTE: Multi-tab only\n getActiveClients(): Promise<ClientId[]> {\n return this.localStore.getActiveClients();\n }\n\n // PORTING NOTE: Multi-tab only\n async applyTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): Promise<void> {\n if (this.isPrimary) {\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 log.debug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n if (this.queriesByTarget[targetId]) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await this.localStore.getNewDocumentChanges();\n const synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current'\n );\n await this.emitNewSnapsAndNotifyLocalStore(\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await this.localStore.releaseTarget(\n targetId,\n /* keepPersistedTargetData */ true\n );\n this.removeAndCleanupTarget(targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n }\n\n // PORTING NOTE: Multi-tab only\n async applyActiveTargetsChange(\n added: TargetId[],\n removed: TargetId[]\n ): Promise<void> {\n if (!this.isPrimary) {\n return;\n }\n\n for (const targetId of added) {\n assert(\n !this.queriesByTarget[targetId],\n 'Trying to add an already active target'\n );\n const target = await this.localStore.getTarget(targetId);\n assert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await this.localStore.allocateTarget(target);\n await this.initializeViewAndComputeSnapshot(\n this.synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false\n );\n this.remoteStore.listen(targetData);\n }\n\n for (const targetId of removed) {\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 if (!this.queriesByTarget[targetId]) {\n continue;\n }\n\n // Release queries that are still active.\n await this.localStore\n .releaseTarget(targetId, /* keepPersistedTargetData */ false)\n .then(() => {\n this.remoteStore.unlisten(targetId);\n this.removeAndCleanupTarget(targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n }\n\n // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\n // the online state.\n enableNetwork(): Promise<void> {\n this.localStore.setNetworkEnabled(true);\n return this.remoteStore.enableNetwork();\n }\n\n // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\n // the online state.\n disableNetwork(): Promise<void> {\n this.localStore.setNetworkEnabled(false);\n return this.remoteStore.disableNetwork();\n }\n\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet {\n const limboResolution = this.limboResolutionsByTarget[targetId];\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = this.queriesByTarget[targetId];\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, `No query view found for ${query}`);\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert } from '../util/assert';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Query } from './query';\nimport { SyncEngine, SyncEngineListener } from './sync_engine';\nimport { OnlineState, TargetId } from './types';\nimport { DocumentViewChange, ChangeType, ViewSnapshot } from './view_snapshot';\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nclass QueryListenersInfo {\n viewSnap: ViewSnapshot | null = null;\n targetId: TargetId = 0;\n listeners: QueryListener[] = [];\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer<T> {\n next: EventHandler<T>;\n error: EventHandler<Error>;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nexport class EventManager implements SyncEngineListener {\n private queries = new ObjectMap<Query, QueryListenersInfo>(q =>\n q.canonicalId()\n );\n\n private onlineState: OnlineState = OnlineState.Unknown;\n\n private snapshotsInSyncListeners: Set<Observer<void>> = new Set();\n\n constructor(private syncEngine: SyncEngine) {\n this.syncEngine.subscribe(this);\n }\n\n listen(listener: QueryListener): Promise<TargetId> {\n const query = listener.query;\n let firstListen = false;\n\n let queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(this.onlineState);\n assert(\n !raisedEvent,\n \"applyOnlineStateChange() shouldn't raise an event for brand-new listeners.\"\n );\n\n if (queryInfo.viewSnap) {\n const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap);\n if (raisedEvent) {\n this.raiseSnapshotsInSyncEvent();\n }\n }\n\n if (firstListen) {\n return this.syncEngine.listen(query).then(targetId => {\n queryInfo!.targetId = targetId;\n return targetId;\n });\n } else {\n return Promise.resolve(queryInfo.targetId);\n }\n }\n\n async unlisten(listener: QueryListener): Promise<void> {\n const query = listener.query;\n let lastListen = false;\n\n const queryInfo = this.queries.get(query);\n if (queryInfo) {\n const i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n\n if (lastListen) {\n this.queries.delete(query);\n return this.syncEngine.unlisten(query);\n }\n }\n\n onWatchChange(viewSnaps: ViewSnapshot[]): void {\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n if (listener.onViewSnapshot(viewSnap)) {\n raisedEvent = true;\n }\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n if (raisedEvent) {\n this.raiseSnapshotsInSyncEvent();\n }\n }\n\n onWatchError(query: Query, error: Error): void {\n const queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n }\n\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n }\n\n onOnlineStateChange(onlineState: OnlineState): void {\n this.onlineState = onlineState;\n let raisedEvent = false;\n this.queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n if (listener.applyOnlineStateChange(onlineState)) {\n raisedEvent = true;\n }\n }\n });\n if (raisedEvent) {\n this.raiseSnapshotsInSyncEvent();\n }\n }\n\n addSnapshotsInSyncListener(observer: Observer<void>): void {\n this.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n }\n\n removeSnapshotsInSyncListener(observer: Observer<void>): void {\n this.snapshotsInSyncListeners.delete(observer);\n }\n\n // Call all global snapshot listeners that have been set.\n private raiseSnapshotsInSyncEvent(): void {\n this.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n }\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\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 */\nexport class QueryListener {\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 private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState: OnlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer<ViewSnapshot>,\n options?: ListenOptions\n ) {\n this.options = 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 */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n assert(\n snap.docChanges.length > 0 || snap.syncStateChanged,\n 'We got a new snapshot with no changes?'\n );\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const docChanges: DocumentViewChange[] = [];\n for (const docChange of snap.docChanges) {\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(\n snap.query,\n snap.docs,\n snap.oldDocs,\n docChanges,\n snap.mutatedKeys,\n snap.fromCache,\n snap.syncStateChanged,\n /* excludesMetadataChanges= */ true\n );\n }\n let raisedEvent = false;\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n raisedEvent = true;\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n raisedEvent = true;\n }\n\n this.snap = snap;\n return raisedEvent;\n }\n\n onError(error: Error): void {\n this.queryObserver.error(error);\n }\n\n /** Returns whether a snapshot was raised. */\n applyOnlineStateChange(onlineState: OnlineState): boolean {\n this.onlineState = onlineState;\n let raisedEvent = false;\n if (\n this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)\n ) {\n this.raiseInitialEvent(this.snap);\n raisedEvent = true;\n }\n return raisedEvent;\n }\n\n private shouldRaiseInitialEvent(\n snap: ViewSnapshot,\n onlineState: OnlineState\n ): boolean {\n assert(\n !this.raisedInitialEvent,\n 'Determining whether to raise first event but already had first event'\n );\n\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(\n snap.fromCache,\n 'Waiting for sync, but snapshot is not from cache'\n );\n return false;\n }\n\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\n }\n\n private shouldRaiseEvent(snap: ViewSnapshot): boolean {\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 (snap.docChanges.length > 0) {\n return true;\n }\n\n const hasPendingWritesChanged =\n this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\n }\n\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 return false;\n }\n\n private raiseInitialEvent(snap: ViewSnapshot): void {\n assert(\n !this.raisedInitialEvent,\n 'Trying to raise initial events for second time'\n );\n snap = ViewSnapshot.fromInitialDocuments(\n snap.query,\n snap.docs,\n snap.mutatedKeys,\n snap.fromCache\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { Deferred } from '../util/promise';\nimport { TimerId, AsyncQueue } from '../util/async_queue';\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Transaction } from './transaction';\nimport { RemoteStore } from '../remote/remote_store';\nimport { isNullOrUndefined } from '../util/types';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { FirestoreError } from '../util/error';\n\nconst RETRY_COUNT = 5;\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner<T> {\n private retries = RETRY_COUNT;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly remoteStore: RemoteStore,\n private readonly updateFunction: (transaction: Transaction) => Promise<T>,\n private readonly deferred: Deferred<T>\n ) {\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.RetryTransaction\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = this.remoteStore.createTransaction();\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise<T> | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.retries > 0 && this.isRetryableTransactionError(error)) {\n this.retries -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error): boolean {\n if (error.name === 'FirebaseError') {\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 code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encode(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\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 */\nexport function decode(path: EncodedResourcePath): ResourcePath {\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 length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 'Non-empty path ' + path + ' had length 2'\n );\n return ResourcePath.EMPTY_PATH;\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\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 end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nexport function prefixSuccessor(\n path: EncodedResourcePath\n): EncodedResourcePath {\n const c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { getUA } from '@firebase/util';\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug, error } from '../util/log';\nimport { Deferred } from '../util/promise';\nimport { SCHEMA_VERSION } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readonly-idempotent'\n | 'readwrite-idempotent';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void>;\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 */\nexport class SimpleDb {\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support downgrading the schema\n * version. We currently do not support any way to do versioning outside of IndexedDB's versioning\n * mechanism, as only version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n static openOrCreate(\n name: string,\n version: number,\n schemaConverter: SimpleDbSchemaConverter\n ): Promise<SimpleDb> {\n assert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n debug(LOG_TAG, 'Opening database:', name);\n return new PersistencePromise<SimpleDb>((resolve, reject) => {\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 request = window.indexedDB.open(name, version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(new SimpleDb(db));\n };\n\n request.onblocked = () => {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else {\n reject(error);\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n debug(\n LOG_TAG,\n 'Database \"' + name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n SCHEMA_VERSION\n )\n .next(() => {\n debug(\n LOG_TAG,\n 'Database upgrade to version ' + SCHEMA_VERSION + ' complete'\n );\n });\n };\n }).toPromise();\n }\n\n /** Deletes the specified database. */\n static delete(name: string): Promise<void> {\n debug(LOG_TAG, 'Removing database:', name);\n return wrapRequest<void>(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // In some Node environments, `window` is defined, but `window.navigator` is\n // not. We don't support IndexedDB persistence in Node if the\n // isMockPersistence() check above returns false.\n if (window.navigator === undefined) {\n return false;\n }\n\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\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\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\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = SimpleDb.getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore<KeyType extends IDBValidKey, ValueType extends unknown>(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore<KeyType, ValueType> {\n return txn.store<KeyType, ValueType>(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1]\n .split('_')\n .slice(0, 2)\n .join('.')\n : '-1';\n return Number(version);\n }\n\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1]\n .split('.')\n .slice(0, 2)\n .join('.')\n : '-1';\n return Number(version);\n }\n\n constructor(private db: IDBDatabase) {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\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 if (iOSVersion === 12.2) {\n error(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n\n async runTransaction<T>(\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n ): Promise<T> {\n const readonly = mode.startsWith('readonly');\n const idempotent = mode.endsWith('idempotent');\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n try {\n const transactionFnResult = transactionFn(transaction)\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject<T>(error);\n })\n .toPromise();\n\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 transactionFnResult.catch(() => {});\n\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 transaction.completionPromise;\n return transactionFnResult;\n } catch (error) {\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\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 const retryable =\n idempotent &&\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n debug(\n LOG_TAG,\n 'Transaction failed with error: %s. Retrying: %s.',\n error.message,\n retryable\n );\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n this.db.close();\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 */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\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 */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise<void> {\n return wrapRequest<void>(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback<KeyType, ValueType> = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise<void>;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A promise that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred<void>();\n\n static open(\n db: IDBDatabase,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\n }\n\n constructor(private readonly transaction: IDBTransaction) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(transaction.error);\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(error);\n };\n }\n\n get completionPromise(): Promise<void> {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n debug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\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 */\n store<KeyType extends IDBValidKey, ValueType extends unknown>(\n storeName: string\n ): SimpleDbStore<KeyType, ValueType> {\n const store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore<KeyType, ValueType>(store);\n }\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 */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value The object to write.\n */\n put(value: ValueType): PersistencePromise<void>;\n put(key: KeyType, value: ValueType): PersistencePromise<void>;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise<void> {\n let request;\n if (value !== undefined) {\n debug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n debug(LOG_TAG, 'PUT', this.store.name, '<auto-key>', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest<void>(request);\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 * @return The key of the value to add.\n */\n add(value: ValueType): PersistencePromise<KeyType> {\n debug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest<KeyType>(request);\n }\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 * @return The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise<ValueType | null> {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest<any>(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n debug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest<void>(request);\n }\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 */\n count(): PersistencePromise<number> {\n debug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest<number>(request);\n }\n\n loadAll(): PersistencePromise<ValueType[]>;\n loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<ValueType[]> {\n const cursor = this.cursor(this.options(indexOrRange, range));\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n\n deleteAll(): PersistencePromise<void>;\n deleteAll(range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<void> {\n debug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options Options specifying how to iterate the objects in the store.\n * @param callback will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n options: IterateOptions,\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback<KeyType, ValueType>,\n callback?: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback<KeyType, ValueType>;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\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 */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise<boolean>\n ): PersistencePromise<void> {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n const results: Array<PersistencePromise<void>> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise<void> = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => {\n return PersistencePromise.waitFor(results);\n });\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n assert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\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 */\nfunction wrapRequest<R>(request: IDBRequest): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { User } from '../auth/user';\nimport { Query } from '../core/query';\nimport { BatchId, ProtoByteString } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport {\n IndexedDbPersistence,\n IndexedDbTransaction\n} from './indexeddb_persistence';\nimport {\n DbDocumentMutation,\n DbDocumentMutationKey,\n DbMutationBatch,\n DbMutationBatchKey,\n DbMutationQueue,\n DbMutationQueueKey\n} from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { PersistenceTransaction, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\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 private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\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 */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\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 assert(user.uid !== '', 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean> {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatch.userMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n acknowledgeBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch,\n streamToken: ProtoByteString\n ): PersistencePromise<void> {\n return this.getMutationQueueMetadata(transaction).next(metadata => {\n metadata.lastStreamToken = convertStreamToken(streamToken);\n\n return mutationQueuesStore(transaction).put(metadata);\n });\n }\n\n getLastStreamToken(\n transaction: PersistenceTransaction\n ): PersistencePromise<ProtoByteString> {\n return this.getMutationQueueMetadata(transaction).next<ProtoByteString>(\n metadata => metadata.lastStreamToken\n );\n }\n\n setLastStreamToken(\n transaction: PersistenceTransaction,\n streamToken: ProtoByteString\n ): PersistencePromise<void> {\n return this.getMutationQueueMetadata(transaction).next(metadata => {\n metadata.lastStreamToken = convertStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(metadata);\n });\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\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\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n assert(typeof batchId === 'number', 'Auto-generated key is not a number');\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n\n const promises: Array<PersistencePromise<void>> = [];\n let collectionParents = new SortedSet<ResourcePath>((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = DbDocumentMutation.key(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutation.PLACEHOLDER)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n assert(\n dbBatch.userId === this.userId,\n `Unexpected user '${dbBatch.userId}' for mutation batch ${batchId}`\n );\n return this.serializer.fromDbMutationBatch(dbBatch);\n }\n return null;\n });\n }\n\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<DocumentKeySet | null> {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve<DocumentKeySet | null>(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatch.userMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n assert(\n dbBatch.batchId >= nextBatchId,\n 'Should have found mutation after ' + nextBatchId\n );\n foundBatch = this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise<BatchId> {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatch.userMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise<MutationBatch[]> {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatch.userMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => this.serializer.fromDbMutationBatch(dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutationBatch[]> {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = DbDocumentMutation.prefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\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 const path = EncodedResourcePath.decode(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 'Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n batchId\n );\n }\n assert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(this.serializer.fromDbMutationBatch(mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap<DocumentKey, unknown>\n ): PersistencePromise<MutationBatch[]> {\n let uniqueBatchIDs = new SortedSet<BatchId>(primitiveComparator);\n\n const promises: Array<PersistencePromise<void>> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = DbDocumentMutation.prefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\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 const path = EncodedResourcePath.decode(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<MutationBatch[]> {\n assert(\n !query.isDocumentQuery(),\n \"Document queries shouldn't go down this path\"\n );\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = DbDocumentMutation.prefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\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 uniqueBatchIDs = new SortedSet<BatchId>(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = EncodedResourcePath.decode(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\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 if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet<BatchId>\n ): PersistencePromise<MutationBatch[]> {\n const results: MutationBatch[] = [];\n const promises: Array<PersistencePromise<void>> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 'Dangling document-mutation reference found, ' +\n 'which points to ' +\n batchId\n );\n }\n assert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(this.serializer.fromDbMutationBatch(mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise<void> {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.removeMutationReference(\n transaction,\n key\n );\n }\n );\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n DbDocumentMutation.prefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = EncodedResourcePath.decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n assert(\n danglingMutationReferences.length === 0,\n 'Document leak -- detected dangling mutation references when queue is empty. ' +\n 'Dangling keys: ' +\n danglingMutationReferences.map(p => p.canonicalString())\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\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 private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise<DbMutationQueue> {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata ||\n new DbMutationQueue(\n this.userId,\n BATCHID_UNKNOWN,\n /*lastStreamToken=*/ ''\n )\n );\n });\n }\n}\n\n/**\n * @return true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise<boolean> {\n const indexKey = DbDocumentMutation.prefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise<boolean> {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @return A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: MutationBatch\n): PersistencePromise<DocumentKey[]> {\n const mutationStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatch.store\n );\n const indexTxn = txn.store<DbDocumentMutationKey, DbDocumentMutation>(\n DbDocumentMutation.store\n );\n const promises: Array<PersistencePromise<void>> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n assert(\n numDeleted === 1,\n 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = DbDocumentMutation.key(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\nfunction convertStreamToken(token: ProtoByteString): string {\n if (token instanceof Uint8Array) {\n // TODO(b/78771403): Convert tokens to strings during deserialization\n assert(\n SimpleDb.isMockPersistence(),\n 'Persisting non-string stream tokens is only supported with mock persistence.'\n );\n return token.toString();\n } else {\n return token;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbMutationBatchKey, DbMutationBatch> {\n return IndexedDbPersistence.getStore<DbMutationBatchKey, DbMutationBatch>(\n txn,\n DbMutationBatch.store\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbDocumentMutationKey, DbDocumentMutation> {\n return IndexedDbPersistence.getStore<\n DbDocumentMutationKey,\n DbDocumentMutation\n >(txn, DbDocumentMutation.store);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbMutationQueueKey, DbMutationQueue> {\n return IndexedDbPersistence.getStore<DbMutationQueueKey, DbMutationQueue>(\n txn,\n DbMutationQueue.store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport {\n IndexedDbLruDelegate,\n IndexedDbPersistence,\n IndexedDbTransaction\n} from './indexeddb_persistence';\nimport {\n DbTarget,\n DbTargetDocument,\n DbTargetDocumentKey,\n DbTargetGlobal,\n DbTargetGlobalKey,\n DbTargetKey\n} from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\nimport { Target } from '../core/target';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\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\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestTargetId = this.targetIdGenerator.after(\n metadata.highestTargetId\n );\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<ListenSequenceNumber> {\n return getHighestListenSequenceNumber(\n (transaction as IndexedDbTransaction).simpleDbTransaction\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise<void> {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n assert(metadata.targetCount > 0, 'Removing from an empty target cache');\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\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 */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n let count = 0;\n const promises: Array<PersistencePromise<void>> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = this.serializer.fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = this.serializer.fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise<DbTargetGlobal> {\n return retrieveMetadata(\n (transaction as IndexedDbTransaction).simpleDbTransaction\n );\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise<void> {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return targetsStore(transaction).put(\n this.serializer.toDbTarget(targetData)\n );\n }\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 */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\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 canonicalId = target.canonicalId();\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTarget.queryTargetsIndexName },\n (key, value, control) => {\n const found = this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (target.isEqual(found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array<PersistencePromise<void>> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = EncodedResourcePath.encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n promises.push(this.referenceDelegate.addReference(txn, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = EncodedResourcePath.encode(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<void> {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<DocumentKeySet> {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = EncodedResourcePath.decode(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n const path = EncodedResourcePath.encode(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\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 if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<TargetData | null> {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return this.serializer.fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbTargetKey, DbTarget> {\n return IndexedDbPersistence.getStore<DbTargetKey, DbTarget>(\n txn,\n DbTarget.store\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbTargetGlobalKey, DbTargetGlobal> {\n return IndexedDbPersistence.getStore<DbTargetGlobalKey, DbTargetGlobal>(\n txn,\n DbTargetGlobal.store\n );\n}\n\nfunction retrieveMetadata(\n txn: SimpleDbTransaction\n): PersistencePromise<DbTargetGlobal> {\n const globalStore = SimpleDb.getStore<DbTargetGlobalKey, DbTargetGlobal>(\n txn,\n DbTargetGlobal.store\n );\n return globalStore.get(DbTargetGlobal.key).next(metadata => {\n assert(metadata !== null, 'Missing metadata row.');\n return metadata;\n });\n}\n\nexport function getHighestListenSequenceNumber(\n txn: SimpleDbTransaction\n): PersistencePromise<ListenSequenceNumber> {\n return retrieveMetadata(txn).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbTargetDocumentKey, DbTargetDocument> {\n return IndexedDbPersistence.getStore<DbTargetDocumentKey, DbTargetDocument>(\n txn,\n DbTargetDocument.store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Query } from '../core/query';\nimport {\n DocumentKeySet,\n DocumentMap,\n documentMap,\n DocumentSizeEntries,\n DocumentSizeEntry,\n MaybeDocumentMap,\n maybeDocumentMap,\n nullableMaybeDocumentMap,\n NullableMaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport {\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentKey\n} from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { IterateOptions, SimpleDbStore } from './simple_db';\nimport { ObjectMap } from '../util/obj_map';\n\nexport class IndexedDbRemoteDocumentCache implements RemoteDocumentCache {\n /**\n * @param {LocalSerializer} serializer The document serializer.\n * @param {IndexManager} indexManager The query indexes that need to be maintained.\n */\n constructor(\n readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager\n ) {}\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 */\n private addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise<void> {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(dbKey(key), doc);\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 */\n private removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<void> {\n const store = remoteDocumentsStore(transaction);\n const key = dbKey(documentKey);\n return store.delete(key);\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 */\n private updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise<void> {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(dbRemoteDoc => {\n return this.maybeDecodeDocument(dbRemoteDoc);\n });\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey The key of the entry to look up.\n * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<DocumentSizeEntry | null> {\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(dbRemoteDoc => {\n const doc = this.maybeDecodeDocument(dbRemoteDoc);\n return doc\n ? {\n maybeDocument: doc,\n size: dbDocumentSize(dbRemoteDoc!)\n }\n : null;\n });\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n let results = nullableMaybeDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys The set of keys entries to look up.\n * @return A map of MaybeDocuments indexed by key (if a document cannot be\n * found, the key will be mapped to null) and a map of sizes indexed by\n * key (zero if the key cannot be found).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<DocumentSizeEntries> {\n let results = nullableMaybeDocumentMap();\n let sizeMap = new SortedMap<DocumentKey, number>(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(dbRemoteDoc);\n if (doc) {\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc!));\n } else {\n results = results.insert(key, null);\n sizeMap = sizeMap.insert(key, 0);\n }\n }\n ).next(() => {\n return { maybeDocuments: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise<void> {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n const range = IDBKeyRange.bound(\n documentKeys.first()!.path.toArray(),\n documentKeys.last()!.path.toArray()\n );\n const keyIter = documentKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate({ range }, (potentialKeyRaw, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments(potentialKeyRaw);\n\n // Go through keys not found in cache.\n while (nextKey && DocumentKey.comparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(nextKey!.path.toArray());\n } else {\n control.done();\n }\n })\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 while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n let results = documentMap();\n\n const immediateChildrenPathLength = query.path.length + 1;\n\n const iterationOptions: IterateOptions = {};\n if (sinceReadTime.isEqual(SnapshotVersion.MIN)) {\n // Documents are ordered by key, so we can use a prefix scan to narrow\n // down the documents we need to match the query against.\n const startKey = query.path.toArray();\n iterationOptions.range = IDBKeyRange.lowerBound(startKey);\n } else {\n // Execute an index-free query and filter by read time. This is safe\n // since all document changes to queries that have a\n // lastLimboFreeSnapshotVersion (`sinceReadTime`) have a read time set.\n const collectionKey = query.path.toArray();\n const readTimeKey = this.serializer.toDbTimestampKey(sinceReadTime);\n iterationOptions.range = IDBKeyRange.lowerBound(\n [collectionKey, readTimeKey],\n /* open= */ true\n );\n iterationOptions.index = DbRemoteDocument.collectionReadTimeIndex;\n }\n\n return remoteDocumentsStore(transaction)\n .iterate(iterationOptions, (key, dbRemoteDoc, control) => {\n // The query is actually returning any path that starts with the query\n // path prefix which may include documents in subcollections. For\n // example, a query on 'rooms' will return rooms/abc/messages/xyx but we\n // shouldn't match it. Fix this by discarding rows with document keys\n // more than one segment longer than the query path.\n if (key.length !== immediateChildrenPathLength) {\n return;\n }\n\n const maybeDoc = this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n } else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(() => results);\n }\n\n getNewDocumentChanges(\n transaction: PersistenceTransaction,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<{\n changedDocs: MaybeDocumentMap;\n readTime: SnapshotVersion;\n }> {\n let changedDocs = maybeDocumentMap();\n\n let lastReadTime = this.serializer.toDbTimestampKey(sinceReadTime);\n\n const documentsStore = remoteDocumentsStore(transaction);\n const range = IDBKeyRange.lowerBound(lastReadTime, true);\n return documentsStore\n .iterate(\n { index: DbRemoteDocument.readTimeIndex, range },\n (_, dbRemoteDoc) => {\n // Unlike `getEntry()` and others, `getNewDocumentChanges()` parses\n // the documents directly since we want to keep sentinel deletes.\n const doc = this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n changedDocs = changedDocs.insert(doc.key, doc);\n lastReadTime = dbRemoteDoc.readTime!;\n }\n )\n .next(() => {\n return {\n changedDocs,\n readTime: this.serializer.fromDbTimestampKey(lastReadTime)\n };\n });\n }\n\n getLastReadTime(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n const documentsStore = remoteDocumentsStore(transaction);\n\n // If there are no existing entries, we return SnapshotVersion.MIN.\n let readTime = SnapshotVersion.MIN;\n\n return documentsStore\n .iterate(\n { index: DbRemoteDocument.readTimeIndex, reverse: true },\n (key, dbRemoteDoc, control) => {\n if (dbRemoteDoc.readTime) {\n readTime = this.serializer.fromDbTimestampKey(dbRemoteDoc.readTime);\n }\n control.done();\n }\n )\n .next(() => readTime);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentCache.RemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise<DbRemoteDocumentGlobal> {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobal.key)\n .next(metadata => {\n assert(!!metadata, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise<void> {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobal.key, metadata);\n }\n\n /**\n * Decodes `remoteDoc` and returns the document (or null, if the document\n * corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n dbRemoteDoc: DbRemoteDocument | null\n ): MaybeDocument | null {\n if (dbRemoteDoc) {\n const doc = this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (\n doc instanceof NoDocument &&\n doc.version.isEqual(SnapshotVersion.forDeletedDoc())\n ) {\n // The document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`.\n return null;\n }\n\n return doc;\n }\n return null;\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 */\n private static RemoteDocumentChangeBuffer = class extends RemoteDocumentChangeBuffer {\n // A map of document sizes prior to applying the changes in this buffer.\n protected documentSizes: ObjectMap<\n DocumentKey,\n number\n > = new ObjectMap(key => key.toString());\n\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(\n private readonly documentCache: IndexedDbRemoteDocumentCache,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet<ResourcePath>((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, maybeDocument) => {\n const previousSize = this.documentSizes.get(key);\n assert(\n previousSize !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n if (maybeDocument) {\n assert(\n !this.readTime.isEqual(SnapshotVersion.MIN),\n 'Cannot add a document with a read time of zero'\n );\n const doc = this.documentCache.serializer.toDbRemoteDocument(\n maybeDocument,\n this.readTime\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousSize!;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousSize!;\n if (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 deletedDoc = this.documentCache.serializer.toDbRemoteDocument(\n new NoDocument(key, SnapshotVersion.forDeletedDoc()),\n this.readTime\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n } else {\n promises.push(this.documentCache.removeEntry(transaction, key));\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n if (getResult === null) {\n this.documentSizes.set(documentKey, 0);\n return null;\n } else {\n this.documentSizes.set(documentKey, getResult.size);\n return getResult.maybeDocument;\n }\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ maybeDocuments, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `NullableMaybeDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentSizes.set(documentKey, size);\n });\n return maybeDocuments;\n });\n }\n };\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal> {\n return IndexedDbPersistence.getStore<\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobal\n >(txn, DbRemoteDocumentGlobal.store);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentKey, DbRemoteDocument> {\n return IndexedDbPersistence.getStore<DbRemoteDocumentKey, DbRemoteDocument>(\n txn,\n DbRemoteDocument.store\n );\n}\n\nfunction dbKey(docKey: DocumentKey): DbRemoteDocumentKey {\n return docKey.path.toArray();\n}\n\n/**\n * Retrusn an approximate size for the given document.\n */\nexport function dbDocumentSize(doc: DbRemoteDocument): number {\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { ResourcePath } from '../model/path';\nimport { assert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { IndexManager } from './index_manager';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\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 */\nexport class MemoryCollectionParentIndex {\n private index = {} as {\n [collectionId: string]: SortedSet<ResourcePath>;\n };\n\n // Returns false if the entry already existed.\n add(collectionPath: ResourcePath): boolean {\n assert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n const added = !existingParents.has(parentPath);\n this.index[collectionId] = existingParents.add(parentPath);\n return added;\n }\n\n has(collectionPath: ResourcePath): boolean {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents = this.index[collectionId];\n return existingParents && existingParents.has(parentPath);\n }\n\n getEntries(collectionId: string): ResourcePath[] {\n const parentPaths =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n return parentPaths.toArray();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert } from '../util/assert';\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { decode, encode, EncodedResourcePath } from './encoded_resource_path';\nimport { removeMutationBatch } from './indexeddb_mutation_queue';\nimport { getHighestListenSequenceNumber } from './indexeddb_target_cache';\nimport { dbDocumentSize } from './indexeddb_remote_document_cache';\nimport { LocalSerializer } from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\n * 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 */\nexport const SCHEMA_VERSION = 9;\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\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 */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void> {\n assert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v{toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction(txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\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 p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.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 dropRemoteDocumentChangesStore(db);\n createRemoteDocumentReadTimeIndex(txn);\n });\n }\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n let byteCount = 0;\n return txn\n .store<DbRemoteDocumentKey, DbRemoteDocument>(DbRemoteDocument.store)\n .iterate((_, doc) => {\n byteCount += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata = new DbRemoteDocumentGlobal(byteCount);\n return txn\n .store<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>(\n DbRemoteDocumentGlobal.store\n )\n .put(DbRemoteDocumentGlobal.key, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const queuesStore = txn.store<DbMutationQueueKey, DbMutationQueue>(\n DbMutationQueue.store\n );\n const mutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatch.store\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatch.userMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n assert(\n dbBatch.userId === queue.userId,\n `Cannot process batch ${dbBatch.batchId} from unexpected user`\n );\n const batch = this.serializer.fromDbMutationBatch(dbBatch);\n\n return removeMutationBatch(\n txn,\n queue.userId,\n batch\n ).next(() => {});\n }\n );\n });\n });\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 */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocument.store);\n const documentsStore = txn.store<DbRemoteDocumentKey, DbRemoteDocument>(\n DbRemoteDocument.store\n );\n\n return getHighestListenSequenceNumber(txn).next(currentSequenceNumber => {\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise<void> => {\n return documentTargetStore.put(\n new DbTargetDocument(0, encode(path), currentSequenceNumber)\n );\n };\n\n const promises: Array<PersistencePromise<void>> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n // Create the index.\n db.createObjectStore(DbCollectionParent.store, {\n keyPath: DbCollectionParent.keyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParent.store);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise<void> | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encode(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store<DbRemoteDocumentKey, DbRemoteDocument>(DbRemoteDocument.store)\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store<DbDocumentMutationKey, DbDocumentMutation>(\n DbDocumentMutation.store\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decode(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encode(path)];\n}\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport class DbTimestamp {\n constructor(public seconds: number, public nanoseconds: number) {}\n}\n\n/** A timestamp type that can be used in IndexedDb keys. */\nexport type DbTimestampKey = [/* seconds */ number, /* nanos */ number];\n\n// The key for the singleton object in the DbPrimaryClient is a single string.\nexport type DbPrimaryClientKey = typeof DbPrimaryClient.key;\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport class DbPrimaryClient {\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 static store = 'owner';\n\n /**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n static key = 'owner';\n\n constructor(\n public ownerId: string,\n /** Whether to allow shared access from multiple tabs. */\n public allowTabSynchronization: boolean,\n public leaseTimestampMs: number\n ) {}\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClient.store);\n}\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport class DbMutationQueue {\n /** Name of the IndexedDb object store. */\n static store = 'mutationQueues';\n\n /** Keys are automatically assigned via the userId property. */\n static keyPath = 'userId';\n\n constructor(\n /**\n * The normalized user ID to which this queue belongs.\n */\n public userId: string,\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n public lastAcknowledgedBatchId: number,\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n public lastStreamToken: string\n ) {}\n}\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport class DbMutationBatch {\n /** Name of the IndexedDb object store. */\n static store = 'mutations';\n\n /** Keys are automatically assigned via the userId, batchId properties. */\n static keyPath = 'batchId';\n\n /** The index name for lookup of mutations by user. */\n static userMutationsIndex = 'userMutationsIndex';\n\n /** The user mutations index is keyed by [userId, batchId] pairs. */\n static userMutationsKeyPath = ['userId', 'batchId'];\n\n constructor(\n /**\n * The normalized user ID to which this batch belongs.\n */\n public userId: string,\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n public batchId: BatchId,\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n public localWriteTimeMs: number,\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n public baseMutations: api.Write[] | undefined,\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n public mutations: api.Write[]\n ) {}\n}\n\n/**\n * The key for a db document mutation, which is made up of a userID, path, and\n * batchId. Note that the path must be serialized into a form that indexedDB can\n * sort.\n */\nexport type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId];\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatch.userMutationsIndex,\n DbMutationBatch.userMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutation.store);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise<void> {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatch.store\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatch.store);\n\n const mutationsStore = db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatch.userMutationsIndex,\n DbMutationBatch.userMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatch.store\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport class DbDocumentMutation {\n static store = 'documentMutations';\n\n /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n static prefixForUser(userId: string): [string] {\n return [userId];\n }\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 */\n static prefixForPath(\n userId: string,\n path: ResourcePath\n ): [string, EncodedResourcePath] {\n return [userId, encode(path)];\n }\n\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n static key(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n ): DbDocumentMutationKey {\n return [userId, encode(path), batchId];\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 */\n static PLACEHOLDER = new DbDocumentMutation();\n\n private constructor() {}\n}\n\n/**\n * A key in the 'remoteDocuments' object store is a string array containing the\n * segments that make up the path.\n */\nexport type DbRemoteDocumentKey = string[];\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocument.store);\n}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport class DbNoDocument {\n constructor(public path: string[], public readTime: DbTimestamp) {}\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport class DbUnknownDocument {\n constructor(public path: string[], public version: DbTimestamp) {}\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport class DbRemoteDocument {\n static store = 'remoteDocuments';\n\n /**\n * An index that provides access to all entries sorted by read time (which\n * corresponds to the last modification time of each row).\n *\n * This index is used to provide a changelog for Multi-Tab.\n */\n static readTimeIndex = 'readTimeIndex';\n\n static readTimeIndexPath = 'readTime';\n\n /**\n * An index that provides access to documents in a collection sorted by read\n * time.\n *\n * This index is used to allow the RemoteDocumentCache to fetch newly changed\n * documents in a collection.\n */\n static collectionReadTimeIndex = 'collectionReadTimeIndex';\n\n static collectionReadTimeIndexPath = ['parentPath', 'readTime'];\n\n // TODO: We are currently storing full document keys almost three times\n // (once as part of the primary key, once - partly - as `parentPath` and once\n // inside the encoded documents). During our next migration, we should\n // rewrite the primary key as parentPath + document ID which would allow us\n // to drop one value.\n\n constructor(\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n public unknownDocument: DbUnknownDocument | null | undefined,\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n public noDocument: DbNoDocument | null,\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n public document: api.Document | null,\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n public hasCommittedMutations: boolean | undefined,\n\n /**\n * When the document was read from the backend. Undefined for data written\n * prior to schema version 9.\n */\n public readTime: DbTimestampKey | undefined,\n\n /**\n * The path of the collection this document is part of. Undefined for data\n * written prior to schema version 9.\n */\n public parentPath: string[] | undefined\n ) {}\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport class DbRemoteDocumentGlobal {\n static store = 'remoteDocumentGlobal';\n\n static key = 'remoteDocumentGlobalKey';\n\n /**\n * @param byteSize Approximately the total size in bytes of all the documents in the document\n * cache.\n */\n constructor(public byteSize: number) {}\n}\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobal.key;\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobal.store);\n}\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = api.QueryTarget | api.DocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport class DbTarget {\n static store = 'targets';\n\n /** Keys are automatically assigned via the targetId property. */\n static keyPath = 'targetId';\n\n /** The name of the queryTargets index. */\n static queryTargetsIndexName = 'queryTargetsIndex';\n\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n static queryTargetsKeyPath = ['canonicalId', 'targetId'];\n\n constructor(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n public targetId: TargetId,\n /**\n * The canonical string representing this query. This is not unique.\n */\n public canonicalId: string,\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n public readTime: DbTimestamp,\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n public resumeToken: string,\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n public lastListenSequenceNumber: number,\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n public lastLimboFreeSnapshotVersion: DbTimestamp | undefined,\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n public query: DbQuery\n ) {}\n}\n\n/**\n * The key for a DbTargetDocument, containing a targetId and an encoded resource\n * path.\n */\nexport type DbTargetDocumentKey = [TargetId, EncodedResourcePath];\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport class DbTargetDocument {\n /** Name of the IndexedDb object store. */\n static store = 'targetDocuments';\n\n /** Keys are automatically assigned via the targetId, path properties. */\n static keyPath = ['targetId', 'path'];\n\n /** The index name for the reverse index. */\n static documentTargetsIndex = 'documentTargetsIndex';\n\n /** We also need to create the reverse index for these properties. */\n static documentTargetsKeyPath = ['path', 'targetId'];\n\n constructor(\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n public targetId: TargetId,\n /**\n * The path to the document, as encoded in the key.\n */\n public path: EncodedResourcePath,\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n public sequenceNumber?: ListenSequenceNumber\n ) {\n assert(\n (targetId === 0) === (sequenceNumber !== undefined),\n 'A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number'\n );\n }\n}\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobal.key;\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport class DbTargetGlobal {\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n static key = 'targetGlobalKey';\n static store = 'targetGlobal';\n\n constructor(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n public highestTargetId: TargetId,\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n public highestListenSequenceNumber: number,\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n public lastRemoteSnapshotVersion: DbTimestamp,\n /**\n * The number of targets persisted.\n */\n public targetCount: number\n ) {}\n}\n\n/**\n * The key for a DbCollectionParent entry, containing the collection ID\n * and the parent path that contains it. Note that the parent path will be an\n * empty path in the case of root-level collections.\n */\nexport type DbCollectionParentKey = [string, EncodedResourcePath];\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport class DbCollectionParent {\n /** Name of the IndexedDb object store. */\n static store = 'collectionParents';\n\n /** Keys are automatically assigned via the collectionId, parent properties. */\n static keyPath = ['collectionId', 'parent'];\n\n constructor(\n /**\n * The collectionId (e.g. 'messages')\n */\n public collectionId: string,\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n public parent: EncodedResourcePath\n ) {}\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\n keyPath: DbTargetDocument.keyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocument.documentTargetsIndex,\n DbTargetDocument.documentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTarget.queryTargetsIndexName,\n DbTarget.queryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobal.store);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocument.store);\n db.deleteObjectStore(DbTarget.store);\n db.deleteObjectStore(DbTargetGlobal.store);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise<void> {\n const globalStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>(\n DbTargetGlobal.store\n );\n const metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0,\n /*lastListenSequenceNumber=*/ 0,\n SnapshotVersion.MIN.toTimestamp(),\n /*targetCount=*/ 0\n );\n return globalStore.put(DbTargetGlobal.key, metadata);\n}\n\n/**\n * Creates indices on the RemoteDocuments store used for both multi-tab\n * and Index-Free queries.\n */\nfunction createRemoteDocumentReadTimeIndex(txn: IDBTransaction): void {\n const remoteDocumentStore = txn.objectStore(DbRemoteDocument.store);\n remoteDocumentStore.createIndex(\n DbRemoteDocument.readTimeIndex,\n DbRemoteDocument.readTimeIndexPath,\n { unique: false }\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocument.collectionReadTimeIndex,\n DbRemoteDocument.collectionReadTimeIndexPath,\n { unique: false }\n );\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport class DbClientMetadata {\n /** Name of the IndexedDb object store. */\n static store = 'clientMetadata';\n\n /** Keys are automatically assigned via the clientId properties. */\n static keyPath = 'clientId';\n\n constructor(\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n public clientId: string,\n /** The last time this state was updated. */\n public updateTimeMs: number,\n /** Whether the client's network connection is enabled. */\n public networkEnabled: boolean,\n /** Whether this client is running in a foreground tab. */\n public inForeground: boolean\n ) {}\n}\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadata.store, {\n keyPath: DbClientMetadata.keyPath\n });\n}\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbPrimaryClient.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n// V2 is no longer usable (see comment at top of file)\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n\n// Visible for testing\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadata.store];\n\n// V5 does not change the set of stores.\n\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobal.store];\n\n// V7 does not change the set of stores.\n\nexport const V8_STORES = [...V6_STORES, DbCollectionParent.store];\n\n// V9 does not change the set of stores.\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V8_STORES;\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { ResourcePath } from '../model/path';\nimport { assert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\nimport { decode, encode } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { DbCollectionParent, DbCollectionParentKey } from './indexeddb_schema';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * A persisted implementation of IndexManager.\n */\nexport class IndexedDbIndexManager implements IndexManager {\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 used to\n * satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\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 */\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n assert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n if (!this.collectionParentsCache.has(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n\n transaction.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.collectionParentsCache.add(collectionPath);\n });\n\n const collectionParent: DbCollectionParent = {\n collectionId,\n parent: encode(parentPath)\n };\n return collectionParentsStore(transaction).put(collectionParent);\n }\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n const parentPaths = [] as ResourcePath[];\n const range = IDBKeyRange.bound(\n [collectionId, ''],\n [immediateSuccessor(collectionId), ''],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return collectionParentsStore(transaction)\n .loadAll(range)\n .next(entries => {\n for (const entry of entries) {\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 (entry.collectionId !== collectionId) {\n break;\n }\n parentPaths.push(decode(entry.parent));\n }\n return parentPaths;\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */\nfunction collectionParentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbCollectionParentKey, DbCollectionParent> {\n return IndexedDbPersistence.getStore<\n DbCollectionParentKey,\n DbCollectionParent\n >(txn, DbCollectionParent.store);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n Document,\n MaybeDocument,\n NoDocument,\n UnknownDocument\n} from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport * as api from '../protos/firestore_proto_api';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { assert, fail } from '../util/assert';\n\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { Target } from '../core/target';\nimport { decode, encode, EncodedResourcePath } from './encoded_resource_path';\nimport {\n DbMutationBatch,\n DbNoDocument,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp,\n DbTimestampKey,\n DbUnknownDocument\n} from './indexeddb_schema';\nimport { SimpleDb } from './simple_db';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(private remoteSerializer: JsonProtoSerializer) {}\n\n /** Decodes a remote document from storage locally to a Document. */\n fromDbRemoteDocument(remoteDoc: DbRemoteDocument): MaybeDocument {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = this.fromDbTimestamp(remoteDoc.noDocument.readTime);\n return new NoDocument(key, version, {\n hasCommittedMutations: !!remoteDoc.hasCommittedMutations\n });\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = this.fromDbTimestamp(remoteDoc.unknownDocument.version);\n return new UnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n }\n\n /** Encodes a document for storage locally. */\n toDbRemoteDocument(\n maybeDoc: MaybeDocument,\n readTime: SnapshotVersion\n ): DbRemoteDocument {\n const dbReadTime = this.toDbTimestampKey(readTime);\n const parentPath = maybeDoc.key.path.popLast().toArray();\n if (maybeDoc instanceof Document) {\n const doc = maybeDoc.proto\n ? maybeDoc.proto\n : this.remoteSerializer.toDocument(maybeDoc);\n const hasCommittedMutations = maybeDoc.hasCommittedMutations;\n return new DbRemoteDocument(\n /* unknownDocument= */ null,\n /* noDocument= */ null,\n doc,\n hasCommittedMutations,\n dbReadTime,\n parentPath\n );\n } else if (maybeDoc instanceof NoDocument) {\n const path = maybeDoc.key.path.toArray();\n const readTime = this.toDbTimestamp(maybeDoc.version);\n const hasCommittedMutations = maybeDoc.hasCommittedMutations;\n return new DbRemoteDocument(\n /* unknownDocument= */ null,\n new DbNoDocument(path, readTime),\n /* document= */ null,\n hasCommittedMutations,\n dbReadTime,\n parentPath\n );\n } else if (maybeDoc instanceof UnknownDocument) {\n const path = maybeDoc.key.path.toArray();\n const readTime = this.toDbTimestamp(maybeDoc.version);\n return new DbRemoteDocument(\n new DbUnknownDocument(path, readTime),\n /* noDocument= */ null,\n /* document= */ null,\n /* hasCommittedMutations= */ true,\n dbReadTime,\n parentPath\n );\n } else {\n return fail('Unexpected MaybeDocument');\n }\n }\n\n toDbTimestampKey(snapshotVersion: SnapshotVersion): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n }\n\n fromDbTimestampKey(dbTimestampKey: DbTimestampKey): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n }\n\n private toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return new DbTimestamp(timestamp.seconds, timestamp.nanoseconds);\n }\n\n private fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(\n dbTimestamp.seconds,\n dbTimestamp.nanoseconds\n );\n return SnapshotVersion.fromTimestamp(timestamp);\n }\n\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n toDbMutationBatch(userId: string, batch: MutationBatch): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n this.remoteSerializer.toMutation(m)\n );\n const serializedMutations = batch.mutations.map(m =>\n this.remoteSerializer.toMutation(m)\n );\n return new DbMutationBatch(\n userId,\n batch.batchId,\n batch.localWriteTime.toMillis(),\n serializedBaseMutations,\n serializedMutations\n );\n }\n\n /** Decodes a DbMutationBatch into a MutationBatch */\n fromDbMutationBatch(dbBatch: DbMutationBatch): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n this.remoteSerializer.fromMutation(m)\n );\n const mutations = dbBatch.mutations.map(m =>\n this.remoteSerializer.fromMutation(m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n }\n\n /*\n * Encodes a set of document keys into an array of EncodedResourcePaths.\n */\n toDbResourcePaths(keys: DocumentKeySet): EncodedResourcePath[] {\n const encodedKeys: EncodedResourcePath[] = [];\n\n keys.forEach(key => {\n encodedKeys.push(encode(key.path));\n });\n\n return encodedKeys;\n }\n\n /** Decodes an array of EncodedResourcePaths into a set of document keys. */\n fromDbResourcePaths(encodedPaths: EncodedResourcePath[]): DocumentKeySet {\n let keys = documentKeySet();\n\n for (const documentKey of encodedPaths) {\n keys = keys.add(new DocumentKey(decode(documentKey)));\n }\n\n return keys;\n }\n\n /** Decodes a DbTarget into TargetData */\n fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = this.fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? this.fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.MIN;\n // TODO(b/140573486): Convert to platform representation\n const resumeToken = dbTarget.resumeToken;\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n } else {\n target = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n resumeToken\n );\n }\n\n /** Encodes TargetData into a DbTarget for storage locally. */\n toDbTarget(targetData: TargetData): DbTarget {\n assert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = this.toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = this.toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetData.target.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(targetData.target);\n } else {\n queryProto = this.remoteSerializer.toQueryTarget(targetData.target);\n }\n\n let resumeToken: string;\n\n if (targetData.resumeToken instanceof Uint8Array) {\n // TODO(b/78771403): Convert tokens to strings during deserialization\n assert(\n SimpleDb.isMockPersistence(),\n 'Persisting non-string stream tokens is only supported with mock persistence .'\n );\n resumeToken = targetData.resumeToken.toString();\n } else {\n resumeToken = targetData.resumeToken;\n }\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(\n targetData.targetId,\n targetData.target.canonicalId(),\n dbTimestamp,\n resumeToken,\n targetData.sequenceNumber,\n dbLastLimboFreeTimestamp,\n queryProto\n );\n }\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is api.DocumentsTarget {\n return (dbQuery as api.DocumentsTarget).documents !== undefined;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { User } from '../auth/user';\nimport { DatabaseInfo } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\nimport { Platform } from '../platform/platform';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { assert, fail } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { CancelablePromise } from '../util/promise';\n\nimport { decode, encode, EncodedResourcePath } from './encoded_resource_path';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport {\n IndexedDbMutationQueue,\n mutationQueuesContainKey\n} from './indexeddb_mutation_queue';\nimport { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n ALL_STORES,\n DbClientMetadata,\n DbClientMetadataKey,\n DbPrimaryClient,\n DbPrimaryClientKey,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION,\n SchemaConverter\n} from './indexeddb_schema';\nimport {\n documentTargetStore,\n getHighestListenSequenceNumber,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport {\n Persistence,\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG,\n PrimaryStateListener,\n ReferenceDelegate\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport { ClientId } from './shared_client_state';\nimport { TargetData } from './target_data';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\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 */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Another tab has exclusive access to the persistence layer. ' +\n 'To allow shared access, make sure to invoke ' +\n '`enablePersistence()` with `synchronizeTabs:true` in all tabs.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie_<persistence_prefix>_<instance_key>\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\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 * IndexedDbs “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 */\nexport class IndexedDbPersistence implements Persistence {\n static getStore<Key extends IDBValidKey, Value>(\n txn: PersistenceTransaction,\n store: string\n ): SimpleDbStore<Key, Value> {\n if (txn instanceof IndexedDbTransaction) {\n return SimpleDb.getStore<Key, Value>(txn.simpleDbTransaction, store);\n } else {\n throw fail(\n 'IndexedDbPersistence must use instances of IndexedDbTransaction'\n );\n }\n }\n\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n static MAIN_DATABASE = 'main';\n\n static async createIndexedDbPersistence(options: {\n allowTabSynchronization: boolean;\n persistenceKey: string;\n clientId: ClientId;\n platform: Platform;\n lruParams: LruParams;\n queue: AsyncQueue;\n serializer: JsonProtoSerializer;\n sequenceNumberSyncer: SequenceNumberSyncer;\n }): Promise<IndexedDbPersistence> {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n const persistence = new IndexedDbPersistence(\n options.allowTabSynchronization,\n options.persistenceKey,\n options.clientId,\n options.platform,\n options.lruParams,\n options.queue,\n options.serializer,\n options.sequenceNumberSyncer\n );\n await persistence.start();\n return persistence;\n }\n\n private readonly document: Document | null;\n private readonly window: Window;\n\n // Technically these types should be `| undefined` because they are\n // initialized asynchronously by start(), but that would be more misleading\n // than useful.\n private simpleDb!: SimpleDb;\n private listenSequence!: ListenSequence;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: CancelablePromise<void> | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly targetCache: IndexedDbTargetCache;\n private readonly indexManager: IndexedDbIndexManager;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly webStorage: Storage;\n readonly referenceDelegate: IndexedDbLruDelegate;\n\n private constructor(\n private readonly allowTabSynchronization: boolean,\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n platform: Platform,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer\n ) {\n this.referenceDelegate = new IndexedDbLruDelegate(this, lruParams);\n this.dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.document = platform.document;\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.indexManager = new IndexedDbIndexManager();\n this.remoteDocumentCache = new IndexedDbRemoteDocumentCache(\n this.serializer,\n this.indexManager\n );\n if (platform.window && platform.window.localStorage) {\n this.window = platform.window;\n this.webStorage = this.window.localStorage;\n } else {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @return {Promise<void>} Whether persistence was enabled.\n */\n private start(): Promise<void> {\n assert(!this.started, 'IndexedDbPersistence double-started!');\n assert(this.window !== null, \"Expected 'window' to be defined\");\n\n return SimpleDb.openOrCreate(\n this.dbName,\n SCHEMA_VERSION,\n new SchemaConverter(this.serializer)\n )\n .then(db => {\n this.simpleDb = db;\n // NOTE: This is expected to fail sometimes (in the case of another tab already\n // having the persistence lock), so it's the first thing we should do.\n return this.updateClientMetadataAndTryBecomePrimary();\n })\n .then(() => {\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.simpleDb.runTransaction(\n 'readonly-idempotent',\n [DbTargetGlobal.store],\n txn => getHighestListenSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise<void> {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise<void>\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\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 */\n private updateClientMetadataAndTryBecomePrimary(): Promise<void> {\n return this.simpleDb\n .runTransaction('readwrite-idempotent', ALL_STORES, txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put(\n new DbClientMetadata(\n this.clientId,\n Date.now(),\n this.networkEnabled,\n this.inForeground\n )\n )\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueAndForget(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n })\n .catch(e => {\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n log.debug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueAndForget(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: SimpleDbTransaction\n ): PersistencePromise<boolean> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\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 */\n private async maybeGarbageCollectMultiClientState(): Promise<void> {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary-idempotent',\n txn => {\n const metadataStore = IndexedDbPersistence.getStore<\n DbClientMetadataKey,\n DbClientMetadata\n >(txn, DbClientMetadata.store);\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n );\n\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 inactiveClients.forEach(inactiveClient => {\n this.window.localStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n });\n }\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 */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\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 */\n private canActAsPrimary(\n txn: SimpleDbTransaction\n ): PersistencePromise<boolean> {\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClient.key)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\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 if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.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 //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n log.debug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise<void> {\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._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n await this.simpleDb.runTransaction(\n 'readwrite-idempotent',\n [DbPrimaryClient.store, DbClientMetadata.store],\n txn => {\n return this.releasePrimaryLeaseIfHeld(txn).next(() =>\n this.removeClientMetadata(txn)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n getActiveClients(): Promise<ClientId[]> {\n return this.simpleDb.runTransaction(\n 'readonly-idempotent',\n [DbClientMetadata.store],\n txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n }\n );\n }\n\n static async clearPersistence(persistenceKey: string): Promise<void> {\n if (!IndexedDbPersistence.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getMutationQueue(user: User): MutationQueue {\n assert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n this.indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n assert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n assert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(): IndexedDbIndexManager {\n assert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return this.indexManager;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n log.debug(LOG_TAG, 'Starting transaction:', action);\n\n // TODO(schmidt-sebastian): Simplify once all transactions are idempotent.\n const idempotent = mode.endsWith('idempotent');\n const readonly = mode.startsWith('readonly');\n const simpleDbMode = readonly\n ? idempotent\n ? 'readonly-idempotent'\n : 'readonly'\n : idempotent\n ? 'readwrite-idempotent'\n : 'readwrite';\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(simpleDbMode, ALL_STORES, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence.next()\n );\n\n if (\n mode === 'readwrite-primary' ||\n mode === 'readwrite-primary-idempotent'\n ) {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(simpleDbTxn)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(simpleDbTxn);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n log.error(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueAndForget(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(simpleDbTxn).next(\n () => result\n );\n });\n } else {\n return this.verifyAllowTabSynchronization(simpleDbTxn).next(() =>\n transactionOperation(persistenceTransaction)\n );\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\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 private verifyAllowTabSynchronization(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\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 */\n private acquireOrExtendPrimaryLease(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const newPrimary = new DbPrimaryClient(\n this.clientId,\n this.allowTabSynchronization,\n Date.now()\n );\n return primaryClientStore(txn).put(DbPrimaryClient.key, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n static buildStoragePrefix(databaseInfo: DatabaseInfo): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n log.debug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClient.key);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n log.error(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n assert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\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 */\n private attachWindowUnloadHook(): void {\n if (typeof this.window.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\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.markClientZombied();\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('unload', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n assert(\n typeof this.window.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\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 */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage.getItem(this.zombiedClientLocalStorageKey(clientId)) !==\n null;\n log.debug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n log.error(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\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 */\n private markClientZombied(): void {\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: SimpleDbTransaction\n): SimpleDbStore<DbPrimaryClientKey, DbPrimaryClient> {\n return txn.store<DbPrimaryClientKey, DbPrimaryClient>(DbPrimaryClient.store);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: SimpleDbTransaction\n): SimpleDbStore<DbClientMetadataKey, DbClientMetadata> {\n return txn.store<DbClientMetadataKey, DbClientMetadata>(\n DbClientMetadata.store\n );\n}\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegate implements ReferenceDelegate, LruDelegate {\n private inMemoryPins: ReferenceSet | null = null;\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: IndexedDbPersistence, params: LruParams) {\n this.garbageCollector = new LruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocmentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocmentCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n setInMemoryPins(inMemoryPins: ReferenceSet): void {\n this.inMemoryPins = inMemoryPins;\n }\n\n addReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.db\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeMutationReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\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 */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise<boolean> {\n if (this.inMemoryPins!.containsKey(docKey)) {\n return PersistencePromise.resolve<boolean>(true);\n } else {\n return mutationQueuesContainKey(txn, docKey);\n }\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array<PersistencePromise<void>> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey);\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\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 */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocument.documentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\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 if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decode(nextPath)), nextToReport);\n }\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 nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\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 nextToReport = ListenSequence.INVALID;\n }\n }\n )\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 if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decode(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encode(key.path)];\n}\n\n/**\n * @return A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return new DbTargetDocument(0, encode(key.path), sequenceNumber);\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise<void> {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { QueryEngine } from './query_engine';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { Query, LimitType } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentMap,\n MaybeDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { assert } from '../util/assert';\nimport { debug, getLogLevel, LogLevel } from '../util/log';\nimport { SortedSet } from '../util/sorted_set';\n\n// TOOD(b/140938512): Drop SimpleQueryEngine and rename IndexFreeQueryEngine.\n\n/**\n * A query engine that takes advantage of the target document mapping in the\n * QueryCache. The IndexFreeQueryEngine optimizes query execution by only\n * reading the documents that previously matched a query plus any documents that were\n * edited after the query was last listened to.\n *\n * There are some cases where Index-Free queries are not guaranteed to produce\n * the same results as full collection scans. In these cases, the\n * IndexFreeQueryEngine falls back to full query processing. 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 */\nexport class IndexFreeQueryEngine implements QueryEngine {\n private localDocumentsView: LocalDocumentsView | undefined;\n\n setLocalDocumentsView(localDocuments: LocalDocumentsView): void {\n this.localDocumentsView = localDocuments;\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n assert(\n this.localDocumentsView !== undefined,\n 'setLocalDocumentsView() not called'\n );\n\n // Queries that match all documents don't benefit from using\n // IndexFreeQueries. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n if (query.matchesAllDocuments()) {\n return this.executeFullCollectionScan(transaction, query);\n }\n\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.MIN)) {\n return this.executeFullCollectionScan(transaction, query);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n (query.hasLimitToFirst() || query.hasLimitToLast()) &&\n this.needsRefill(\n query.limitType,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return this.executeFullCollectionScan(transaction, query);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n debug(\n 'IndexFreeQueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n query.toString()\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n lastLimboFreeSnapshotVersion\n ).next(updatedResults => {\n // We merge `previousResults` into `updateResults`, since\n // `updateResults` is already a DocumentMap. If a document is\n // contained in both lists, then its contents are the same.\n previousResults.forEach(doc => {\n updatedResults = updatedResults.insert(doc.key, doc);\n });\n return updatedResults;\n });\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: MaybeDocumentMap\n ): SortedSet<Document> {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let queryResults = new SortedSet<Document>((d1, d2) =>\n query.docComparator(d1, d2)\n );\n documents.forEach((_, maybeDoc) => {\n if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n queryResults = queryResults.add(maybeDoc);\n }\n });\n return queryResults;\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 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 query\n * was last synchronized.\n */\n private needsRefill(\n limitType: LimitType,\n sortedPreviousResults: SortedSet<Document>,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n if (remoteKeys.size !== sortedPreviousResults.size) {\n return true;\n }\n\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 docAtLimitEdge =\n limitType === LimitType.First\n ? sortedPreviousResults.last()\n : sortedPreviousResults.first();\n if (!docAtLimitEdge) {\n // We don't need to refill the query if there were already no documents.\n return false;\n }\n return (\n docAtLimitEdge.hasPendingWrites ||\n docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0\n );\n }\n\n private executeFullCollectionScan(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<DocumentMap> {\n if (getLogLevel() <= LogLevel.DEBUG) {\n debug(\n 'IndexFreeQueryEngine',\n 'Using full collection scan to execute query: %s',\n query.toString()\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n SnapshotVersion.MIN\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Timestamp } from '../api/timestamp';\nimport { Query } from '../core/query';\nimport { BatchId, ProtoByteString } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch, BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { PersistenceTransaction, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { DocReference } from './reference_set';\n\nexport class MemoryMutationQueue implements MutationQueue {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationBatch[] = [];\n\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n private nextBatchId: BatchId = 1;\n\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n private lastStreamToken: ProtoByteString = emptyByteString();\n\n /** An ordered mapping between documents and the mutations batch IDs. */\n private batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n\n constructor(\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n }\n\n acknowledgeBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch,\n streamToken: ProtoByteString\n ): PersistencePromise<void> {\n const batchId = batch.batchId;\n const batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n assert(\n batchIndex === 0,\n 'Can only acknowledge the first batch in the mutation queue'\n );\n\n // Verify that the batch in the queue is the one to be acknowledged.\n const check = this.mutationQueue[batchIndex];\n assert(\n batchId === check.batchId,\n 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId\n );\n\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n }\n\n getLastStreamToken(\n transaction: PersistenceTransaction\n ): PersistencePromise<ProtoByteString> {\n return PersistencePromise.resolve(this.lastStreamToken);\n }\n\n setLastStreamToken(\n transaction: PersistenceTransaction,\n streamToken: ProtoByteString\n ): PersistencePromise<void> {\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n const batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n const prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(\n prior.batchId < batchId,\n 'Mutation batchIDs must be monotonically increasing order'\n );\n }\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n this.mutationQueue.push(batch);\n\n // Track references by document key and index collection parents.\n for (const mutation of mutations) {\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n new DocReference(mutation.key, batchId)\n );\n\n this.indexManager.addToCollectionParentIndex(\n transaction,\n mutation.key.path.popLast()\n );\n }\n\n return PersistencePromise.resolve(batch);\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<DocumentKeySet | null> {\n const mutationBatch = this.findMutationBatch(batchId);\n assert(mutationBatch != null, 'Failed to find local mutation batch.');\n return PersistencePromise.resolve<DocumentKeySet | null>(\n mutationBatch.keys()\n );\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n const nextBatchId = batchId + 1;\n\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n const rawIndex = this.indexOfBatchId(nextBatchId);\n const index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(\n this.mutationQueue.length > index ? this.mutationQueue[index] : null\n );\n }\n\n getHighestUnacknowledgedBatchId(): PersistencePromise<BatchId> {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise<MutationBatch[]> {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutationBatch[]> {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n const result: MutationBatch[] = [];\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n assert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n assert(\n batch !== null,\n 'Batches in the index must exist in the main table'\n );\n result.push(batch!);\n });\n\n return PersistencePromise.resolve(result);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap<DocumentKey, unknown>\n ): PersistencePromise<MutationBatch[]> {\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n documentKeys.forEach(documentKey => {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n assert(\n documentKey.isEqual(ref.key),\n \"For each key, should only iterate over a single key's batches\"\n );\n\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<MutationBatch[]> {\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const prefix = query.path;\n const immediateChildrenPathLength = prefix.length + 1;\n\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 startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n const start = new DocReference(new DocumentKey(startPath), 0);\n\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n this.batchesByDocumentKey.forEachWhile(ref => {\n const rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n } else {\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 if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n private findMutationBatches(batchIDs: SortedSet<number>): MutationBatch[] {\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 result: MutationBatch[] = [];\n batchIDs.forEach(batchId => {\n const batch = this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise<void> {\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n assert(\n batchIndex === 0,\n 'Can only remove the first entry of the mutation queue'\n );\n this.mutationQueue.shift();\n\n let references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, (mutation: Mutation) => {\n const ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return this.referenceDelegate.removeMutationReference(\n transaction,\n mutation.key\n );\n }).next(() => {\n this.batchesByDocumentKey = references;\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n const ref = new DocReference(key, 0);\n const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n if (this.mutationQueue.length === 0) {\n assert(\n this.batchesByDocumentKey.isEmpty(),\n 'Document leak -- detected dangling mutation references when queue is empty.'\n );\n }\n return PersistencePromise.resolve();\n }\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 */\n private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n const index = this.indexOfBatchId(batchId);\n assert(\n index >= 0 && index < this.mutationQueue.length,\n 'Batches must exist to be ' + action\n );\n return index;\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return 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 */\n private indexOfBatchId(batchId: BatchId): number {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n\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 const firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n }\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 */\n private findMutationBatch(batchId: BatchId): MutationBatch | null {\n const index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n const batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { IndexFreeQueryEngine } from '../local/index_free_query_engine';\nimport { LocalStore } from '../local/local_store';\nimport { MemoryPersistence } from '../local/memory_persistence';\nimport { Persistence } from '../local/persistence';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Platform } from '../platform/platform';\nimport { Datastore } from '../remote/datastore';\nimport { RemoteStore } from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug } from '../util/log';\nimport { Deferred } from '../util/promise';\nimport {\n EventManager,\n ListenOptions,\n Observer,\n QueryListener\n} from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport { View } from './view';\n\nimport {\n LruGarbageCollector,\n LruParams,\n LruScheduler\n} from '../local/lru_garbage_collector';\nimport {\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { AutoId } from '../util/misc';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport { Query } from './query';\nimport { Transaction } from './transaction';\nimport { OnlineState, OnlineStateSource } from './types';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\nexport class IndexedDbPersistenceSettings {\n constructor(\n readonly cacheSizeBytes: number,\n readonly synchronizeTabs: boolean\n ) {}\n\n lruParams(): LruParams {\n return LruParams.withCacheSize(this.cacheSizeBytes);\n }\n}\n\nexport class MemoryPersistenceSettings {}\n\nexport type InternalPersistenceSettings =\n | IndexedDbPersistenceSettings\n | MemoryPersistenceSettings;\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 */\nexport class FirestoreClient {\n // NOTE: These should technically have '|undefined' in the types, since\n // they're initialized asynchronously rather than in the constructor, but\n // given that all work is done on the async queue and we assert that\n // initialization completes before any other work is queued, we're cheating\n // with the types rather than littering the code with '!' or unnecessary\n // undefined checks.\n private eventMgr!: EventManager;\n private persistence!: Persistence;\n private localStore!: LocalStore;\n private remoteStore!: RemoteStore;\n private syncEngine!: SyncEngine;\n // PORTING NOTE: SharedClientState is only used for multi-tab web.\n private sharedClientState!: SharedClientState;\n\n private lruScheduler?: LruScheduler;\n\n private readonly clientId = AutoId.newId();\n\n constructor(\n private platform: Platform,\n private databaseInfo: DatabaseInfo,\n private credentials: CredentialsProvider,\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 private asyncQueue: AsyncQueue\n ) {}\n\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param persistenceSettings Settings object to configure offline\n * persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n start(persistenceSettings: InternalPersistenceSettings): Promise<void> {\n this.verifyNotTerminated();\n // We defer our initialization until we get the current user from\n // setChangeListener(). We block the async queue until we got the initial\n // user and the initialization is completed. This will prevent any scheduled\n // work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n const initializationDone = new Deferred<void>();\n\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n const persistenceResult = new Deferred<void>();\n\n let initialized = false;\n this.credentials.setChangeListener(user => {\n if (!initialized) {\n initialized = true;\n\n this.initializePersistence(persistenceSettings, persistenceResult, user)\n .then(maybeLruGc => this.initializeRest(user, maybeLruGc))\n .then(initializationDone.resolve, initializationDone.reject);\n } else {\n this.asyncQueue.enqueueAndForget(() => {\n return this.handleCredentialChange(user);\n });\n }\n });\n\n // Block the async queue until initialization is done\n this.asyncQueue.enqueueAndForget(() => {\n return initializationDone.promise;\n });\n\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n }\n\n /** Enables the network connection and requeues all pending operations. */\n enableNetwork(): Promise<void> {\n this.verifyNotTerminated();\n return this.asyncQueue.enqueue(() => {\n return this.syncEngine.enableNetwork();\n });\n }\n\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param persistenceSettings Settings object to configure offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n private initializePersistence(\n persistenceSettings: InternalPersistenceSettings,\n persistenceResult: Deferred<void>,\n user: User\n ): Promise<LruGarbageCollector | null> {\n if (persistenceSettings instanceof IndexedDbPersistenceSettings) {\n return this.startIndexedDbPersistence(user, persistenceSettings)\n .then(maybeLruGc => {\n persistenceResult.resolve();\n return maybeLruGc;\n })\n .catch(error => {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n\n // An unknown failure on the first stage shuts everything down.\n if (!this.canFallback(error)) {\n throw error;\n }\n console.warn(\n 'Error enabling offline persistence. Falling back to' +\n ' persistence disabled: ' +\n error\n );\n return this.startMemoryPersistence();\n });\n } else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n }\n\n /**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\n private canFallback(error: FirestoreError | DOMException): boolean {\n if (error instanceof FirestoreError) {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\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 return (\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 error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n }\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 */\n private verifyNotTerminated(): void {\n if (this.asyncQueue.isShuttingDown) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n private startIndexedDbPersistence(\n user: User,\n settings: IndexedDbPersistenceSettings\n ): Promise<LruGarbageCollector> {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n const persistenceKey = IndexedDbPersistence.buildStoragePrefix(\n this.databaseInfo\n );\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n const serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n\n return Promise.resolve().then(async () => {\n if (\n settings.synchronizeTabs &&\n !WebStorageSharedClientState.isAvailable(this.platform)\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n\n const lruParams = settings.lruParams();\n\n this.sharedClientState = settings.synchronizeTabs\n ? new WebStorageSharedClientState(\n this.asyncQueue,\n this.platform,\n persistenceKey,\n this.clientId,\n user\n )\n : new MemorySharedClientState();\n\n const persistence = await IndexedDbPersistence.createIndexedDbPersistence(\n {\n allowTabSynchronization: settings.synchronizeTabs,\n persistenceKey,\n clientId: this.clientId,\n platform: this.platform,\n queue: this.asyncQueue,\n serializer,\n lruParams,\n sequenceNumberSyncer: this.sharedClientState\n }\n );\n\n this.persistence = persistence;\n return persistence.referenceDelegate.garbageCollector;\n });\n }\n\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n private startMemoryPersistence(): Promise<LruGarbageCollector | null> {\n this.persistence = MemoryPersistence.createEagerPersistence(this.clientId);\n this.sharedClientState = new MemorySharedClientState();\n return Promise.resolve(null);\n }\n\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n private initializeRest(\n user: User,\n maybeLruGc: LruGarbageCollector | null\n ): Promise<void> {\n debug(LOG_TAG, 'Initializing. user=', user.uid);\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(async connection => {\n const queryEngine = new IndexFreeQueryEngine();\n this.localStore = new LocalStore(this.persistence, queryEngine, user);\n await this.localStore.start();\n\n if (maybeLruGc) {\n // We're running LRU Garbage collection. Set up the scheduler.\n this.lruScheduler = new LruScheduler(\n maybeLruGc,\n this.asyncQueue,\n this.localStore\n );\n }\n\n const connectivityMonitor = this.platform.newConnectivityMonitor();\n const serializer = this.platform.newSerializer(\n this.databaseInfo.databaseId\n );\n const datastore = new Datastore(\n this.asyncQueue,\n connection,\n this.credentials,\n serializer\n );\n\n const remoteStoreOnlineStateChangedHandler = (\n onlineState: OnlineState\n ): void =>\n this.syncEngine.applyOnlineStateChange(\n onlineState,\n OnlineStateSource.RemoteStore\n );\n const sharedClientStateOnlineStateChangedHandler = (\n onlineState: OnlineState\n ): void =>\n this.syncEngine.applyOnlineStateChange(\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore = new RemoteStore(\n this.localStore,\n datastore,\n this.asyncQueue,\n remoteStoreOnlineStateChangedHandler,\n connectivityMonitor\n );\n\n this.syncEngine = new SyncEngine(\n this.localStore,\n this.remoteStore,\n this.sharedClientState,\n user\n );\n\n this.sharedClientState.onlineStateHandler = sharedClientStateOnlineStateChangedHandler;\n\n // Set up wiring between sync engine and other components\n this.remoteStore.syncEngine = this.syncEngine;\n this.sharedClientState.syncEngine = this.syncEngine;\n\n this.eventMgr = new EventManager(this.syncEngine);\n\n // PORTING NOTE: LocalStore doesn't need an explicit start() on the Web.\n await this.sharedClientState.start();\n await this.remoteStore.start();\n\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.setPrimaryStateListener(async isPrimary => {\n await this.syncEngine.applyPrimaryState(isPrimary);\n if (this.lruScheduler) {\n if (isPrimary && !this.lruScheduler.started) {\n this.lruScheduler.start();\n } else if (!isPrimary) {\n this.lruScheduler.stop();\n }\n }\n });\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 await this.persistence.setDatabaseDeletedListener(async () => {\n await this.terminate();\n });\n });\n }\n\n private handleCredentialChange(user: User): Promise<void> {\n this.asyncQueue.verifyOperationInProgress();\n\n debug(LOG_TAG, 'Credential Changed. Current user: ' + user.uid);\n return this.syncEngine.handleCredentialChange(user);\n }\n\n /** Disables the network connection. Pending operations will not complete. */\n disableNetwork(): Promise<void> {\n this.verifyNotTerminated();\n return this.asyncQueue.enqueue(() => {\n return this.syncEngine.disableNetwork();\n });\n }\n\n terminate(): Promise<void> {\n return this.asyncQueue.enqueueAndInitiateShutdown(async () => {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n if (this.lruScheduler) {\n this.lruScheduler.stop();\n }\n await this.remoteStore.shutdown();\n await this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n\n // `removeChangeListener` must be called after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving\n // auth tokens.\n this.credentials.removeChangeListener();\n });\n }\n\n /**\n * Returns a Promise that resolves when all writes that were pending at the time this\n * method was called received server acknowledgement. An acknowledgement can be either acceptance\n * or rejection.\n */\n waitForPendingWrites(): Promise<void> {\n this.verifyNotTerminated();\n\n const deferred = new Deferred<void>();\n this.asyncQueue.enqueueAndForget(() => {\n return this.syncEngine.registerPendingWritesCallback(deferred);\n });\n return deferred.promise;\n }\n\n listen(\n query: Query,\n observer: Observer<ViewSnapshot>,\n options: ListenOptions\n ): QueryListener {\n this.verifyNotTerminated();\n const listener = new QueryListener(query, observer, options);\n this.asyncQueue.enqueueAndForget(() => {\n return this.eventMgr.listen(listener);\n });\n return listener;\n }\n\n unlisten(listener: QueryListener): void {\n // Checks for termination but does not raise error, allowing unlisten after\n // termination to be a no-op.\n if (this.clientTerminated) {\n return;\n }\n this.asyncQueue.enqueueAndForget(() => {\n return this.eventMgr.unlisten(listener);\n });\n }\n\n getDocumentFromLocalCache(docKey: DocumentKey): Promise<Document | null> {\n this.verifyNotTerminated();\n return this.asyncQueue\n .enqueue(() => {\n return this.localStore.readDocument(docKey);\n })\n .then((maybeDoc: MaybeDocument | null) => {\n if (maybeDoc instanceof Document) {\n return maybeDoc;\n } else if (maybeDoc instanceof NoDocument) {\n return null;\n } else {\n throw new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from cache. (However, this document may ' +\n \"exist on the server. Run again without setting 'source' in \" +\n 'the GetOptions to attempt to retrieve the document from the ' +\n 'server.)'\n );\n }\n });\n }\n\n getDocumentsFromLocalCache(query: Query): Promise<ViewSnapshot> {\n this.verifyNotTerminated();\n return this.asyncQueue.enqueue(async () => {\n const queryResult = await this.localStore.executeQuery(\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n return view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ false\n ).snapshot!;\n });\n }\n\n write(mutations: Mutation[]): Promise<void> {\n this.verifyNotTerminated();\n const deferred = new Deferred<void>();\n this.asyncQueue.enqueueAndForget(() =>\n this.syncEngine.write(mutations, deferred)\n );\n return deferred.promise;\n }\n\n databaseId(): DatabaseId {\n return this.databaseInfo.databaseId;\n }\n\n addSnapshotsInSyncListener(observer: Observer<void>): void {\n this.verifyNotTerminated();\n this.asyncQueue.enqueueAndForget(() => {\n this.eventMgr.addSnapshotsInSyncListener(observer);\n return Promise.resolve();\n });\n }\n\n removeSnapshotsInSyncListener(observer: Observer<void>): void {\n // Checks for shutdown but does not raise error, allowing remove after\n // shutdown to be a no-op.\n if (this.clientTerminated) {\n return;\n }\n this.eventMgr.removeSnapshotsInSyncListener(observer);\n }\n\n get clientTerminated(): boolean {\n // Technically, the asyncQueue is still running, but only accepting operations\n // related to termination or supposed to be run after termination. It is effectively\n // terminated to the eyes of users.\n return this.asyncQueue.isShuttingDown;\n }\n\n transaction<T>(\n updateFunction: (transaction: Transaction) => Promise<T>\n ): Promise<T> {\n this.verifyNotTerminated();\n const deferred = new Deferred<T>();\n this.asyncQueue.enqueueAndForget(() => {\n this.syncEngine.runTransaction(this.asyncQueue, updateFunction, deferred);\n return Promise.resolve();\n });\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Query } from '../core/query';\nimport {\n DocumentKeySet,\n DocumentMap,\n documentMap,\n DocumentSizeEntry,\n MaybeDocumentMap,\n NullableMaybeDocumentMap,\n nullableMaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nimport { IndexManager } from './index_manager';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: MaybeDocument) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry extends DocumentSizeEntry {\n readTime: SnapshotVersion;\n}\n\ntype DocumentEntryMap = SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>(\n DocumentKey.comparator\n );\n}\n\nexport class MemoryRemoteDocumentCache implements RemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n\n /** Size of all cached documents. */\n private size = 0;\n\n /**\n * @param sizer Used to assess the size of a document. For eager GC, this is expected to just\n * return 0 to avoid unnecessarily doing the work of calculating the size.\n */\n constructor(\n private readonly indexManager: IndexManager,\n private readonly sizer: DocumentSizer\n ) {}\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 */\n private addEntry(\n transaction: PersistenceTransaction,\n doc: MaybeDocument,\n readTime: SnapshotVersion\n ): PersistencePromise<void> {\n assert(\n !readTime.isEqual(SnapshotVersion.MIN),\n 'Cannot add a document with a read time of zero'\n );\n\n const key = doc.key;\n const entry = this.docs.get(key);\n const previousSize = entry ? entry.size : 0;\n const currentSize = this.sizer(doc);\n\n this.docs = this.docs.insert(key, {\n maybeDocument: doc,\n size: currentSize,\n readTime\n });\n\n this.size += currentSize - previousSize;\n\n return this.indexManager.addToCollectionParentIndex(\n transaction,\n key.path.popLast()\n );\n }\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 */\n private removeEntry(documentKey: DocumentKey): void {\n const entry = this.docs.get(documentKey);\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n }\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(entry ? entry.maybeDocument : null);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n let results = nullableMaybeDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(documentKey, entry ? entry.maybeDocument : null);\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n let results = documentMap();\n\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 prefix = new DocumentKey(query.path.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { maybeDocument, readTime }\n } = iterator.getNext();\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (readTime.compareTo(sinceReadTime) <= 0) {\n continue;\n }\n if (maybeDocument instanceof Document && query.matches(maybeDocument)) {\n results = results.insert(maybeDocument.key, maybeDocument);\n }\n }\n return PersistencePromise.resolve(results);\n }\n\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n }\n\n getNewDocumentChanges(\n transaction: PersistenceTransaction,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<{\n changedDocs: MaybeDocumentMap;\n readTime: SnapshotVersion;\n }> {\n throw new Error(\n 'getNewDocumentChanges() is not supported with MemoryPersistence'\n );\n }\n\n getLastReadTime(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return PersistencePromise.resolve(SnapshotVersion.MIN);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new MemoryRemoteDocumentCache.RemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return PersistencePromise.resolve(this.size);\n }\n\n /**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\n private static RemoteDocumentChangeBuffer = class extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCache) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n this.changes.forEach((key, doc) => {\n if (doc) {\n promises.push(\n this.documentCache.addEntry(transaction, doc, this.readTime)\n );\n } else {\n this.documentCache.removeEntry(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n };\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { MemoryPersistence } from './memory_persistence';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\nimport { Target } from '../core/target';\n\nexport class MemoryTargetCache implements TargetCache {\n /**\n * Maps a target to the data about that target\n */\n private targets = new ObjectMap<Target, TargetData>(t => t.canonicalId());\n\n /** The last received snapshot version. */\n private lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n private highestTargetId: TargetId = 0;\n /** The highest sequence number encountered. */\n private highestSequenceNumber: ListenSequenceNumber = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n private references = new ReferenceSet();\n\n private targetCount = 0;\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n constructor(private readonly persistence: MemoryPersistence) {}\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<ListenSequenceNumber> {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n const nextTargetId = this.targetIdGenerator.after(this.highestTargetId);\n this.highestTargetId = nextTargetId;\n return PersistencePromise.resolve(nextTargetId);\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise<void> {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n return PersistencePromise.resolve();\n }\n\n private saveTargetData(targetData: TargetData): void {\n this.targets.set(targetData.target, targetData);\n const targetId = targetData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n if (targetData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = targetData.sequenceNumber;\n }\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n assert(\n !this.targets.has(targetData.target),\n 'Adding a target that already exists'\n );\n this.saveTargetData(targetData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n assert(\n this.targets.has(targetData.target),\n 'Updating a non-existent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\n assert(\n this.targets.has(targetData.target),\n 'Removing a non-existent target from the cache'\n );\n this.targets.delete(targetData.target);\n this.references.removeReferencesForId(targetData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n }\n\n removeTargets(\n transaction: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n let count = 0;\n const removals: Array<PersistencePromise<void>> = [];\n this.targets.forEach((key, targetData) => {\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n this.targets.delete(key);\n removals.push(\n this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n );\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(() => count);\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n const targetData = this.targets.get(target) || null;\n return PersistencePromise.resolve(targetData);\n }\n\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): never {\n // This method is only needed for multi-tab and we can't implement it\n // efficiently without additional data structures.\n return fail('Not yet implemented.');\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.addReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array<PersistencePromise<void>> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.addReference(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array<PersistencePromise<void>> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.removeReference(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<DocumentKeySet> {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.references.containsKey(key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { User } from '../auth/user';\nimport { Document, MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { debug } from '../util/log';\nimport * as obj from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { encode } from './encoded_resource_path';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\n\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport { MemoryRemoteDocumentCache } from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport {\n Persistence,\n PersistenceTransaction,\n PersistenceTransactionMode,\n PrimaryStateListener,\n ReferenceDelegate\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport { ClientId } from './shared_client_state';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\n\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nexport class MemoryPersistence implements Persistence {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n private readonly indexManager: MemoryIndexManager;\n private mutationQueues: { [user: string]: MemoryMutationQueue } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly listenSequence = new ListenSequence(0);\n\n private _started = false;\n\n readonly referenceDelegate: MemoryLruDelegate | MemoryEagerDelegate;\n\n static createLruPersistence(\n clientId: ClientId,\n params: LruParams\n ): MemoryPersistence {\n const factory = (p: MemoryPersistence): MemoryLruDelegate =>\n new MemoryLruDelegate(p, params);\n return new MemoryPersistence(clientId, factory);\n }\n\n static createEagerPersistence(clientId: ClientId): MemoryPersistence {\n const factory = (p: MemoryPersistence): MemoryEagerDelegate =>\n new MemoryEagerDelegate(p);\n return new MemoryPersistence(clientId, factory);\n }\n\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 private constructor(\n private readonly clientId: ClientId,\n referenceDelegateFactory: (\n p: MemoryPersistence\n ) => MemoryLruDelegate | MemoryEagerDelegate\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: MaybeDocument): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = new MemoryRemoteDocumentCache(\n this.indexManager,\n sizer\n );\n }\n\n shutdown(): Promise<void> {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n }\n\n get started(): boolean {\n return this._started;\n }\n\n async getActiveClients(): Promise<ClientId[]> {\n return [this.clientId];\n }\n\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise<void> {\n // All clients using memory persistence act as primary.\n return primaryStateListener(true);\n }\n\n setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(networkEnabled: boolean): void {\n // No op.\n }\n\n getIndexManager(): MemoryIndexManager {\n return this.indexManager;\n }\n\n getMutationQueue(user: User): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(\n this.indexManager,\n this.referenceDelegate\n );\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n }\n\n getTargetCache(): MemoryTargetCache {\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): MemoryRemoteDocumentCache {\n return this.remoteDocumentCache;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n debug(LOG_TAG, 'Starting transaction:', action);\n const txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn)\n .next(result => {\n return this.referenceDelegate\n .onTransactionCommitted(txn)\n .next(() => result);\n })\n .toPromise()\n .then(result => {\n txn.raiseOnCommittedEvent();\n return result;\n });\n }\n\n mutationQueuesContainKey(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or(\n obj\n .values(this.mutationQueues)\n .map(queue => () => queue.containsKey(transaction, key))\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport class MemoryEagerDelegate implements ReferenceDelegate {\n private inMemoryPins: ReferenceSet | null = null;\n private _orphanedDocuments: Set<DocumentKey> | null = null;\n\n constructor(private readonly persistence: MemoryPersistence) {}\n\n private get orphanedDocuments(): Set<DocumentKey> {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n setInMemoryPins(inMemoryPins: ReferenceSet): void {\n this.inMemoryPins = inMemoryPins;\n }\n\n addReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.delete(key);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key);\n return PersistencePromise.resolve();\n }\n\n removeMutationReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const cache = this.persistence.getTargetCache();\n return cache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(keys => {\n keys.forEach(key => this.orphanedDocuments.add(key));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set<DocumentKey>();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n // Remove newly orphaned documents.\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n return PersistencePromise.forEach(\n this.orphanedDocuments,\n (key: DocumentKey) => {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key);\n }\n });\n }\n ).next(() => {\n this._orphanedDocuments = null;\n return changeBuffer.apply(txn);\n });\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (isReferenced) {\n this.orphanedDocuments.delete(key);\n } else {\n this.orphanedDocuments.add(key);\n }\n });\n }\n\n documentSize(doc: MaybeDocument): number {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n\n private isReferenced(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => PersistencePromise.resolve(this.inMemoryPins!.containsKey(key))\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private inMemoryPins: ReferenceSet | null = null;\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(k => encode(k.path));\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = new LruGarbageCollector(this, lruParams);\n }\n\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n onTransactionStarted(): void {}\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.persistence\n .getTargetCache()\n .getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.orphanedSequenceNumbers,\n (key, sequenceNumber) => {\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n // being too recent.\n return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n );\n }\n\n setInMemoryPins(inMemoryPins: ReferenceSet): void {\n this.inMemoryPins = inMemoryPins;\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n let count = 0;\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n const p = cache.forEachDocumentKey(txn, key => {\n return this.isPinned(txn, key, upperBound).next(isPinned => {\n if (!isPinned) {\n count++;\n changeBuffer.removeEntry(key);\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n removeMutationReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(txn, updated);\n }\n\n addReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n documentSize(maybeDoc: MaybeDocument): number {\n let documentSize = maybeDoc.key.toString().length;\n if (maybeDoc instanceof Document) {\n documentSize += maybeDoc.data().approximateByteSize();\n }\n return documentSize;\n }\n\n private isPinned(\n txn: PersistenceTransaction,\n key: DocumentKey,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => PersistencePromise.resolve(this.inMemoryPins!.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => {\n const orphanedAt = this.orphanedSequenceNumbers.get(key);\n return PersistencePromise.resolve(\n orphanedAt !== undefined && orphanedAt > upperBound\n );\n }\n ]);\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { Observer } from '../core/event_manager';\nimport { EventHandler } from './misc';\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 */\nexport class AsyncObserver<T> implements Observer<T> {\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n private muted = false;\n\n constructor(private observer: Observer<T>) {}\n\n next(value: T): void {\n this.scheduleEvent(this.observer.next, value);\n }\n\n error(error: Error): void {\n this.scheduleEvent(this.observer.error, error);\n }\n\n mute(): void {\n this.muted = true;\n }\n\n private scheduleEvent<E>(eventHandler: EventHandler<E>, event: E): void {\n if (!this.muted) {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { JsonObject } from '../model/field_value';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error) => 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 interface Unsubscribe {\n (): void;\n}\n\nexport function isPartialObserver(obj: unknown): boolean {\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 JsonObject<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 Inc.\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 * as firestore from '@firebase/firestore-types';\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService, _FirebaseApp } from '@firebase/app-types/private';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { ListenOptions } from '../core/event_manager';\nimport {\n FirestoreClient,\n IndexedDbPersistenceSettings,\n InternalPersistenceSettings,\n MemoryPersistenceSettings\n} from '../core/firestore_client';\nimport {\n Bound,\n Direction,\n FieldFilter,\n Filter,\n Operator,\n OrderBy,\n Query as InternalQuery\n} from '../core/query';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n ArrayValue,\n FieldValue,\n FieldValueOptions,\n ObjectValue,\n RefValue,\n ServerTimestampValue\n} from '../model/field_value';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { assert, fail } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n invalidClassError,\n validateArgType,\n validateAtLeastNumberOfArgs,\n validateBetweenNumberOfArgs,\n validateDefined,\n validateExactNumberOfArgs,\n validateNamedOptionalPropertyEquals,\n validateNamedOptionalType,\n validateNamedType,\n validateOptionalArgType,\n validateOptionalArrayElements,\n validateOptionNames,\n validatePositiveNumber,\n validateStringEnum,\n valueDescription\n} from '../util/input_validation';\n// eslint-disable-next-line import/no-duplicates\nimport * as log from '../util/log';\n// eslint-disable-next-line import/no-duplicates\nimport { LogLevel } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { Rejecter, Resolver } from '../util/promise';\nimport { Deferred } from './../util/promise';\nimport { FieldPath as ExternalFieldPath } from './field_path';\n\nimport {\n CredentialsProvider,\n CredentialsSettings,\n EmptyCredentialsProvider,\n FirebaseCredentialsProvider,\n makeCredentialsProvider\n} from './credentials';\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver,\n Unsubscribe\n} from './observer';\nimport {\n DocumentKeyReference,\n fieldPathFromArgument,\n UserDataConverter\n} from './user_data_converter';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\n// settings() defaults:\nconst DEFAULT_HOST = 'firestore.googleapis.com';\nconst DEFAULT_SSL = true;\nconst DEFAULT_TIMESTAMPS_IN_SNAPSHOTS = true;\nconst DEFAULT_FORCE_LONG_POLLING = false;\n\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * `Firestore` instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LruParams.COLLECTION_DISABLED;\n\n// enablePersistence() defaults:\nconst DEFAULT_SYNCHRONIZE_TABS = false;\n\n/** Undocumented, private additional settings not exposed in our public API. */\ninterface PrivateSettings extends firestore.Settings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n}\n\n/**\n * Options that can be provided in the Firestore constructor when not using\n * Firebase (aka standalone mode).\n */\nexport interface FirestoreDatabase {\n projectId: string;\n database?: string;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass FirestoreSettings {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly timestampsInSnapshots: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly forceLongPolling: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n validateNamedType('settings', 'non-empty string', 'host', settings.host);\n this.host = settings.host;\n\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = objUtils.defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, [\n 'host',\n 'ssl',\n 'credentials',\n 'timestampsInSnapshots',\n 'cacheSizeBytes',\n 'experimentalForceLongPolling'\n ]);\n\n validateNamedOptionalType(\n 'settings',\n 'object',\n 'credentials',\n settings.credentials\n );\n this.credentials = settings.credentials;\n\n validateNamedOptionalType(\n 'settings',\n 'boolean',\n 'timestampsInSnapshots',\n settings.timestampsInSnapshots\n );\n\n // Nobody should set timestampsInSnapshots anymore, but the error depends on\n // whether they set it to true or false...\n if (settings.timestampsInSnapshots === true) {\n log.error(`\n The timestampsInSnapshots setting now defaults to true and you no\n longer need to explicitly set it. In a future release, the setting\n will be removed entirely and so it is recommended that you remove it\n from your firestore.settings() call now.`);\n } else if (settings.timestampsInSnapshots === false) {\n log.error(`\n The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n YOUR CODE.\n\n To hide this warning, stop using the timestampsInSnapshots setting in your\n firestore.settings({ ... }) call.\n\n Once you remove the setting, Timestamps stored in Cloud Firestore will be\n read back as Firebase Timestamp objects instead of as system Date objects.\n So you will also need to update code expecting a Date to instead expect a\n Timestamp. For example:\n\n // Old:\n const date = snapshot.get('created_at');\n // New:\n const timestamp = snapshot.get('created_at'); const date =\n timestamp.toDate();\n\n Please audit all existing usages of Date when you enable the new\n behavior.`);\n }\n this.timestampsInSnapshots = objUtils.defaulted(\n settings.timestampsInSnapshots,\n DEFAULT_TIMESTAMPS_IN_SNAPSHOTS\n );\n\n validateNamedOptionalType(\n 'settings',\n 'number',\n 'cacheSizeBytes',\n settings.cacheSizeBytes\n );\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LruParams.DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LruParams.MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LruParams.MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateNamedOptionalType(\n 'settings',\n 'boolean',\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling\n );\n this.forceLongPolling =\n settings.experimentalForceLongPolling === undefined\n ? DEFAULT_FORCE_LONG_POLLING\n : settings.experimentalForceLongPolling;\n }\n\n isEqual(other: FirestoreSettings): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.timestampsInSnapshots === other.timestampsInSnapshots &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.forceLongPolling === other.forceLongPolling\n );\n }\n}\n\n/**\n * The root reference to the database.\n */\nexport class Firestore implements firestore.FirebaseFirestore, FirebaseService {\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 readonly _databaseId: DatabaseId;\n private readonly _persistenceKey: string;\n private _credentials: CredentialsProvider;\n private readonly _firebaseApp: FirebaseApp | null = null;\n private _settings: FirestoreSettings;\n\n // The firestore client instance. This will be available as soon as\n // configureClient is called, but any calls against it will block until\n // setup has completed.\n //\n // Operations on the _firestoreClient don't block on _firestoreReady. Those\n // are already set to synchronize on the async queue.\n private _firestoreClient: FirestoreClient | undefined;\n\n // Public for use in tests.\n // TODO(mikelehen): Use modularized initialization instead.\n readonly _queue = new AsyncQueue();\n\n readonly _dataConverter: UserDataConverter;\n\n constructor(\n databaseIdOrApp: FirestoreDatabase | FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>\n ) {\n if (typeof (databaseIdOrApp as FirebaseApp).options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n const app = databaseIdOrApp as FirebaseApp;\n this._firebaseApp = app;\n this._databaseId = Firestore.databaseIdFromApp(app);\n this._persistenceKey = app.name;\n this._credentials = new FirebaseCredentialsProvider(authProvider);\n } else {\n const external = databaseIdOrApp as FirestoreDatabase;\n if (!external.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Must provide projectId'\n );\n }\n\n this._databaseId = new DatabaseId(external.projectId, external.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n this._persistenceKey = '[DEFAULT]';\n this._credentials = new EmptyCredentialsProvider();\n }\n\n this._settings = new FirestoreSettings({});\n this._dataConverter = this.createDataConverter(this._databaseId);\n }\n\n settings(settingsLiteral: firestore.Settings): void {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n\n if (\n objUtils.contains(settingsLiteral as objUtils.Dict<{}>, 'persistence')\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().'\n );\n }\n\n const newSettings = new FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._settings.isEqual(newSettings)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n\n this._settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._credentials = makeCredentialsProvider(newSettings.credentials);\n }\n }\n\n enableNetwork(): Promise<void> {\n this.ensureClientConfigured();\n return this._firestoreClient!.enableNetwork();\n }\n\n disableNetwork(): Promise<void> {\n this.ensureClientConfigured();\n return this._firestoreClient!.disableNetwork();\n }\n\n enablePersistence(settings?: firestore.PersistenceSettings): Promise<void> {\n if (this._firestoreClient) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.'\n );\n }\n\n let synchronizeTabs = false;\n\n if (settings) {\n if (settings.experimentalTabSynchronization !== undefined) {\n log.error(\n \"The 'experimentalTabSynchronization' setting has been renamed to \" +\n \"'synchronizeTabs'. In a future release, the setting will be removed \" +\n 'and it is recommended that you update your ' +\n \"firestore.enablePersistence() call to use 'synchronizeTabs'.\"\n );\n }\n synchronizeTabs = objUtils.defaulted(\n settings.synchronizeTabs !== undefined\n ? settings.synchronizeTabs\n : settings.experimentalTabSynchronization,\n DEFAULT_SYNCHRONIZE_TABS\n );\n }\n\n return this.configureClient(\n new IndexedDbPersistenceSettings(\n this._settings.cacheSizeBytes,\n synchronizeTabs\n )\n );\n }\n\n clearPersistence(): Promise<void> {\n const persistenceKey = IndexedDbPersistence.buildStoragePrefix(\n this.makeDatabaseInfo()\n );\n const deferred = new Deferred<void>();\n this._queue.enqueueAndForgetEvenAfterShutdown(async () => {\n try {\n if (\n this._firestoreClient !== undefined &&\n !this._firestoreClient.clientTerminated\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence cannot be cleared after this Firestore instance is initialized.'\n );\n }\n await IndexedDbPersistence.clearPersistence(persistenceKey);\n deferred.resolve();\n } catch (e) {\n deferred.reject(e);\n }\n });\n return deferred.promise;\n }\n\n terminate(): Promise<void> {\n (this.app as _FirebaseApp)._removeServiceInstance('firestore');\n return this.INTERNAL.delete();\n }\n\n get _isTerminated(): boolean {\n this.ensureClientConfigured();\n return this._firestoreClient!.clientTerminated;\n }\n\n waitForPendingWrites(): Promise<void> {\n this.ensureClientConfigured();\n return this._firestoreClient!.waitForPendingWrites();\n }\n\n onSnapshotsInSync(observer: PartialObserver<void>): Unsubscribe;\n onSnapshotsInSync(onSync: () => void): Unsubscribe;\n onSnapshotsInSync(arg: unknown): Unsubscribe {\n this.ensureClientConfigured();\n\n if (isPartialObserver(arg)) {\n return this.onSnapshotsInSyncInternal(arg as PartialObserver<void>);\n } else {\n validateArgType('Firestore.onSnapshotsInSync', 'function', 1, arg);\n const observer: PartialObserver<void> = {\n next: arg as () => void\n };\n return this.onSnapshotsInSyncInternal(observer);\n }\n }\n\n private onSnapshotsInSyncInternal(\n observer: PartialObserver<void>\n ): Unsubscribe {\n const errHandler = (err: Error): void => {\n throw fail('Uncaught Error in onSnapshotsInSync');\n };\n const asyncObserver = new AsyncObserver<void>({\n next: () => {\n if (observer.next) {\n observer.next();\n }\n },\n error: errHandler\n });\n this._firestoreClient!.addSnapshotsInSyncListener(asyncObserver);\n return () => {\n asyncObserver.mute();\n this._firestoreClient!.removeSnapshotsInSyncListener(asyncObserver);\n };\n }\n\n ensureClientConfigured(): FirestoreClient {\n if (!this._firestoreClient) {\n // Kick off starting the client but don't actually wait for it.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.configureClient(new MemoryPersistenceSettings());\n }\n return this._firestoreClient as FirestoreClient;\n }\n\n private makeDatabaseInfo(): DatabaseInfo {\n return new DatabaseInfo(\n this._databaseId,\n this._persistenceKey,\n this._settings.host,\n this._settings.ssl,\n this._settings.forceLongPolling\n );\n }\n\n private configureClient(\n persistenceSettings: InternalPersistenceSettings\n ): Promise<void> {\n assert(!!this._settings.host, 'FirestoreSettings.host is not set');\n\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n\n const databaseInfo = this.makeDatabaseInfo();\n\n this._firestoreClient = new FirestoreClient(\n PlatformSupport.getPlatform(),\n databaseInfo,\n this._credentials,\n this._queue\n );\n\n return this._firestoreClient.start(persistenceSettings);\n }\n\n private createDataConverter(databaseId: DatabaseId): UserDataConverter {\n const preConverter = (value: unknown): unknown => {\n if (value instanceof DocumentReference) {\n const thisDb = databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return new DocumentKeyReference(databaseId, value._key);\n } else {\n return value;\n }\n };\n return new UserDataConverter(preConverter);\n }\n\n private static databaseIdFromApp(app: FirebaseApp): DatabaseId {\n const options = app.options as objUtils.Dict<{}>;\n if (!objUtils.contains(options, 'projectId')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n const projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'projectId must be a string in FirebaseApp.options'\n );\n }\n return new DatabaseId(projectId);\n }\n\n get app(): FirebaseApp {\n if (!this._firebaseApp) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._firebaseApp;\n }\n\n INTERNAL = {\n delete: async (): Promise<void> => {\n // The client must be initalized to ensure that all subsequent API usage\n // throws an exception.\n this.ensureClientConfigured();\n await this._firestoreClient!.terminate();\n }\n };\n\n collection(pathString: string): firestore.CollectionReference {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'non-empty string', 1, pathString);\n this.ensureClientConfigured();\n return new CollectionReference(ResourcePath.fromString(pathString), this);\n }\n\n doc(pathString: string): firestore.DocumentReference {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'non-empty string', 1, pathString);\n this.ensureClientConfigured();\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\n }\n\n collectionGroup(collectionId: string): firestore.Query {\n validateExactNumberOfArgs('Firestore.collectionGroup', arguments, 1);\n validateArgType(\n 'Firestore.collectionGroup',\n 'non-empty string',\n 1,\n collectionId\n );\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `Firestore.collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n this.ensureClientConfigured();\n return new Query(\n new InternalQuery(ResourcePath.EMPTY_PATH, collectionId),\n this\n );\n }\n\n runTransaction<T>(\n updateFunction: (transaction: firestore.Transaction) => Promise<T>\n ): Promise<T> {\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(\n (transaction: InternalTransaction) => {\n return updateFunction(new Transaction(this, transaction));\n }\n );\n }\n\n batch(): firestore.WriteBatch {\n this.ensureClientConfigured();\n\n return new WriteBatch(this);\n }\n\n static get logLevel(): firestore.LogLevel {\n switch (log.getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + log.getLogLevel());\n }\n }\n\n static setLogLevel(level: firestore.LogLevel): void {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'non-empty string', 1, level);\n switch (level) {\n case 'debug':\n log.setLogLevel(log.LogLevel.DEBUG);\n break;\n case 'error':\n log.setLogLevel(log.LogLevel.ERROR);\n break;\n case 'silent':\n log.setLogLevel(log.LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid log level: ' + level\n );\n }\n }\n\n // Note: this is not a property because the minifier can't work correctly with\n // the way TypeScript compiler outputs properties.\n _areTimestampsInSnapshotsEnabled(): boolean {\n return this._settings.timestampsInSnapshots;\n }\n}\n\n/**\n * A reference to a transaction.\n */\nexport class Transaction implements firestore.Transaction {\n constructor(\n private _firestore: Firestore,\n private _transaction: InternalTransaction\n ) {}\n\n get<T>(\n documentRef: firestore.DocumentReference<T>\n ): Promise<firestore.DocumentSnapshot<T>> {\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n const ref = validateReference(\n 'Transaction.get',\n documentRef,\n this._firestore\n );\n return this._transaction\n .lookup([ref._key])\n .then((docs: MaybeDocument[]) => {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc instanceof NoDocument) {\n return new DocumentSnapshot<T>(\n this._firestore,\n ref._key,\n null,\n /* fromCache= */ false,\n /* hasPendingWrites= */ false,\n ref._converter\n );\n } else if (doc instanceof Document) {\n return new DocumentSnapshot<T>(\n this._firestore,\n ref._key,\n doc,\n /* fromCache= */ false,\n /* hasPendingWrites= */ false,\n ref._converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document type: ${doc.constructor.name}`\n );\n }\n });\n }\n\n set<T>(\n documentRef: firestore.DocumentReference<T>,\n value: T,\n options?: firestore.SetOptions\n ): Transaction {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n const ref = validateReference(\n 'Transaction.set',\n documentRef,\n this._firestore\n );\n options = validateSetOptions('Transaction.set', options);\n const [convertedValue, functionName] = applyFirestoreDataConverter(\n ref._converter,\n value,\n 'Transaction.set'\n );\n const parsed =\n options.merge || options.mergeFields\n ? this._firestore._dataConverter.parseMergeData(\n functionName,\n convertedValue,\n options.mergeFields\n )\n : this._firestore._dataConverter.parseSetData(\n functionName,\n convertedValue\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n update(\n documentRef: firestore.DocumentReference<unknown>,\n value: firestore.UpdateData\n ): Transaction;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n field: string | ExternalFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction {\n let ref;\n let parsed;\n\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath\n ) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference(\n 'Transaction.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateVarargs(\n 'Transaction.update',\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference(\n 'Transaction.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateData(\n 'Transaction.update',\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n delete(documentRef: firestore.DocumentReference<unknown>): Transaction {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n const ref = validateReference(\n 'Transaction.delete',\n documentRef,\n this._firestore\n );\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\nexport class WriteBatch implements firestore.WriteBatch {\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n constructor(private _firestore: Firestore) {}\n\n set<T>(\n documentRef: firestore.DocumentReference<T>,\n value: T,\n options?: firestore.SetOptions\n ): WriteBatch {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n const ref = validateReference(\n 'WriteBatch.set',\n documentRef,\n this._firestore\n );\n options = validateSetOptions('WriteBatch.set', options);\n const [convertedValue, functionName] = applyFirestoreDataConverter(\n ref._converter,\n value,\n 'WriteBatch.set'\n );\n const parsed =\n options.merge || options.mergeFields\n ? this._firestore._dataConverter.parseMergeData(\n functionName,\n convertedValue,\n options.mergeFields\n )\n : this._firestore._dataConverter.parseSetData(\n functionName,\n convertedValue\n );\n this._mutations = this._mutations.concat(\n parsed.toMutations(ref._key, Precondition.NONE)\n );\n return this;\n }\n\n update(\n documentRef: firestore.DocumentReference<unknown>,\n value: firestore.UpdateData\n ): WriteBatch;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n field: string | ExternalFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this.verifyNotCommitted();\n\n let ref;\n let parsed;\n\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath\n ) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference(\n 'WriteBatch.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateVarargs(\n 'WriteBatch.update',\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference(\n 'WriteBatch.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateData(\n 'WriteBatch.update',\n fieldOrUpdateData\n );\n }\n\n this._mutations = this._mutations.concat(\n parsed.toMutations(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n delete(documentRef: firestore.DocumentReference<unknown>): WriteBatch {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n const ref = validateReference(\n 'WriteBatch.delete',\n documentRef,\n this._firestore\n );\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.NONE)\n );\n return this;\n }\n\n async commit(): Promise<void> {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._firestore.ensureClientConfigured().write(this._mutations);\n }\n }\n\n private verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nexport class DocumentReference<T = firestore.DocumentData>\n implements firestore.DocumentReference<T> {\n private _firestoreClient: FirestoreClient;\n\n constructor(\n public _key: DocumentKey,\n readonly firestore: Firestore,\n readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n\n static forPath<U>(\n path: ResourcePath,\n firestore: Firestore,\n converter?: firestore.FirestoreDataConverter<U>\n ): DocumentReference<U> {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(\n Code.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(new DocumentKey(path), firestore, converter);\n }\n\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n get parent(): firestore.CollectionReference<T> {\n return new CollectionReference(\n this._key.path.popLast(),\n this.firestore,\n this._converter\n );\n }\n\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n collection(\n pathString: string\n ): firestore.CollectionReference<firestore.DocumentData> {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType(\n 'DocumentReference.collection',\n 'non-empty string',\n 1,\n pathString\n );\n if (!pathString) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Must provide a non-empty collection name to collection()'\n );\n }\n const path = ResourcePath.fromString(pathString);\n return new CollectionReference(this._key.path.child(path), this.firestore);\n }\n\n isEqual(other: firestore.DocumentReference<T>): boolean {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return (\n this.firestore === other.firestore &&\n this._key.isEqual(other._key) &&\n this._converter === other._converter\n );\n }\n\n set(\n value: firestore.DocumentData,\n options?: firestore.SetOptions\n ): Promise<void>;\n set(value: T, options?: firestore.SetOptions): Promise<void> {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n const [convertedValue, functionName] = applyFirestoreDataConverter(\n this._converter,\n value,\n 'DocumentReference.set'\n );\n const parsed =\n options.merge || options.mergeFields\n ? this.firestore._dataConverter.parseMergeData(\n functionName,\n convertedValue,\n options.mergeFields\n )\n : this.firestore._dataConverter.parseSetData(\n functionName,\n convertedValue\n );\n return this._firestoreClient.write(\n parsed.toMutations(this._key, Precondition.NONE)\n );\n }\n\n update(value: firestore.UpdateData): Promise<void>;\n update(\n field: string | ExternalFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void>;\n update(\n fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void> {\n let parsed;\n\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath\n ) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs(\n 'DocumentReference.update',\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData(\n 'DocumentReference.update',\n fieldOrUpdateData\n );\n }\n\n return this._firestoreClient.write(\n parsed.toMutations(this._key, Precondition.exists(true))\n );\n }\n\n delete(): Promise<void> {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new DeleteMutation(this._key, Precondition.NONE)\n ]);\n }\n\n onSnapshot(\n observer: PartialObserver<firestore.DocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n observer: PartialObserver<firestore.DocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<firestore.DocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n onNext: NextFn<firestore.DocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n validateBetweenNumberOfArgs(\n 'DocumentReference.onSnapshot',\n arguments,\n 1,\n 4\n );\n let options: firestore.SnapshotListenOptions = {\n includeMetadataChanges: false\n };\n let observer: PartialObserver<firestore.DocumentSnapshot<T>>;\n let currArg = 0;\n if (\n typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])\n ) {\n options = args[currArg] as firestore.SnapshotListenOptions;\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType(\n 'DocumentReference.onSnapshot',\n 'boolean',\n 'includeMetadataChanges',\n options.includeMetadataChanges\n );\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges\n };\n\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg] as PartialObserver<\n firestore.DocumentSnapshot<T>\n >;\n } else {\n validateArgType(\n 'DocumentReference.onSnapshot',\n 'function',\n currArg,\n args[currArg]\n );\n validateOptionalArgType(\n 'DocumentReference.onSnapshot',\n 'function',\n currArg + 1,\n args[currArg + 1]\n );\n validateOptionalArgType(\n 'DocumentReference.onSnapshot',\n 'function',\n currArg + 2,\n args[currArg + 2]\n );\n observer = {\n next: args[currArg] as NextFn<firestore.DocumentSnapshot<T>>,\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n }\n\n private onSnapshotInternal(\n options: ListenOptions,\n observer: PartialObserver<firestore.DocumentSnapshot<T>>\n ): Unsubscribe {\n let errHandler = (err: Error): void => {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n\n const asyncObserver = new AsyncObserver<ViewSnapshot>({\n next: snapshot => {\n if (observer.next) {\n assert(\n snapshot.docs.size <= 1,\n 'Too many documents returned on a document query'\n );\n const doc = snapshot.docs.get(this._key);\n\n observer.next(\n new DocumentSnapshot(\n this.firestore,\n this._key,\n doc,\n snapshot.fromCache,\n snapshot.hasPendingWrites,\n this._converter\n )\n );\n }\n },\n error: errHandler\n });\n const internalListener = this._firestoreClient.listen(\n InternalQuery.atPath(this._key.path),\n asyncObserver,\n options\n );\n\n return () => {\n asyncObserver.mute();\n this._firestoreClient.unlisten(internalListener);\n };\n }\n\n get(options?: firestore.GetOptions): Promise<firestore.DocumentSnapshot<T>> {\n validateBetweenNumberOfArgs('DocumentReference.get', arguments, 0, 1);\n validateGetOptions('DocumentReference.get', options);\n return new Promise(\n (resolve: Resolver<firestore.DocumentSnapshot<T>>, reject: Rejecter) => {\n if (options && options.source === 'cache') {\n this.firestore\n .ensureClientConfigured()\n .getDocumentFromLocalCache(this._key)\n .then(doc => {\n resolve(\n new DocumentSnapshot(\n this.firestore,\n this._key,\n doc,\n /*fromCache=*/ true,\n doc instanceof Document ? doc.hasLocalMutations : false,\n this._converter\n )\n );\n }, reject);\n } else {\n this.getViaSnapshotListener(resolve, reject, options);\n }\n }\n );\n }\n\n private getViaSnapshotListener(\n resolve: Resolver<firestore.DocumentSnapshot<T>>,\n reject: Rejecter,\n options?: firestore.GetOptions\n ): void {\n const unlisten = this.onSnapshotInternal(\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n },\n {\n next: (snap: firestore.DocumentSnapshot<T>) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n\n if (!snap.exists && snap.metadata.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 reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is ' + 'offline.'\n )\n );\n } else if (\n snap.exists &&\n snap.metadata.fromCache &&\n options &&\n options.source === 'server'\n ) {\n reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from server. (However, this ' +\n 'document does exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached document.)'\n )\n );\n } else {\n resolve(snap);\n }\n },\n error: reject\n }\n );\n }\n\n withConverter<U>(\n converter: firestore.FirestoreDataConverter<U>\n ): firestore.DocumentReference<U> {\n return new DocumentReference<U>(this._key, this.firestore, converter);\n }\n}\n\nclass SnapshotMetadata implements firestore.SnapshotMetadata {\n constructor(\n readonly hasPendingWrites: boolean,\n readonly fromCache: boolean\n ) {}\n\n isEqual(other: firestore.SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * Options interface that can be provided to configure the deserialization of\n * DocumentSnapshots.\n */\nexport interface SnapshotOptions extends firestore.SnapshotOptions {}\n\nexport class DocumentSnapshot<T = firestore.DocumentData>\n implements firestore.DocumentSnapshot<T> {\n constructor(\n private _firestore: Firestore,\n private _key: DocumentKey,\n public _document: Document | null,\n private _fromCache: boolean,\n private _hasPendingWrites: boolean,\n private readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {}\n\n data(options?: firestore.SnapshotOptions): T | undefined {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n if (!this._document) {\n return undefined;\n } else {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n if (this._converter) {\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._key,\n this._document,\n this._fromCache,\n this._hasPendingWrites\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this.toJSObject(\n this._document.data(),\n FieldValueOptions.fromSnapshotOptions(\n options,\n this._firestore._areTimestampsInSnapshotsEnabled()\n )\n ) as T;\n }\n }\n }\n\n get(\n fieldPath: string | ExternalFieldPath,\n options?: firestore.SnapshotOptions\n ): unknown {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n if (this._document) {\n const value = this._document\n .data()\n .field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n if (value !== null) {\n return this.toJSValue(\n value,\n FieldValueOptions.fromSnapshotOptions(\n options,\n this._firestore._areTimestampsInSnapshotsEnabled()\n )\n );\n }\n }\n return undefined;\n }\n\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n get ref(): firestore.DocumentReference<T> {\n return new DocumentReference<T>(\n this._key,\n this._firestore,\n this._converter\n );\n }\n\n get exists(): boolean {\n return this._document !== null;\n }\n\n get metadata(): firestore.SnapshotMetadata {\n return new SnapshotMetadata(this._hasPendingWrites, this._fromCache);\n }\n\n isEqual(other: firestore.DocumentSnapshot<T>): boolean {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n return (\n this._firestore === other._firestore &&\n this._fromCache === other._fromCache &&\n this._key.isEqual(other._key) &&\n (this._document === null\n ? other._document === null\n : this._document.isEqual(other._document)) &&\n this._converter === other._converter\n );\n }\n\n private toJSObject(\n data: ObjectValue,\n options: FieldValueOptions\n ): firestore.DocumentData {\n const result: firestore.DocumentData = {};\n data.forEach((key, value) => {\n result[key] = this.toJSValue(value, options);\n });\n return result;\n }\n\n private toJSValue(value: FieldValue, options: FieldValueOptions): unknown {\n if (value instanceof ObjectValue) {\n return this.toJSObject(value, options);\n } else if (value instanceof ArrayValue) {\n return this.toJSArray(value, options);\n } else if (value instanceof RefValue) {\n const key = value.value(options);\n const database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log.error(\n `Document ${this._key.path} contains a document ` +\n `reference within a different database (` +\n `${value.databaseId.projectId}/${value.databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${database.projectId}/${database.database}) ` +\n `instead.`\n );\n }\n return new DocumentReference(key, this._firestore, this._converter);\n } else {\n return value.value(options);\n }\n }\n\n private toJSArray(data: ArrayValue, options: FieldValueOptions): unknown[] {\n return data.internalValue.map(value => {\n return this.toJSValue(value, options);\n });\n }\n}\n\nexport class QueryDocumentSnapshot<T = firestore.DocumentData>\n extends DocumentSnapshot<T>\n implements firestore.QueryDocumentSnapshot<T> {\n data(options?: SnapshotOptions): T {\n const data = super.data(options);\n assert(\n data !== undefined,\n 'Document in a QueryDocumentSnapshot should exist'\n );\n return data;\n }\n}\n\nexport class Query<T = firestore.DocumentData> implements firestore.Query<T> {\n constructor(\n public _query: InternalQuery,\n readonly firestore: Firestore,\n protected readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {}\n\n where(\n field: string | ExternalFieldPath,\n opStr: firestore.WhereFilterOp,\n value: unknown\n ): firestore.Query<T> {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateDefined('Query.where', 3, value);\n\n // Enumerated from the WhereFilterOp type in index.d.ts.\n const whereFilterOpEnums = [\n '<',\n '<=',\n '==',\n '>=',\n '>',\n 'array-contains',\n 'in',\n 'array-contains-any'\n ];\n validateStringEnum('Query.where', whereFilterOpEnums, 2, opStr);\n\n let fieldValue: FieldValue;\n const fieldPath = fieldPathFromArgument('Query.where', field);\n const operator = Operator.fromString(opStr);\n if (fieldPath.isKeyField()) {\n if (\n operator === Operator.ARRAY_CONTAINS ||\n operator === Operator.ARRAY_CONTAINS_ANY\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${operator.toString()}' ` +\n 'queries on FieldPath.documentId().'\n );\n } else if (operator === Operator.IN) {\n this.validateDisjunctiveFilterElements(value, operator);\n const referenceList: FieldValue[] = [];\n for (const arrayValue of value as FieldValue[]) {\n referenceList.push(this.parseDocumentIdValue(arrayValue));\n }\n fieldValue = new ArrayValue(referenceList);\n } else {\n fieldValue = this.parseDocumentIdValue(value);\n }\n } else {\n if (\n operator === Operator.IN ||\n operator === Operator.ARRAY_CONTAINS_ANY\n ) {\n this.validateDisjunctiveFilterElements(value, operator);\n }\n fieldValue = this.firestore._dataConverter.parseQueryValue(\n 'Query.where',\n value,\n // We only allow nested arrays for IN queries.\n /** allowArrays = */ operator === Operator.IN ? true : false\n );\n }\n const filter = FieldFilter.create(fieldPath, operator, fieldValue);\n this.validateNewFilter(filter);\n return new Query(\n this._query.addFilter(filter),\n this.firestore,\n this._converter\n );\n }\n\n orderBy(\n field: string | ExternalFieldPath,\n directionStr?: firestore.OrderByDirection\n ): firestore.Query<T> {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType(\n 'Query.orderBy',\n 'non-empty string',\n 2,\n directionStr\n );\n let direction: Direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n } else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function Query.orderBy() has unknown direction '${directionStr}', ` +\n `expected 'asc' or 'desc'.`\n );\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().'\n );\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().'\n );\n }\n const fieldPath = fieldPathFromArgument('Query.orderBy', field);\n const orderBy = new OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(\n this._query.addOrderBy(orderBy),\n this.firestore,\n this._converter\n );\n }\n\n limit(n: number): firestore.Query<T> {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n validatePositiveNumber('Query.limit', 1, n);\n return new Query(\n this._query.withLimitToFirst(n),\n this.firestore,\n this._converter\n );\n }\n\n limitToLast(n: number): firestore.Query<T> {\n validateExactNumberOfArgs('Query.limitToLast', arguments, 1);\n validateArgType('Query.limitToLast', 'number', 1, n);\n validatePositiveNumber('Query.limitToLast', 1, n);\n return new Query(\n this._query.withLimitToLast(n),\n this.firestore,\n this._converter\n );\n }\n\n startAt(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.startAt',\n docOrField,\n fields,\n /*before=*/ true\n );\n return new Query(\n this._query.withStartAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n startAfter(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.startAfter',\n docOrField,\n fields,\n /*before=*/ false\n );\n return new Query(\n this._query.withStartAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n endBefore(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.endBefore',\n docOrField,\n fields,\n /*before=*/ true\n );\n return new Query(\n this._query.withEndAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n endAt(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.endAt',\n docOrField,\n fields,\n /*before=*/ false\n );\n return new Query(\n this._query.withEndAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n isEqual(other: firestore.Query<T>): boolean {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (\n this.firestore === other.firestore && this._query.isEqual(other._query)\n );\n }\n\n withConverter<U>(\n converter: firestore.FirestoreDataConverter<U>\n ): firestore.Query<U> {\n return new Query<U>(this._query, this.firestore, converter);\n }\n\n /** Helper function to create a bound from a document or fields */\n private boundFromDocOrFields(\n methodName: string,\n docOrField: unknown | firestore.DocumentSnapshot<T>,\n fields: unknown[],\n before: boolean\n ): Bound {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}().`\n );\n }\n const snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n return this.boundFromDocument(methodName, snap._document!, before);\n } else {\n const allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\n }\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 */\n private boundFromDocument(\n methodName: string,\n doc: Document,\n before: boolean\n ): Bound {\n const components: FieldValue[] = [];\n\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 orderBy of this._query.orderBy) {\n if (orderBy.field.isKeyField()) {\n components.push(new RefValue(this.firestore._databaseId, doc.key));\n } else {\n const value = doc.field(orderBy.field);\n if (value instanceof ServerTimestampValue) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, before);\n }\n\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n private boundFromFields(\n methodName: string,\n values: unknown[],\n before: boolean\n ): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of Query.orderBy() clauses`\n );\n }\n\n const components: FieldValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (\n !this._query.isCollectionGroupQuery() &&\n rawValue.indexOf('/') !== -1\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by FieldPath.documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = this._query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `FieldPath.documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(new RefValue(this.firestore._databaseId, key));\n } else {\n const wrapped = this.firestore._dataConverter.parseQueryValue(\n methodName,\n rawValue\n );\n components.push(wrapped);\n }\n }\n\n return new Bound(components, before);\n }\n\n onSnapshot(\n observer: PartialObserver<firestore.QuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n observer: PartialObserver<firestore.QuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<firestore.QuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n onNext: NextFn<firestore.QuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n let options: firestore.SnapshotListenOptions = {};\n let observer: PartialObserver<firestore.QuerySnapshot<T>>;\n let currArg = 0;\n if (\n typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])\n ) {\n options = args[currArg] as firestore.SnapshotListenOptions;\n validateOptionNames('Query.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType(\n 'Query.onSnapshot',\n 'boolean',\n 'includeMetadataChanges',\n options.includeMetadataChanges\n );\n currArg++;\n }\n\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg] as PartialObserver<firestore.QuerySnapshot<T>>;\n } else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType(\n 'Query.onSnapshot',\n 'function',\n currArg + 1,\n args[currArg + 1]\n );\n validateOptionalArgType(\n 'Query.onSnapshot',\n 'function',\n currArg + 2,\n args[currArg + 2]\n );\n observer = {\n next: args[currArg] as NextFn<firestore.QuerySnapshot<T>>,\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n }\n this.validateHasExplicitOrderByForLimitToLast(this._query);\n return this.onSnapshotInternal(options, observer);\n }\n\n private onSnapshotInternal(\n options: ListenOptions,\n observer: PartialObserver<firestore.QuerySnapshot<T>>\n ): Unsubscribe {\n let errHandler = (err: Error): void => {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n\n const asyncObserver = new AsyncObserver<ViewSnapshot>({\n next: (result: ViewSnapshot): void => {\n if (observer.next) {\n observer.next(\n new QuerySnapshot(\n this.firestore,\n this._query,\n result,\n this._converter\n )\n );\n }\n },\n error: errHandler\n });\n\n const firestoreClient = this.firestore.ensureClientConfigured();\n const internalListener = firestoreClient.listen(\n this._query,\n asyncObserver,\n options\n );\n return (): void => {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n }\n\n private validateHasExplicitOrderByForLimitToLast(query: InternalQuery): void {\n if (query.hasLimitToLast() && query.explicitOrderBy.length === 0) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n }\n\n get(options?: firestore.GetOptions): Promise<firestore.QuerySnapshot<T>> {\n validateBetweenNumberOfArgs('Query.get', arguments, 0, 1);\n validateGetOptions('Query.get', options);\n this.validateHasExplicitOrderByForLimitToLast(this._query);\n return new Promise(\n (resolve: Resolver<firestore.QuerySnapshot<T>>, reject: Rejecter) => {\n if (options && options.source === 'cache') {\n this.firestore\n .ensureClientConfigured()\n .getDocumentsFromLocalCache(this._query)\n .then((viewSnap: ViewSnapshot) => {\n resolve(\n new QuerySnapshot(\n this.firestore,\n this._query,\n viewSnap,\n this._converter\n )\n );\n }, reject);\n } else {\n this.getViaSnapshotListener(resolve, reject, options);\n }\n }\n );\n }\n\n private getViaSnapshotListener(\n resolve: Resolver<firestore.QuerySnapshot<T>>,\n reject: Rejecter,\n options?: firestore.GetOptions\n ): void {\n const unlisten = this.onSnapshotInternal(\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n },\n {\n next: (result: firestore.QuerySnapshot<T>) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n\n if (\n result.metadata.fromCache &&\n options &&\n options.source === 'server'\n ) {\n reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get documents from server. (However, these ' +\n 'documents may exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached documents.)'\n )\n );\n } else {\n resolve(result);\n }\n },\n error: reject\n }\n );\n }\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 */\n private parseDocumentIdValue(documentIdValue: unknown): RefValue {\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with FieldPath.documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (\n !this._query.isCollectionGroupQuery() &&\n documentIdValue.indexOf('/') !== -1\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `FieldPath.documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = this._query.path.child(\n ResourcePath.fromString(documentIdValue)\n );\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `FieldPath.documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return new RefValue(this.firestore._databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n const ref = documentIdValue as DocumentReference<T>;\n return new RefValue(this.firestore._databaseId, ref._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with FieldPath.documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n }\n\n /**\n * Validates that the value passed into a disjunctrive filter satisfies all\n * array requirements.\n */\n private validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n ): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n if (value.length > 10) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. '${operator.toString()}' filters support a ` +\n 'maximum of 10 elements in the value array.'\n );\n }\n if (value.indexOf(null) >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. '${operator.toString()}' filters cannot contain 'null' ` +\n 'in the value array.'\n );\n }\n if (value.filter(element => Number.isNaN(element)).length > 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. '${operator.toString()}' filters cannot contain 'NaN' ` +\n 'in the value array.'\n );\n }\n }\n\n private validateNewFilter(filter: Filter): void {\n if (filter instanceof FieldFilter) {\n const arrayOps = [Operator.ARRAY_CONTAINS, Operator.ARRAY_CONTAINS_ANY];\n const disjunctiveOps = [Operator.IN, Operator.ARRAY_CONTAINS_ANY];\n const isArrayOp = arrayOps.indexOf(filter.op) >= 0;\n const isDisjunctiveOp = disjunctiveOps.indexOf(filter.op) >= 0;\n\n if (filter.isInequality()) {\n const existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n ` inequality filters on '${existingField.toString()}'` +\n ` and '${filter.field.toString()}'`\n );\n }\n\n const firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(\n filter.field,\n firstOrderByField\n );\n }\n } else if (isDisjunctiveOp || isArrayOp) {\n // You can have at most 1 disjunctive filter and 1 array filter. Check if\n // the new filter conflicts with an existing one.\n let conflictingOp: Operator | null = null;\n if (isDisjunctiveOp) {\n conflictingOp = this._query.findFilterOperator(disjunctiveOps);\n }\n if (conflictingOp === null && isArrayOp) {\n conflictingOp = this._query.findFilterOperator(arrayOps);\n }\n if (conflictingOp != null) {\n // We special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === filter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${filter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${filter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n }\n }\n }\n\n private validateNewOrderBy(orderBy: OrderBy): void {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n const inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n }\n\n private validateOrderByAndInequalityMatch(\n inequality: FieldPath,\n orderBy: FieldPath\n ): void {\n if (!orderBy.isEqual(inequality)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You have a where filter with an inequality ` +\n `(<, <=, >, or >=) on field '${inequality.toString()}' ` +\n `and so you must also use '${inequality.toString()}' ` +\n `as your first Query.orderBy(), but your first Query.orderBy() ` +\n `is on field '${orderBy.toString()}' instead.`\n );\n }\n }\n}\n\nexport class QuerySnapshot<T = firestore.DocumentData>\n implements firestore.QuerySnapshot<T> {\n private _cachedChanges: Array<firestore.DocumentChange<T>> | null = null;\n private _cachedChangesIncludeMetadataChanges: boolean | null = null;\n\n readonly metadata: firestore.SnapshotMetadata;\n\n constructor(\n private readonly _firestore: Firestore,\n private readonly _originalQuery: InternalQuery,\n private readonly _snapshot: ViewSnapshot,\n private readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n }\n\n get docs(): Array<firestore.QueryDocumentSnapshot<T>> {\n const result: Array<firestore.QueryDocumentSnapshot<T>> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n get empty(): boolean {\n return this._snapshot.docs.isEmpty();\n }\n\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n forEach(\n callback: (result: firestore.QueryDocumentSnapshot<T>) => void,\n thisArg?: unknown\n ): void {\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(doc => {\n callback.call(thisArg, this.convertToDocumentImpl(doc));\n });\n }\n\n get query(): firestore.Query<T> {\n return new Query(this._originalQuery, this._firestore, this._converter);\n }\n\n docChanges(\n options?: firestore.SnapshotListenOptions\n ): Array<firestore.DocumentChange<T>> {\n if (options) {\n validateOptionNames('QuerySnapshot.docChanges', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType(\n 'QuerySnapshot.docChanges',\n 'boolean',\n 'includeMetadataChanges',\n options.includeMetadataChanges\n );\n }\n\n const includeMetadataChanges = !!(\n options && options.includeMetadataChanges\n );\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'To include metadata changes with your document changes, you must ' +\n 'also pass { includeMetadataChanges:true } to onSnapshot().'\n );\n }\n\n if (\n !this._cachedChanges ||\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n ) {\n this._cachedChanges = changesFromSnapshot<T>(\n this._firestore,\n includeMetadataChanges,\n this._snapshot,\n this._converter\n );\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n\n /** Check the equality. The call can be very expensive. */\n isEqual(other: firestore.QuerySnapshot<T>): boolean {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n\n return (\n this._firestore === other._firestore &&\n this._originalQuery.isEqual(other._originalQuery) &&\n this._snapshot.isEqual(other._snapshot) &&\n this._converter === other._converter\n );\n }\n\n private convertToDocumentImpl(doc: Document): QueryDocumentSnapshot<T> {\n return new QueryDocumentSnapshot(\n this._firestore,\n doc.key,\n doc,\n this.metadata.fromCache,\n this._snapshot.mutatedKeys.has(doc.key),\n this._converter\n );\n }\n}\n\n// TODO(2018/11/01): As of 2018/04/17 we're changing docChanges from an array\n// into a method. Because this is a runtime breaking change and somewhat subtle\n// (both Array and Function have a .length, etc.), we'll replace commonly-used\n// properties (including Symbol.iterator) to throw a custom error message. In\n// ~6 months we can delete the custom error as most folks will have hopefully\n// migrated.\nfunction throwDocChangesMethodError(): never {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'QuerySnapshot.docChanges has been changed from a property into a ' +\n 'method, so usages like \"querySnapshot.docChanges\" should become ' +\n '\"querySnapshot.docChanges()\"'\n );\n}\n\nconst docChangesPropertiesToOverride = [\n 'length',\n 'forEach',\n 'map',\n ...(typeof Symbol !== 'undefined' ? [Symbol.iterator] : [])\n];\ndocChangesPropertiesToOverride.forEach(property => {\n /**\n * We are (re-)defining properties on QuerySnapshot.prototype.docChanges which\n * is a Function. This could fail, in particular in the case of 'length' which\n * already exists on Function.prototype and on IE11 is improperly defined with\n * `{ configurable: false }`. So we wrap this in a try/catch to ensure that we\n * still have a functional SDK.\n */\n try {\n Object.defineProperty(QuerySnapshot.prototype.docChanges, property, {\n get: () => throwDocChangesMethodError()\n });\n } catch (err) {} // Ignore this failure intentionally\n});\n\nexport class CollectionReference<T = firestore.DocumentData> extends Query<T>\n implements firestore.CollectionReference<T> {\n constructor(\n readonly _path: ResourcePath,\n firestore: Firestore,\n _converter?: firestore.FirestoreDataConverter<T>\n ) {\n super(InternalQuery.atPath(_path), firestore, _converter);\n if (_path.length % 2 !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n `${_path.canonicalString()} has ${_path.length}`\n );\n }\n }\n\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n get parent(): firestore.DocumentReference<firestore.DocumentData> | null {\n const parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference<firestore.DocumentData>(\n new DocumentKey(parentPath),\n this.firestore\n );\n }\n }\n\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n doc(pathString?: string): firestore.DocumentReference<T> {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = AutoId.newId();\n }\n validateArgType(\n 'CollectionReference.doc',\n 'non-empty string',\n 1,\n pathString\n );\n if (pathString === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Document path must be a non-empty string'\n );\n }\n const path = ResourcePath.fromString(pathString!);\n return DocumentReference.forPath<T>(\n this._query.path.child(path),\n this.firestore,\n this._converter\n );\n }\n\n add(value: T): Promise<firestore.DocumentReference<T>> {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n const docRef = this.doc();\n return docRef.set(value).then(() => docRef);\n }\n\n withConverter<U>(\n converter: firestore.FirestoreDataConverter<U>\n ): firestore.CollectionReference<U> {\n return new CollectionReference<U>(this._path, this.firestore, converter);\n }\n}\n\nfunction validateSetOptions(\n methodName: string,\n options: firestore.SetOptions | undefined\n): firestore.SetOptions {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n\n validateOptionNames(methodName, options, ['merge', 'mergeFields']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n validateOptionalArrayElements(\n methodName,\n 'mergeFields',\n 'a string or a FieldPath',\n options.mergeFields,\n element =>\n typeof element === 'string' || element instanceof ExternalFieldPath\n );\n\n if (options.mergeFields !== undefined && options.merge !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid options passed to function ${methodName}(): You cannot specify both \"merge\" ` +\n `and \"mergeFields\".`\n );\n }\n\n return options;\n}\n\nfunction validateSnapshotOptions(\n methodName: string,\n options: firestore.SnapshotOptions | undefined\n): firestore.SnapshotOptions {\n if (options === undefined) {\n return {};\n }\n\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(\n methodName,\n 'options',\n 'serverTimestamps',\n options.serverTimestamps,\n ['estimate', 'previous', 'none']\n );\n return options;\n}\n\nfunction validateGetOptions(\n methodName: string,\n options: firestore.GetOptions | undefined\n): void {\n validateOptionalArgType(methodName, 'object', 1, options);\n if (options) {\n validateOptionNames(methodName, options, ['source']);\n validateNamedOptionalPropertyEquals(\n methodName,\n 'options',\n 'source',\n options.source,\n ['default', 'server', 'cache']\n );\n }\n}\n\nfunction validateReference<T>(\n methodName: string,\n documentRef: firestore.DocumentReference<T>,\n firestore: Firestore\n): DocumentReference<T> {\n if (!(documentRef instanceof DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n } else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef;\n }\n}\n\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nexport function changesFromSnapshot<T>(\n firestore: Firestore,\n includeMetadataChanges: boolean,\n snapshot: ViewSnapshot,\n converter?: firestore.FirestoreDataConverter<T>\n): Array<firestore.DocumentChange<T>> {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n let lastDoc: Document;\n let index = 0;\n return snapshot.docChanges.map(change => {\n const doc = new QueryDocumentSnapshot<T>(\n firestore,\n change.doc.key,\n change.doc,\n snapshot.fromCache,\n snapshot.mutatedKeys.has(change.doc.key),\n converter\n );\n assert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n assert(\n !lastDoc || snapshot.query.docComparator(lastDoc, change.doc) < 0,\n 'Got added events in wrong order'\n );\n lastDoc = change.doc;\n return {\n type: 'added' as firestore.DocumentChangeType,\n doc,\n oldIndex: -1,\n newIndex: index++\n };\n });\n } else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let indexTracker = snapshot.oldDocs;\n return snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot<T>(\n firestore,\n change.doc.key,\n change.doc,\n snapshot.fromCache,\n snapshot.mutatedKeys.has(change.doc.key),\n converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker = indexTracker.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker = indexTracker.add(change.doc);\n newIndex = indexTracker.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc, oldIndex, newIndex };\n });\n }\n}\n\nfunction resultChangeType(type: ChangeType): firestore.DocumentChangeType {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\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 */\nfunction applyFirestoreDataConverter<T>(\n converter: firestore.FirestoreDataConverter<T> | undefined,\n value: T,\n functionName: string\n): [firestore.DocumentData, string] {\n let convertedValue;\n if (converter) {\n convertedValue = converter.toFirestore(value);\n functionName = 'toFirestore() in ' + functionName;\n } else {\n convertedValue = value as firestore.DocumentData;\n }\n return [convertedValue, functionName];\n}\n\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\nexport const PublicFirestore = makeConstructorPrivate(\n Firestore,\n 'Use firebase.firestore() instead.'\n);\nexport const PublicTransaction = makeConstructorPrivate(\n Transaction,\n 'Use firebase.firestore().runTransaction() instead.'\n);\nexport const PublicWriteBatch = makeConstructorPrivate(\n WriteBatch,\n 'Use firebase.firestore().batch() instead.'\n);\nexport const PublicDocumentReference = makeConstructorPrivate(\n DocumentReference,\n 'Use firebase.firestore().doc() instead.'\n);\nexport const PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\nexport const PublicQueryDocumentSnapshot = makeConstructorPrivate(\n QueryDocumentSnapshot\n);\nexport const PublicQuery = makeConstructorPrivate(Query);\nexport const PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\nexport const PublicCollectionReference = makeConstructorPrivate(\n CollectionReference,\n 'Use firebase.firestore().collection() instead.'\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { PublicBlob } from '../api/blob';\nimport {\n CACHE_SIZE_UNLIMITED,\n Firestore,\n PublicCollectionReference,\n PublicDocumentReference,\n PublicDocumentSnapshot,\n PublicFirestore,\n PublicQuery,\n PublicQueryDocumentSnapshot,\n PublicQuerySnapshot,\n PublicTransaction,\n PublicWriteBatch\n} from '../api/database';\nimport { FieldPath } from '../api/field_path';\nimport { PublicFieldValue } from '../api/field_value';\nimport { GeoPoint } from '../api/geo_point';\nimport { Timestamp } from '../api/timestamp';\nimport { shallowCopy } from '../util/obj';\nimport { Component, ComponentType } from '@firebase/component';\n\nconst firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint,\n Timestamp,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: Firestore.setLogLevel,\n CACHE_SIZE_UNLIMITED\n};\n\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nexport function configureForFirebase(firebase: FirebaseNamespace): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'firestore',\n container => {\n const app = container.getProvider('app').getImmediate()!;\n return new Firestore(app, container.getProvider('auth-internal'));\n },\n ComponentType.PUBLIC\n ).setServiceProps(shallowCopy(firestoreNamespace))\n );\n}\n\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nexport function configureForStandalone(exportObject: {\n [key: string]: {};\n}): void {\n const copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\n\nexport class NoopConnectivityMonitor implements ConnectivityMonitor {\n addCallback(callback: (status: NetworkStatus) => void): void {\n // No-op.\n }\n\n shutdown(): void {\n // No-op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\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 { debug } from '../util/log';\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from './../remote/connectivity_monitor';\n\nconst LOG_TAG = 'ConnectivityMonitor';\n\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nexport class BrowserConnectivityMonitor implements ConnectivityMonitor {\n private readonly networkAvailableListener = (): void =>\n this.onNetworkAvailable();\n private readonly networkUnavailableListener = (): void =>\n this.onNetworkUnavailable();\n private callbacks: ConnectivityMonitorCallback[] = [];\n\n constructor() {\n this.configureNetworkMonitoring();\n }\n\n addCallback(callback: (status: NetworkStatus) => void): void {\n this.callbacks.push(callback);\n }\n\n shutdown(): void {\n window.removeEventListener('online', this.networkAvailableListener);\n window.removeEventListener('offline', this.networkUnavailableListener);\n }\n\n private configureNetworkMonitoring(): void {\n window.addEventListener('online', this.networkAvailableListener);\n window.addEventListener('offline', this.networkUnavailableListener);\n }\n\n private onNetworkAvailable(): void {\n debug(LOG_TAG, 'Network connectivity changed: AVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.AVAILABLE);\n }\n }\n\n private onNetworkUnavailable(): void {\n debug(LOG_TAG, 'Network connectivity changed: UNAVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.UNAVAILABLE);\n }\n }\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 isAvailable(): boolean {\n return (\n typeof window !== 'undefined' &&\n window.addEventListener !== undefined &&\n window.removeEventListener !== undefined\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { assert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\n\nimport { Stream } from './connection';\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 */\nexport class StreamBridge<I, O> implements Stream<I, O> {\n private wrappedOnOpen: (() => void) | undefined;\n private wrappedOnClose: ((err?: FirestoreError) => void) | undefined;\n private wrappedOnMessage: ((msg: O) => void) | undefined;\n\n private sendFn: (msg: I) => void;\n private closeFn: () => void;\n\n constructor(args: { sendFn: (msg: I) => void; closeFn: () => void }) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n onOpen(callback: () => void): void {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n }\n\n close(): void {\n this.closeFn();\n }\n\n send(msg: I): void {\n this.sendFn(msg);\n }\n\n callOnOpen(): void {\n assert(\n this.wrappedOnOpen !== undefined,\n 'Cannot call onOpen because no callback was set'\n );\n this.wrappedOnOpen();\n }\n\n callOnClose(err?: FirestoreError): void {\n assert(\n this.wrappedOnClose !== undefined,\n 'Cannot call onClose because no callback was set'\n );\n this.wrappedOnClose(err);\n }\n\n callOnMessage(msg: O): void {\n assert(\n this.wrappedOnMessage !== undefined,\n 'Cannot call onMessage because no callback was set'\n );\n this.wrappedOnMessage(msg);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo\n} from '@firebase/webchannel-wrapper';\n\nimport {\n isBrowserExtension,\n isElectron,\n isIE,\n isReactNative,\n isUWP\n} from '@firebase/util';\n\nimport { Token } from '../api/credentials';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { SDK_VERSION } from '../core/version';\nimport { Connection, Stream } from '../remote/connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../remote/rpc_error';\nimport { StreamBridge } from '../remote/stream_bridge';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { Indexable } from '../util/misc';\nimport { Rejecter, Resolver } from '../util/promise';\nimport { StringMap } from '../util/types';\n\nconst LOG_TAG = 'Connection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\nconst RPC_URL_VERSION = 'v1';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n * Uses Object Literal notation to avoid renaming.\n */\nconst RPC_NAME_REST_MAPPING: { [key: string]: string } = {};\nRPC_NAME_REST_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_REST_MAPPING['Commit'] = 'commit';\n\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nconst X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection implements Connection {\n private readonly databaseId: DatabaseId;\n private readonly baseUrl: string;\n private readonly forceLongPolling: boolean;\n\n constructor(info: DatabaseInfo) {\n this.databaseId = info.databaseId;\n const proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n this.forceLongPolling = info.forceLongPolling;\n }\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n private modifyHeadersForRequest(\n headers: StringMap,\n token: Token | null\n ): void {\n if (token) {\n for (const header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n }\n\n invokeRPC<Req, Resp>(\n rpcName: string,\n request: Req,\n token: Token | null\n ): Promise<Resp> {\n const url = this.makeUrl(rpcName);\n\n return new Promise((resolve: Resolver<Resp>, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n log.debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(\n new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out')\n );\n break;\n case ErrorCode.HTTP_ERROR:\n const status = xhr.getStatus();\n log.debug(\n LOG_TAG,\n 'RPC \"' + rpcName + '\" failed with status:',\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n const responseError = (xhr.getResponseJson() as WebChannelError)\n .error;\n if (\n !!responseError &&\n !!responseError.status &&\n !!responseError.message\n ) {\n const firestoreErrorCode = mapCodeFromHttpResponseErrorStatus(\n responseError.status\n );\n reject(\n new FirestoreError(\n firestoreErrorCode,\n responseError.message\n )\n );\n } else {\n reject(\n new FirestoreError(\n Code.UNKNOWN,\n 'Server responded with status ' + xhr.getStatus()\n )\n );\n }\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n 'RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n }\n });\n\n // The database field is already encoded in URL. Specifying it again in\n // the body is not necessary in production, and will cause duplicate field\n // errors in the Firestore Emulator. Let's remove it.\n const jsonObj = ({ ...request } as unknown) as Indexable;\n delete jsonObj.database;\n\n const requestString = JSON.stringify(jsonObj);\n log.debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\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\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n const headers: StringMap = { 'Content-Type': 'text/plain' };\n\n this.modifyHeadersForRequest(headers, token);\n\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n request: Req,\n token: Token | null\n ): Promise<Resp[]> {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC<Req, Resp[]>(rpcName, request, token);\n }\n\n openStream<Req, Resp>(\n rpcName: string,\n token: Token | null\n ): Stream<Req, Resp> {\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const request: WebChannelOptions = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\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: true,\n supportsCrossDomainXhr: true,\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: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling\n };\n\n this.modifyHeadersForRequest(request.initMessageHeaders!, token);\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 //\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the httpHeadersOverwriteParam option to specify that\n // the headers should instead be encoded into a special \"$httpHeaders\" query\n // parameter, which is recognized by the webchannel backend. This is\n // formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32\n //\n // TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request\n // doesn't have an Origin header. So we have to exclude a few browser environments that are\n // known to (sometimes) not include an Origin. See\n // https://github.com/firebase/firebase-js-sdk/issues/1491.\n if (\n !isReactNative() &&\n !isElectron() &&\n !isIE() &&\n !isUWP() &&\n !isBrowserExtension()\n ) {\n request.httpHeadersOverwriteParam = '$httpHeaders';\n }\n\n const url = urlParts.join('');\n log.debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n const channel = webchannelTransport.createWebChannel(url, request);\n\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 opened = false;\n\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 let closed = false;\n\n const streamBridge = new StreamBridge<Req, Resp>({\n sendFn: (msg: Req) => {\n if (!closed) {\n if (!opened) {\n log.debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n log.debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n } else {\n log.debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: () => channel.close()\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 const unguardedEventListen = <T>(\n type: string,\n fn: (param?: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, (param: unknown) => {\n try {\n fn(param as T);\n } catch (e) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(WebChannel.EventType.OPEN, () => {\n if (!closed) {\n log.debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n\n unguardedEventListen(WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen<Error>(WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'The operation could not be completed'\n )\n );\n }\n });\n\n // WebChannel delivers message events as array. If batching is not enabled\n // (it's off by default) each message will be delivered alone, resulting in\n // a single element array.\n interface WebChannelResponse {\n data: Resp[];\n }\n\n unguardedEventListen<WebChannelResponse>(\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg!.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\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 msgDataOrError: WebChannelError | object = msgData;\n const error =\n msgDataOrError.error ||\n (msgDataOrError as WebChannelError[])[0]?.error;\n if (error) {\n log.debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const status: string = error.status;\n let code = mapCodeFromRpcStatus(status);\n let message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n log.debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\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 streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n }\n\n // visible for testing\n makeUrl(rpcName: string): string {\n const urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n return (\n this.baseUrl +\n '/' +\n RPC_URL_VERSION +\n '/projects/' +\n this.databaseId.projectId +\n '/databases/' +\n this.databaseId.database +\n '/documents:' +\n urlRpcName\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { Platform } from '../platform/platform';\nimport { Connection } from '../remote/connection';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { ConnectivityMonitor } from './../remote/connectivity_monitor';\n\nimport { NoopConnectivityMonitor } from '../remote/connectivity_monitor_noop';\nimport { BrowserConnectivityMonitor } from './browser_connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\nexport class BrowserPlatform implements Platform {\n readonly base64Available: boolean;\n\n readonly emptyByteString = '';\n\n constructor() {\n this.base64Available = typeof atob !== 'undefined';\n }\n\n get document(): Document | null {\n return typeof document !== 'undefined' ? document : null;\n }\n\n get window(): Window | null {\n return typeof window !== 'undefined' ? window : null;\n }\n\n loadConnection(databaseInfo: DatabaseInfo): Promise<Connection> {\n return Promise.resolve(new WebChannelConnection(databaseInfo));\n }\n\n newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\n }\n }\n\n newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\n }\n\n formatJSON(value: unknown): string {\n return JSON.stringify(value);\n }\n\n atob(encoded: string): string {\n return atob(encoded);\n }\n\n btoa(raw: string): string {\n return btoa(raw);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 { PlatformSupport } from '../platform/platform';\nimport { BrowserPlatform } from './browser_platform';\n\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nPlatformSupport.setPlatform(new BrowserPlatform());\n","/**\n * @license\n * Copyright 2017 Google Inc.\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 firebase from '@firebase/app';\nimport { configureForFirebase } from './src/platform/config';\nimport './src/platform_browser/browser_init';\n\nimport * as types from '@firebase/firestore-types';\nimport { FirebaseNamespace } from '@firebase/app-types';\n\nimport { name, version } from './package.json';\n\nexport function registerFirestore(instance: FirebaseNamespace): void {\n configureForFirebase(instance);\n instance.registerVersion(name, version);\n}\n\nregisterFirestore(firebase);\n\ndeclare module '@firebase/app-types' {\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"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","LogLevel","__assign","assign","t","s","i","n","arguments","length","call","apply","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","__generator","body","f","y","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","v","op","TypeError","pop","push","__spreadArrays","il","r","k","a","j","jl","defaultLogHandler","instance","logType","_i","args","logLevel","now","Date","toISOString","DEBUG","VERBOSE","console","log","name","INFO","info","WARN","warn","ERROR","error","Error","defaultLogLevel","Logger","_logLevel","val","_logHandler","getUA","navigator","code","message","_super","_this","FirebaseError","captureStackTrace","ErrorFactory","data","customData","fullCode","service","template","errors","replace","PATTERN","key","toString","replaceTemplate","fullMessage","serviceName","_b","keys","_a","slice","Component","mode","instantiationMode","multipleInstances","props","serviceProps","instanceFactory","type","goog","goog.global","goog.isNumber","goog.getObjectByName","opt_obj","parts","cur","goog.nullFunction","goog.typeOf","className","goog.isArray","goog.isArrayLike","goog.isObject","goog.UID_PROPERTY_","Math","goog.uidCounter_","fn","selfObj","var_args","goog.bindJs_","boundArgs","newArgs","goog.bind","Function","goog.bindNative_","goog.partial","goog.now","childCtor","parentCtor","tempCtor","childCtor.base","me","methodName","goog.Disposable","goog.Disposable.prototype.dispose","goog.Disposable.MONITORING_MODE","obj","goog.Disposable.prototype.disposeInternal","goog.array.indexOf","arr","opt_fromIndex","goog.isString","fromIndex","goog.array.forEach","l","arr2","goog.array.concat","goog.array.toArray","object","rv","goog.string.internal.isEmptyOrWhitespace","str","goog.labs.userAgent.util.userAgent_","goog.string.internal.trim","String","subString","goog.string.internal.compareElements_","left","right","goog.global.navigator","userAgent","A","goog.object.forEach","goog.object.clone","res","goog.object.PROTOTYPE_FIELDS_","target","source","goog.object.PROTOTYPE_FIELDS_.length","goog.reflect.sinkValue","x","goog.userAgent.VERSION","goog.userAgent.OPERA","goog.string.internal.contains","goog.userAgent.IE","goog.userAgent.EDGE","goog.userAgent.EDGE_OR_IE","goog.userAgent.GECKO","goog.userAgent.WEBKIT","doc","undefined","version","docMode","goog.userAgent.getDocumentMode_","parseFloat","Ia","Na","goog.userAgent.isVersionOrHigherCache_","valueFn","cacheObj","order","v1Subs","v2Subs","subCount","subIdx","v1Sub","v2Sub","v1Comp","v2Comp","parseInt","HAS_W3C_EVENT_SUPPORT","Number","goog.userAgent.DOCUMENT_MODE","SET_KEY_CODE_TO_PREVENT_DEFAULT","goog.userAgent.isVersionOrHigher","PASSIVE_EVENTS","goog.global.addEventListener","passive","options","get","goog.global.removeEventListener","goog.events.Event","opt_target","goog.events.BrowserEvent","opt_e","opt_currentTarget","goog.events.Event.call","init","relevantTouch","relatedTarget","MOUSEOVER","MOUSEOUT","goog.events.BrowserEvent.IE_POINTER_TYPE_MAP","goog.events.Event.prototype.preventDefault","goog.inherits","arg","2","TOUCH","3","PEN","4","MOUSE","goog.events.BrowserEvent.prototype.preventDefault","goog.events.BrowserEvent.superClass_.preventDefault.call","be","goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT","VK_F1","VK_F12","ex","goog.events.Listenable.IMPLEMENTED_BY_PROP","goog.events.ListenableKey.counter_","goog.events.Listener","listener","src","capture","opt_handler","proxy","goog.events.Listener.prototype.markAsRemoved","goog.events.ListenerMap","goog.events.ListenerMap.prototype.removeByKey","markAsRemoved","goog.events.ListenerMap.findListenerIndex_","listenerArray","opt_useCapture","opt_listenerScope","listenerObj","goog.events.ListenerMap.prototype.add","callOnce","typeStr","index","goog.events.LISTENER_MAP_PROP_","goog.events.onStringMap_","opt_options","goog.events.listenOnce","goog.events.wrapListener","goog.events.listen_","goog.events.listen","goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT","listenerMap","goog.events.getListenerMap_","goog.events.getProxy","proxyCallbackFunction","goog.events.handleBrowserEvent_","eventObject","goog.events.BrowserFeature.PASSIVE_EVENTS","goog.events.getOnString_","goog.events.unlistenByKey","removeByKey","goog.events.onString_","goog.events.fireListener","listenerFn","listenerHandler","opt_evt","evt","goog.events.LISTENER_WRAPPER_PROP_","goog.events.EventTarget","goog.Disposable.call","goog.events.EventTarget.prototype.fireListeners","unlistenByKey","G","goog.events.EventTarget.prototype.addEventListener","handler","opt_capture","opt_handlerScope","goog.events.EventTarget.prototype.removeEventListener","goog.events.unlisten","eventTargetListeners_","c","goog.events.EventTarget.prototype.dispatchEvent","ancestorsTree","ancestor","getParentEventTarget","actualEventTarget_","oldEvent","opt_ancestorsTree","currentTarget","fireListeners","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","reset","goog.async.WorkQueue","goog.async.FreeList","item","xb","goog.async.WorkQueue.freelist_","goog.async.WorkItem","goog.async.throwException","exception","goog.global.setTimeout","goog.async.run","callback","opt_context","goog.async.run.schedule_","promise","goog.global.Promise.resolve","goog.async.run.processWorkQueue","goog.async.run.initializeRunner_","goog.async.run.workQueueScheduled_","goog.async.WorkQueue.prototype.add","scope","goog.async.WorkQueue.freelist_.get","goog.async.WorkItem.prototype.set","goog.async.WorkItem.prototype.reset","goog.async.run.workQueue_","goog.async.WorkQueue.prototype.remove","goog.async.run.workQueue_.remove","put","goog.async.WorkQueue.freelist_.put","goog.Timer","opt_interval","opt_timerObject","goog.events.EventTarget.call","goog.Timer.prototype.stop","opt_delay","goog.async.Throttle","interval","goog.async.Throttle.prototype.doAction_","goog.Timer.callOnce","goog.events.EventHandler","opt_scope","Cb","goog.Timer.prototype.tick_","elapsed","goog.Timer.intervalScale","dispatchTick","goog.Timer.TICK","stop","goog.Timer.prototype.start","goog.Timer.prototype","goog.Timer.prototype.disposeInternal","goog.Timer.superClass_.disposeInternal.call","Fb","goog.async.Throttle.prototype.fire","doAction_","goog.async.Throttle.prototype.disposeInternal","goog.async.Throttle.superClass_.disposeInternal.call","goog.global.clearTimeout","goog.async.Throttle.prototype.onTimer_","goog.events.EventHandler.typeArray_","goog.events.EventHandler.prototype.listen_","opt_fn","self","goog.events.EventHandler.prototype.removeAll","goog.labs.net.webChannel.WebChannelDebug","goog.events.EventHandler.prototype.disposeInternal","goog.events.EventHandler.superClass_.disposeInternal.call","removeAll","goog.events.EventHandler.prototype.handleEvent","goog.labs.net.webChannel.requestStats.statEventTarget_","goog.labs.net.webChannel.requestStats.Event.SERVER_REACHABILITY_EVENT","reachabilityType","goog.labs.net.webChannel.requestStats.statEventTarget_.dispatchEvent","goog.labs.net.webChannel.requestStats.ServerReachabilityEvent","requestStats.StatEvent","eventTarget","goog.labs.net.webChannel.requestStats.Event.STAT_EVENT","stat","goog.labs.net.webChannel.requestStats.StatEvent","requestStats.TimingEvent","goog.labs.net.webChannel.requestStats.Event.TIMING_EVENT","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","goog.net.XmlHttpFactory.prototype.getOptions","cachedOptions_","goog.net.WebChannel","Wb","goog.net.WebChannel.EventType","OPEN","CLOSE","MESSAGE","goog.labs.net.webChannel.ChannelRequest","channel","opt_requestId","opt_retryId","goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_","EDGE_POLLING_INTERVAL_","goog.net.WebChannel.MessageEvent","goog.net.WebChannel.ErrorEvent","goog.net.DefaultXmlHttpFactory","factory","goog.labs.net.webChannel.ChannelRequest.INVALID_CHUNK_","goog.labs.net.webChannel.ChannelRequest.INCOMPLETE_CHUNK_","ChannelRequest.prototype.xmlHttpPost","uri","postData","XML_HTTP","makeUnique","clone","decodeChunks","sendXmlHttp_","ChannelRequest.prototype.xmlHttpGet","hostPrefix","ChannelRequest.prototype.sendXmlHttp_","ensureWatchDogTimer_","headers","REQUEST_MADE","ChannelRequest.prototype.decodeNextChunks_","readyState","responseText","decodeNextChunksSuccessful","chunkText","getNextChunk_","BAD_DATA","goog.labs.net.webChannel.requestStats.notifyStatEvent","REQUEST_INCOMPLETE_DATA","REQUEST_BAD_DATA","safeOnRequestData_","NO_DATA","REQUEST_NO_DATA","cleanup_","dispatchFailure_","ChannelRequest.prototype.getNextChunk_","sizeStartIndex","sizeEndIndex","isNaN","size","chunkStartIndex","ChannelRequest.prototype.ensureWatchDogTimer_","startWatchDogTimer_","ChannelRequest.prototype.startWatchDogTimer_","time","goog.labs.net.webChannel.requestStats.setTimeout","ChannelRequest.prototype.cancelWatchDogTimer_","ChannelRequest.prototype.dispatchFailure_","ChannelRequest.prototype.cleanup_","cancelWatchDogTimer_","readyStateChangeThrottle_","xmlhttp","ChannelRequest.prototype.safeOnRequestData_","goog.labs.net.webChannel.requestStats.notifyServerReachabilityEvent","BACK_CHANNEL_ACTIVITY","goog.structs.forEach","col","goog.structs.getValues","values","goog.structs.Map","opt_map","argLength","addAll","goog.structs.Map.prototype.remove","goog.structs.Map.hasKey_","cleanupKeysArray_","goog.structs.Map.prototype.cleanupKeysArray_","srcIndex","destIndex","seen","M","ChannelRequest.prototype.setTimeout","timeout","goog.labs.net.webChannel.ChannelRequest.prototype","ChannelRequest.prototype.readyStateChangeHandler_","xhr","throttle","INTERACTIVE","getReadyState","ChannelRequest.prototype.xmlHttpHandler_","onXmlHttpReadyStateChanged_","errorCode","statusCode","REQUEST_FAILED","REQUEST_SUCCEEDED","status","getStreamingResponseHeader","goog.net.WebChannel.X_HTTP_INITIAL_RESPONSE","initialResponse","UNKNOWN_SESSION_ID","REQUEST_UNKNOWN_SESSION_ID","decodeNextChunks_","listen_","STATUS","REQUEST_BAD_STATUS","ChannelRequest.prototype.pollResponse_","ChannelRequest.prototype.cancel","ChannelRequest.prototype.onWatchDogTimeout_","CLOSE_REQUEST","handleTimeout_","REQUEST_TIMEOUT","Q","goog.structs.Map.prototype.getValues","goog.structs.Map.prototype.getKeys","goog.structs.Map.prototype","goog.structs.Map.prototype.get","opt_val","goog.structs.Map.prototype.set","goog.structs.Map.prototype.forEach","goog.uri.utils.splitRe_","goog.Uri","opt_uri","opt_ignoreCase","m","setScheme","setUserInfo","setDomain","setPort","setPath","setQueryData","setFragment","SCHEME","goog.Uri.decodeOrEmpty_","USER_INFO","DOMAIN","PORT","PATH","QUERY_DATA","FRAGMENT","goog.Uri.QueryData","goog.Uri.prototype.clone","goog.Uri.prototype.setScheme","newScheme","opt_decode","goog.Uri.prototype.setDomain","newDomain","goog.Uri.prototype.setPort","newPort","goog.Uri.prototype.setQueryData","queryData","goog.Uri.QueryData.prototype.setIgnoreCase","ignoreCase","ensureKeyMapInitialized_","invalidateCache_","lowerCase","remove","setValues","setIgnoreCase","goog.Uri.encodeSpecialChars_","goog.Uri.reDisallowedInQuery_","goog.Uri.prototype.setParameterValue","goog.Uri.prototype.setParameterValues","goog.Uri.prototype.makeUnique","setParameterValue","RANDOM","opt_preserveReserved","decodeURI","decodeURIComponent","unescapedPart","extra","opt_removeDoubleEncoding","encoded","encodeURI","goog.Uri.encodeChar_","ch","goog.Uri.prototype.toString","out","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_","goog.Uri.prototype.resolve","relativeUri","absoluteUri","overridden","hasPath","lastSlashIndex","leadingSlash","prefix","pos","segments","segment","opt_query","goog.Uri.QueryData.prototype.ensureKeyMapInitialized_","encodedQuery","pairs","indexOfEquals","goog.uri.utils.parseQueryData","goog.Uri.QueryData.prototype.remove","getKeyName_","goog.Uri.QueryData.prototype.containsKey","goog.Uri.QueryData.prototype.setValues","goog.Uri.QueryData.prototype.clone","goog.Uri.QueryData.prototype.getKeyName_","keyName","goog.labs.net.webChannel.BaseTestChannel","BaseTestChannel.prototype.checkBufferingProxy_","bufferingProxyResult","TEST_STAGE_TWO_START","PROXY","testConnectionFinished","NOPROXY","createDataUri","channel_","recvDataUri","param","goog.labs.net.webChannel.ConnectionState","goog.structs.Set","goog.structs.Set.getKey_","Wire.QueuedMap","mapId","map","ForwardChannelRequestPool","opt_maxPoolSize","module$contents$goog$labs$net$webChannel$ForwardChannelRequestPool_ForwardChannelRequestPool.MAX_POOL_SIZE_","entrys","goog.global.performance.getEntriesByType","goog.global.chrome","goog.global.chrome.loadTimes","Ac","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","sb","encodedKey","goog.debug.TextFormatter","goog.debug.Formatter","Sc","goog.labs.net.webChannel.BaseTestChannel.prototype","BaseTestChannel.prototype.createXhrIo","BaseTestChannel.prototype.abort","BaseTestChannel.prototype.isClosed","BaseTestChannel.prototype.onRequestData","req","INIT","applyControlHeaders_","protocolHeader","goog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL","httpSessionIdHeader","goog.net.WebChannel.X_HTTP_SESSION_ID","respArray","testChannel","signalError_","CONNECTION_TESTING","TEST_STAGE_TWO_DATA_TWO","TEST_STAGE_TWO_DATA_ONE","documentMode","TEST_STAGE_TWO_DATA_BOTH","BaseTestChannel.prototype.onRequestComplete","checkBufferingProxy_","TEST_STAGE_ONE_FAILED","TEST_STAGE_TWO_FAILED","BaseTestChannel.prototype.shouldUseSecondaryDomains","BaseTestChannel.prototype.isActive","goog.structs.Set.prototype.add","element","goog.structs.Set.prototype.getValues","ForwardChannelRequestPool.prototype.applyClientProtocol","clientProtocol","addRequest","ForwardChannelRequestPool.prototype.isFull","ForwardChannelRequestPool.prototype.getRequestCount","ForwardChannelRequestPool.prototype.hasRequest","Zc","ForwardChannelRequestPool.prototype.addRequest","ForwardChannelRequestPool.prototype.removeRequest","requestPool_","ForwardChannelRequestPool.prototype.getPendingMessages","goog.json.NativeJsonProcessor","goog.labs.net.webChannel.WireV8","WireV8.prototype.encodeMessage","buffer","opt_prefix","encodedValue","netUtils.imageCallback_","channelDebug","img","debugText","ForwardChannelRequestPool.prototype.cancel","getPendingMessages","goog.structs.Map.prototype.clear","clear","goog.json.NativeJsonProcessor.prototype.stringify","opt_replacer","goog.json.NativeJsonProcessor.prototype.parse","opt_reviver","goog.json.hybrid.parse","goog.net.XhrIo","opt_xmlHttpFactory","goog.net.XhrIo.ResponseType.DEFAULT","DEFAULT","goog.net.XhrIo.HTTP_SCHEME_PATTERN","goog.net.XhrIo.METHODS_WITH_FORM_DATA","goog.net.XhrIo.isContentTypeHeader_","header","goog.net.XhrIo.prototype.error_","err","dispatchErrors_","cleanUpXhr_","goog.net.XhrIo.prototype.dispatchErrors_","goog.net.XhrIo.prototype.onReadyStateChangeHelper_","LOCAL_REQUEST_ERROR","isComplete","isSuccess","OK","CREATED","ACCEPTED","NO_CONTENT","PARTIAL_CONTENT","NOT_MODIFIED","QUIRK_IE_NO_CONTENT","goog.global.self","goog.global.self.location","protocol","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_","goog.net.XhrIo.prototype.getReadyState","UNINITIALIZED","goog.net.XhrIo.prototype.getStreamingResponseHeader","exports.setHttpHeadersWithOverwriteParam","url","urlParam","extraHeaders","exports.generateHttpHeadersOverwriteParam","module$exports$goog$net$rpc$HttpCors.generateHttpHeadersOverwriteParam","httpHeaders","hashIndex","questionIndex","goog.labs.net.webChannel.WebChannelBase","WebChannelBase.prototype.disconnect","cancelRequests_","OPENED","rid","addAdditionalParams_","request","goog.global.navigator.sendBeacon","requestSent","goog.global.Image","Image","onClose_","WebChannelBase.prototype.cancelRequests_","clearDeadBackchannelTimer_","clearForwardChannelTimer_","WebChannelBase.prototype.sendMap","goog.labs.net.webChannel.Wire.QueuedMap","ensureForwardChannel_","WebChannelBase.prototype.ensureForwardChannel_","isFull","WebChannelBase.prototype.makeForwardChannelRequest_","opt_retryRequest","module$exports$goog$net$rpc$HttpCors.setHttpHeadersWithOverwriteParam","requeuePendingMaps_","dequeueOutgoingMaps_","goog.labs.net.webChannel.WebChannelBase.MAX_MAPS_PER_REQUEST_","requestText","WebChannelBase.prototype.addAdditionalParams_","params","WebChannelBase.prototype.dequeueOutgoingMaps_","maxNum","count","badMapHandler","outgoingMaps_","offset","messageQueue","encodeMessage","pendingMessages","WebChannelBase.prototype.ensureBackChannel_","WebChannelBase.prototype.maybeRetryBackChannel_","goog.labs.net.webChannel.WebChannelBase.BACK_CHANNEL_MAX_RETRIES","getRetryTime_","WebChannelBase.prototype.testConnectionFinished","useChunked","applyClientProtocol","connectChannel_","WebChannelBase.prototype.clearDeadBackchannelTimer_","WebChannelBase.prototype.getRetryTime_","retryCount","retryTime","goog.labs.net.webChannel.WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR","WebChannelBase.prototype.signalError_","imageUri","goog.global.location","goog.global.location.protocol","netUtils.testLoadImage","goog.labs.net.webChannel.netUtils.imageCallback_","goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT","ERROR_OTHER","CLOSED","onError_","WebChannelBase.prototype.onClose_","WebChannelBase.prototype.createDataUri","goog.Uri.parse","hostName","locationPage","goog.Uri.create","opt_scheme","opt_domain","opt_port","opt_path","getHttpSessionIdParam","getHttpSessionId","goog.labs.net.webChannel.WebChannelBaseTransport","goog.string.path.join","suffix","messageHeaders","goog.net.WebChannel.X_CLIENT_PROTOCOL","goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL","initHeaders","goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE","goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE","httpHeadersOverwriteParam","httpSessionIdParam","messageUrlParams_","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.Handler_","array","goog.net.WebChannel.MessageEvent.call","metadata","metadataKey","goog.net.WebChannel.ErrorEvent.call","NETWORK_ERROR","X","goog.net.XhrIo.prototype.send","opt_method","opt_content","opt_headers","method","XMLHttpRequest","getOptions","goog.net.XmlHttp.factory_.getOptions","error_","content","goog.array.find","contentTypeKey","contentIsFormData","goog.net.XhrIo.CONTENT_TYPE_HEADER","goog.net.XhrIo.FORM_CONTENT_TYPE","goog.net.XhrIo.shouldUseXhr2Timeout_","goog.net.XhrIo.prototype","goog.net.XhrIo.prototype.timeout_","goog.net.XhrIo.prototype.abort","opt_failureCode","goog.net.XhrIo.prototype.disposeInternal","goog.net.XhrIo.prototype.onReadyStateChange_","isDisposed","onReadyStateChangeHelper_","goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.getStatus","goog.net.XhrIo.prototype.getResponseText","goog.net.XhrIo.prototype.getResponseJson","opt_xssiPrefix","goog.net.XhrIo.prototype.getLastErrorCode","goog.net.XhrIo.prototype.getLastError","Ad","goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION","goog.labs.net.webChannel.WebChannelBase.prototype","WebChannelBase.prototype.isClosed","WebChannelBase.prototype.onStartForwardChannelTimer_","startForwardChannel_","goog.object.extend","total","goog.labs.net.webChannel.Wire.RAW_DATA_KEY","goog.labs.net.webChannel.WebChannelBase.MAX_CHARS_PER_GET_","goog.net.WebChannelTransport.CLIENT_VERSION","xmlHttpPost","OPENING","makeForwardChannelRequest_","WebChannelBase.prototype.onStartBackChannelTimer_","startBackChannel_","readyStateChangeThrottleMs_","WebChannelBase.prototype.onRequestData","hasRequest","response","handlePostResponse_","goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE","BACKCHANNEL_MISSING","responseValues","goog.labs.net.webChannel.WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF","getRequestCount","onForwardChannelFlushed_","BAD_RESPONSE","nextArray","onInput_","negotiatedVersion","serverKeepaliveMs","removeRequest","backChannelRequestTimeoutMs_","opt_timeout","ensureBackChannel_","STOP","disconnect","WebChannelBase.prototype.onBackChannelDead_","maybeRetryBackChannel_","BACKCHANNEL_DEAD","WebChannelBase.prototype.onRequestComplete","BACK_CHANNEL","FORWARD_CHANNEL","rtt","lastError","WebChannelBase.prototype.maybeRetryForwardChannel_","getForwardChannelMaxRetries","maybeRetryForwardChannel_","forwardChannelRequestPool_","WebChannelBase.prototype.testNetworkCallback_","networkUp","ERROR_NETWORK","WebChannelBase.prototype.createXhrIo","WebChannelBase.prototype.isActive","WebChannelBase.prototype.shouldUseSecondaryDomains","Od","WebChannelBase.Handler.prototype.channelOpened","WebChannelBase.Handler.prototype.channelHandleArray","WebChannelBase.Handler.prototype.channelError","WebChannelBase.Handler.prototype.channelClosed","WebChannelBase.Handler.prototype.badMapError","WebChannelBaseTransport.prototype.createWebChannel","goog.labs.net.webChannel.WebChannelBaseTransport.Channel","Y","WebChannelBaseTransport.Channel.prototype.addEventListener","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.superClass_.addEventListener.call","WebChannelBaseTransport.Channel.prototype.removeEventListener","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.superClass_.removeEventListener.call","WebChannelBaseTransport.Channel.prototype.open","supportCrossDomain","testUrl_","url_","CONNECT_ATTEMPT","channelPath","opt_extraParams","connectTest_","testPath","urlPath","TEST_STAGE_ONE_START","handshakeResult","setParameterValues","sendDataUri","xmlHttpGet","WebChannelBaseTransport.Channel.prototype.close","WebChannelBaseTransport.Channel.prototype.send","rawJson","sendMap","WebChannelBaseTransport.Channel.prototype.disposeInternal","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","goog.net.createWebChannelTransport","goog.functions.create","temp","createWebChannelTransport","ErrorCode","EventType","WebChannel","XhrIo","SDK_VERSION","firebase","__PRIVATE_logClient","__PRIVATE_FirebaseLogLevel","SILENT","setLogLevel","__PRIVATE_newLevel","debug","tag","msg","platform","__PRIVATE_PlatformSupport","fail","__PRIVATE_failure","assert","__PRIVATE_assertion","__PRIVATE_chars","__PRIVATE_autoId","__PRIVATE_i","charAt","floor","random","isEqual","__PRIVATE_databaseId","persistenceKey","host","ssl","forceLongPolling","__PRIVATE_DEFAULT_DATABASE_NAME","database","__PRIVATE_DatabaseId","other","projectId","__PRIVATE_primitiveComparator","OnlineState","OnlineStateSource","user","Authorization","uid","User","__PRIVATE_otherUser","Code","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","UNAUTHENTICATED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","__PRIVATE_EmptyCredentialsProvider","__PRIVATE_changeListener","__PRIVATE_FirebaseCredentialsProvider","__PRIVATE_initialTokenCounter","forceRefresh","auth","getToken","__PRIVATE_tokenData","FirestoreError","accessToken","currentUser","removeAuthTokenListener","V","__PRIVATE_currentUid","getUid","X-Goog-AuthUser","__PRIVATE_authHeader","__PRIVATE_FirstPartyCredentialsProvider","__PRIVATE_gapi","__PRIVATE_sessionIndex","__PRIVATE_authProvider","getImmediate","optional","addAuthTokenListener","contains","defaultValue","num","forEach","functionName","__PRIVATE_formatPlural","__PRIVATE_numberOfArgs","__PRIVATE_minNumberOfArgs","__PRIVATE_maxNumberOfArgs","position","__PRIVATE_argument","__PRIVATE_validateType","__PRIVATE_ordinal","__PRIVATE_validateArgType","__PRIVATE_optionName","__PRIVATE_validateNamedType","__PRIVATE_inputName","input","__PRIVATE_expected","__PRIVATE_expectedDescription","__PRIVATE_valueDescription","__PRIVATE_actualDescription","join","__PRIVATE_isPlainObject","description","getPrototypeOf","substring","JSON","stringify","__PRIVATE_customObjectName","results","exec","__PRIVATE_optionNames","obj.forEach","__PRIVATE__","indexOf","GeoPoint","Timestamp","fromMillis","date","getTime","milliseconds","seconds","toMillis","nanoseconds","__PRIVATE_SnapshotVersion","MIN","timestamp","__PRIVATE_BasePath","__PRIVATE_nameOrPath","limit","__PRIVATE_segment","__PRIVATE_potentialChild","end","p1","p2","__PRIVATE_len","min","ResourcePath","split","filter","__PRIVATE_identifierRegExp","FieldPath","test","__PRIVATE_current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","collectionId","__PRIVATE_DocumentKey","k1","k2","root","__PRIVATE_LLRBNode","__PRIVATE_SortedMap","node","cmp","__PRIVATE_prunedNodes","action","__PRIVATE_descriptions","color","__PRIVATE_comparator","EMPTY","__PRIVATE_smallest","__PRIVATE_nl","RED","__PRIVATE_nr","__PRIVATE_blackDepth","pow","__PRIVATE_LLRBEmptyNode","__PRIVATE_startKey","__PRIVATE_isReverse","latitude","longitude","__PRIVATE_validateExactNumberOfArgs","isFinite","add","__PRIVATE_SortedSet","__PRIVATE_elem","cb","range","__PRIVATE_iter","start","has","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","previousValue","__PRIVATE_localWriteTime","__PRIVATE_transformResult","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_coercedFieldValuesArray","find","elements","ArrayValue","__PRIVATE_misc.__PRIVATE_arrayEquals","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_baseValue","__PRIVATE_sum","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","transformResults","fields","__PRIVATE_fieldsAsSet","fieldPath","found","__PRIVATE_fieldMaskPath","__PRIVATE_FieldMask","FieldTransform","field","transform","MutationType","Precondition","exists","updateTime","__PRIVATE_maybeDoc","Document","__PRIVATE_mutationResult","hasCommittedMutations","__PRIVATE_baseDoc","__PRIVATE_Mutation","vn","__PRIVATE_SetMutation","__PRIVATE_newData","__PRIVATE_PatchMutation","__PRIVATE_ObjectValue","newValue","set","delete","__PRIVATE_baseObject","fieldTransforms","__PRIVATE_existingValue","__PRIVATE_fieldTransform","__PRIVATE_coercedValue","__PRIVATE_TransformMutation","__PRIVATE_serverTransformResults","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_precondition","__PRIVATE_MutationType","__PRIVATE_fieldMask","Set","TypeOrder","ServerTimestampBehavior","timestampsInSnapshots","serverTimestamps","__PRIVATE_ServerTimestampBehavior","FieldValue","__PRIVATE_NullValue","__PRIVATE_BooleanValue","__PRIVATE_NumberValue","__PRIVATE_internalValue","__PRIVATE_TypeOrder","__PRIVATE_serverTimestampBehavior","__PRIVATE_IntegerValue","__PRIVATE_numericEquals","__PRIVATE_DoubleValue","NaN","Infinity","__PRIVATE_StringValue","__PRIVATE_TimestampValue","toDate","__PRIVATE_ServerTimestampValue","__PRIVATE_BlobValue","__PRIVATE_RefValue","__PRIVATE_GeoPointValue","__PRIVATE_it1","__PRIVATE_it2","__PRIVATE_next1","__PRIVATE_next2","to","child","newChild","__PRIVATE_pathSegment","__PRIVATE_currentPath","__PRIVATE_nestedFields","__PRIVATE_nestedPath","__PRIVATE_childName","minLength","reduce","__PRIVATE_totalSize","__PRIVATE_d1","__PRIVATE_d2","Map","__PRIVATE_canonicalPath","__PRIVATE_fieldValue","__PRIVATE_protoValue","converter","result_1","proto","mapValue","v1","v2","__PRIVATE_NoDocument","__PRIVATE_UnknownDocument","__PRIVATE_NumberAsAny","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","isInteger","__PRIVATE_objectValue","isSafeInteger","Target","canonicalId","collectionGroup","filters","_c","orderBy","__PRIVATE_isNullOrUndefined","startAt","endAt","LimitType","Query","__PRIVATE_inequalityField","__PRIVATE_firstOrderByField","__PRIVATE_foundKeyOrdering","__PRIVATE_lastDirection","dir","__PRIVATE_Direction","ASCENDING","FieldFilter","__PRIVATE_newFilters","concat","__PRIVATE_newOrderBy","__PRIVATE_LimitType","bound","__PRIVATE_comparedOnKeyField","__PRIVATE_comp","compare","__PRIVATE_operators","__PRIVATE_orderBys","DESCENDING","before","__PRIVATE_docPath","matches","__PRIVATE_Operator","LESS_THAN","LESS_THAN_OR_EQUAL","EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","ARRAY_CONTAINS","IN","ARRAY_CONTAINS_ANY","every","__PRIVATE_comparison","__PRIVATE_KeyFieldFilter","__PRIVATE_refValue","__PRIVATE_KeyFieldInFilter","some","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","arrayValue","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_lhsElem","__PRIVATE_Bound","__PRIVATE_orderByComponent","component","__PRIVATE_docValue","__PRIVATE_thisPosition","__PRIVATE_otherPosition","__PRIVATE_OrderBy","__PRIVATE_KEY_ORDERING_ASC","__PRIVATE_KEY_ORDERING_DESC","__PRIVATE_explicitOrderBy","__PRIVATE_limitType","TargetPurpose","sequenceNumber","lastLimboFreeSnapshotVersion","resumeToken","__PRIVATE_snapshotVersion","__PRIVATE_TargetData","ExistenceFilter","__PRIVATE_purpose","log.error","__PRIVATE_RpcCode","RpcCode","__PRIVATE_EMPTY_MAYBE_DOCUMENT_MAP","__PRIVATE_maybeDocumentMap","__PRIVATE_EMPTY_DOCUMENT_MAP","__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP","__PRIVATE_EMPTY_DOCUMENT_KEY_SET","keys_1","__PRIVATE_EMPTY_TARGET_ID_SET","__PRIVATE_oldSet","__PRIVATE_DocumentSet","__PRIVATE_thisDoc","__PRIVATE_otherDoc","__PRIVATE_docStrings","__PRIVATE_keyedMap","__PRIVATE_sortedSet","__PRIVATE_newSet","__PRIVATE_documentMap","ChangeType","SyncState","__PRIVATE_updatedTargetIds","removedTargetIds","__PRIVATE_newDoc","__PRIVATE_existenceFilter","__PRIVATE_DocumentChangeSet","__PRIVATE_change","__PRIVATE_oldChange","__PRIVATE_ChangeType","__PRIVATE_changes","documents","__PRIVATE_mutatedKeys","fromCache","__PRIVATE_ViewSnapshot","docs","docChanges","__PRIVATE_otherChanges","__PRIVATE_targetChanges","TargetChange","__PRIVATE_targetIdSet","__PRIVATE_documentKeySet","__PRIVATE_emptyByteString","__PRIVATE_addedDocuments","__PRIVATE_modifiedDocuments","__PRIVATE_removedDocuments","__PRIVATE_targetMismatches","__PRIVATE_documentUpdates","__PRIVATE_resolvedLimboDocuments","__PRIVATE_oldDocs","__PRIVATE_syncStateChanged","__PRIVATE_excludesMetadataChanges","WatchTargetChangeState","state","targetIds","cause","__PRIVATE_TargetState","__PRIVATE_changeType","__PRIVATE_snapshotChangesMap","__PRIVATE_docChange","targetChange","__PRIVATE_targetState","__PRIVATE_WatchTargetChangeState","removeTarget","__PRIVATE_objUtils.__PRIVATE_forEachNumber","__PRIVATE_watchChange","__PRIVATE_expectedCount","__PRIVATE_targetData","__PRIVATE_targets","__PRIVATE_isOnlyLimboTarget","__PRIVATE_TargetPurpose","__PRIVATE_remoteEvent","__PRIVATE_documentTargetMap","document","__PRIVATE_updatedDocument","__PRIVATE_WatchChangeAggregator","__PRIVATE_targetMapping","__PRIVATE_targetActive","__PRIVATE_metadataProvider","__PRIVATE_dirs","__PRIVATE_ops","__PRIVATE_DIRECTIONS","__PRIVATE_OPERATORS","__PRIVATE_ISO_REG_EXP","RegExp","__PRIVATE_typeUtils.__PRIVATE_isNullOrUndefined","Uint8Array","__PRIVATE_byteString","__PRIVATE_mapCodeFromRpcCode","nanos","__PRIVATE_parseInt64","__PRIVATE_utc","__PRIVATE_fraction","__PRIVATE_nanoStr","substr","bytes","toBase64","toUint8Array","blob","Blob","fromBase64String","fromUint8Array","__PRIVATE_JsonProtoSerializer","__PRIVATE_resource","__PRIVATE_resourceName","__PRIVATE_fieldValue.__PRIVATE_NullValue","nullValue","__PRIVATE_fieldValue.__PRIVATE_BooleanValue","booleanValue","__PRIVATE_fieldValue.__PRIVATE_IntegerValue","integerValue","__PRIVATE_fieldValue.__PRIVATE_DoubleValue","doubleValue","__PRIVATE_fieldValue.__PRIVATE_StringValue","stringValue","__PRIVATE_fieldValue.__PRIVATE_ObjectValue","__PRIVATE_fieldValue.ArrayValue","__PRIVATE_fieldValue.__PRIVATE_TimestampValue","timestampValue","__PRIVATE_fieldValue.__PRIVATE_GeoPointValue","geoPointValue","__PRIVATE_fieldValue.__PRIVATE_BlobValue","bytesValue","__PRIVATE_fieldValue.__PRIVATE_RefValue","referenceValue","of","POSITIVE_INFINITY","NEGATIVE_INFINITY","__PRIVATE_assertPresent","__PRIVATE_dbId","fromVersion","missing","readTime","documentChange","toVersion","documentDelete","documentRemove","__PRIVATE_mapRpcCodeFromCode","targetChangeType","__PRIVATE_causeProto","__PRIVATE_entityChange","__PRIVATE_docDelete","__PRIVATE_docRemove","__PRIVATE_mutation","update","updateMask","verify","currentDocument","NONE","commitTime","__PRIVATE_protos","setToServerValue","appendMissingElements","removeAllFromArray","increment","__PRIVATE_fieldValue.__PRIVATE_NumberValue","__PRIVATE_documentsTarget","structuredQuery","parent","from","allDescendants","where","__PRIVATE_fromCount","__PRIVATE_filterBy","goog-listen-tags","compositeFilter","unaryFilter","fieldFilter","__PRIVATE_accum","cursor","__PRIVATE_fieldReference","direction","__PRIVATE_nanField","__PRIVATE_nullField","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_cls","__PRIVATE_optionalMessage","__PRIVATE_staticProperty","__PRIVATE_PublicConstructor","base64","__PRIVATE_assertBase64Available","atob","__PRIVATE_assertUint8ArrayAvailable","__PRIVATE_invalidClassError","char","fromCharCode","btoa","charCodeAt","__PRIVATE_PublicBlob","__PRIVATE_makeConstructorPrivate","__PRIVATE_ObjectMap","id","matches_1","__PRIVATE_otherKey","splice","__PRIVATE_objUtil.forEach","entries","entries_1","__PRIVATE_objUtil.__PRIVATE_isEmpty","__PRIVATE_docKey","__PRIVATE_batchResult","__PRIVATE_mutationResults","mutations","baseMutations","__PRIVATE_maybeDocs","__PRIVATE_mutatedDocuments","__PRIVATE_m","__PRIVATE_mutatedDocument","__PRIVATE_MutationBatch","batchId","__PRIVATE_MutationBatchResult","batch","__PRIVATE_commitVersion","streamToken","__PRIVATE_versionMap","__PRIVATE_documentVersionMap","ref","__PRIVATE_emptyKey","__PRIVATE_startRef","__PRIVATE_endRef","__PRIVATE_firstRef","PersistencePromise","__PRIVATE_nextFn","__PRIVATE_catchFn","all","__PRIVATE_resolvedCount","__PRIVATE_err","__PRIVATE_predicates","predicate","__PRIVATE_isTrue","collection","__PRIVATE_promises","__PRIVATE_RemoteDocumentChangeBuffer","__PRIVATE_maybeDocument","transaction","__PRIVATE_documentKey","__PRIVATE_bufferedEntry","__PRIVATE_documentKeys","__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG","__PRIVATE_batches","__PRIVATE_inBatches","__PRIVATE_nullableMaybeDocumentMap","__PRIVATE_localView","getEntries","__PRIVATE_baseDocs","__PRIVATE_sinceReadTime","__PRIVATE_parents","__PRIVATE_collectionQuery","__PRIVATE_mutationBatches","__PRIVATE_queryResults","__PRIVATE_matchingMutationBatches","__PRIVATE_mergedDocuments","__PRIVATE_mutatedDoc","__PRIVATE_existingDocuments","__PRIVATE_missingBaseDocEntriesForPatching","__PRIVATE_missingBaseDocs","__PRIVATE_viewSnapshot","__PRIVATE_addedKeys","__PRIVATE_removedKeys","__PRIVATE_externalPreviousValue","max","__PRIVATE_ListenSequence","__PRIVATE_nextValue","__PRIVATE_sequenceNumberSyncer","__PRIVATE_remoteDocumentCache","__PRIVATE_mutationQueue","__PRIVATE_indexManager","__PRIVATE_targetOrBatchId","__PRIVATE_DocReference","__PRIVATE_docVersions","__PRIVATE_mapKeyFn","__PRIVATE_binaryString","TimerId","__PRIVATE_asyncQueue","__PRIVATE_timerId","__PRIVATE_delayMs","__PRIVATE_removalCallback","__PRIVATE_delayedOp","__PRIVATE_DelayedOperation","setTimeout","reason","clearTimeout","enqueue","__PRIVATE_AsyncQueue","__PRIVATE_newTail","catch","stack","__PRIVATE_removedOp","__PRIVATE_lastTimerId","__PRIVATE_TimerId","sort","__PRIVATE_targetTimeMs","bind","__PRIVATE_aSequence","__PRIVATE_aIndex","__PRIVATE_bSequence","__PRIVATE_bIndex","__PRIVATE_seqCmp","__PRIVATE_entry","__PRIVATE_highestValue","last","__PRIVATE_bufferEntryComparator","__PRIVATE_RollingSequenceNumberBuffer","__PRIVATE_GC_DID_NOT_RUN","Io","To","Eo","Ro","__PRIVATE_cacheSize","__PRIVATE_LruParams","__PRIVATE_LruScheduler","cancel","delay","log.debug","txn","__PRIVATE_percentile","targetCount","maxValue","upperBound","activeTargetIds","__PRIVATE_upperBoundSequenceNumber","__PRIVATE_sequenceNumbersToCollect","__PRIVATE_targetsRemoved","__PRIVATE_countedTargetsTs","__PRIVATE_foundUpperBoundTs","__PRIVATE_removedTargetsTs","__PRIVATE_removedDocumentsTs","__PRIVATE_startTs","__PRIVATE_sequenceNumbers","__PRIVATE_numTargetsRemoved","__PRIVATE_documentsRemoved","log.__PRIVATE_getLogLevel","log.LogLevel","__PRIVATE_LOG_TAG","__PRIVATE_LocalStore","__PRIVATE_newMutationQueue","__PRIVATE_newLocalDocuments","persistence","runTransaction","__PRIVATE_oldBatches","__PRIVATE_promisedOldBatches","__PRIVATE_newBatches","__PRIVATE_removedBatchIds","__PRIVATE_addedBatchIds","__PRIVATE_changedKeys","_e","_d","__PRIVATE_affectedDocuments","bh","yh","_h","__PRIVATE_existingDocs","mutations_1","Hu","__PRIVATE_affected","__PRIVATE_documentBuffer","Ph","__PRIVATE_affectedKeys","__PRIVATE_remoteVersion","__PRIVATE_newTargetDataByTargetMap","__PRIVATE_oldTargetData","__PRIVATE_newTargetData","__PRIVATE_changedDocs","__PRIVATE_updatedKeys","__PRIVATE_existingDoc","hasPendingWrites","__PRIVATE_updateRemoteVersion","lastRemoteSnapshotVersion","__PRIVATE_viewChanges","__PRIVATE_viewChange","__PRIVATE_updatedTargetData","__PRIVATE_afterBatchId","__PRIVATE_cached","__PRIVATE_keepPersistedTargetData","__PRIVATE_removed","__PRIVATE_usePreviousResults","__PRIVATE_remoteKeys","rc","networkEnabled","__PRIVATE_docKeys","__PRIVATE_promiseChain","__PRIVATE_remoteDoc","__PRIVATE_ackVersion","__PRIVATE_garbageCollector","__PRIVATE_cachedTargetData","__PRIVATE_queryEngine","__PRIVATE_initialUser","__PRIVATE_delegate","__PRIVATE_params","__PRIVATE_localStore","__PRIVATE_cacheSizeCollectionThreshold","__PRIVATE_percentileToCollect","__PRIVATE_maximumSequenceNumbersToCollect","__PRIVATE_maxElements","__PRIVATE_InternalFieldPath","__PRIVATE_RESERVED","fieldNames","__PRIVATE_FieldValueImpl","__PRIVATE_validateNoArgs","__PRIVATE_DeleteFieldValueImpl","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_validateAtLeastNumberOfArgs","__PRIVATE_PublicFieldValue","__PRIVATE_RESERVED_FIELD_REGEX","__PRIVATE__operand","__PRIVATE__elements","__PRIVATE__methodName","__PRIVATE_dataSource","__PRIVATE_UserDataSource","UserDataSource","__PRIVATE_childPath","context","__PRIVATE_fieldDescription","__PRIVATE_ParseContext","__PRIVATE_isWrite","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_validatedFieldPaths","fieldPaths_1","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_fieldMaskPaths","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","moreFieldsAndValues","__PRIVATE_fieldPathFromArgument","value_1","__PRIVATE_allowArrays","__PRIVATE_parsed","__PRIVATE_errorMessage","__PRIVATE_looksLikeJsonObject","__PRIVATE_isEmpty","__PRIVATE_entryIndex","array_1","__PRIVATE_parsedEntry","__PRIVATE_parsedElements","arrayUnion","arrayRemove","__PRIVATE_numericIncrement","__PRIVATE_typeUtils.isSafeInteger","fromDate","__PRIVATE_preConverter","__PRIVATE_arrayElement","search","__PRIVATE_ExponentialBackoff","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_delaySoFarMs","__PRIVATE_remainingDelayMs","__PRIVATE_queue","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","PersistentStreamState","__PRIVATE_PersistentStreamState","__PRIVATE_PersistentStream","close","stream","send","__PRIVATE_finalState","__PRIVATE_dispatchIfNotClosed","__PRIVATE_closeCount","token","__PRIVATE_rpcError","onMessage","__PRIVATE_startCloseCount","__PRIVATE_PersistentListenStream","__PRIVATE_watchChangeProto","serializer","snapshot","addTarget","labels","__PRIVATE_PersistentWriteStream","__PRIVATE_responseProto","lastStreamToken","writeResults","writes","credentials","__PRIVATE_Datastore","__PRIVATE_rpcName","Transaction","write","__PRIVATE_unwritten","__PRIVATE__version","commit","__PRIVATE_docVersion","__PRIVATE_existingVersion","__PRIVATE_OnlineState","__PRIVATE_OnlineStateTracker","__PRIVATE_newState","details","__PRIVATE_RemoteStore","enableNetwork","__PRIVATE_objUtils.contains","__PRIVATE_objUtils.__PRIVATE_isEmpty","isPrimary","__PRIVATE_requestTargetData","__PRIVATE_lastBatchIdRetrieved","shift","__PRIVATE_success","__PRIVATE_isPermanentError","CLIENT_STATE_KEY_PREFIX","__PRIVATE_datastore","__PRIVATE_onlineStateHandler","__PRIVATE_connectivityMonitor","Ra","ya","Da","Oa","__PRIVATE_connection","__PRIVATE_connectionTimerId","__PRIVATE_idleTimerId","__PRIVATE_credentialsProvider","createWebStorageClientStateKey","clientId","MUTATION_BATCH_KEY_PREFIX","createWebStorageMutationBatchKey","__PRIVATE_mutationKey","QUERY_TARGET_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","__PRIVATE_mutationBatch","parse","__PRIVATE_validData","__PRIVATE_firestoreError","__PRIVATE_batchMetadata","updateTimeMs","__PRIVATE_clientState","__PRIVATE_activeTargetIdsSet","onlineState","window","localStorage","__PRIVATE_WebStorageSharedClientState","__PRIVATE_existingClients","__PRIVATE_storageItem","getItem","__PRIVATE_RemoteClientState","__PRIVATE_onlineStateJSON","storage","event_1","addEventListener","setItem","__PRIVATE_activeTargets","__PRIVATE_objUtils.forEach","__PRIVATE_queryState","__PRIVATE_QueryTargetMetadata","removeItem","removeEventListener","event","storageArea","__PRIVATE_mutationMetadata","__PRIVATE_queryTargetMetadata","__PRIVATE_seqString","__PRIVATE_mutationState","__PRIVATE_targetKey","__PRIVATE_targetMetadata","match","userId","__PRIVATE_MutationMetadata","__PRIVATE_SharedOnlineState","__PRIVATE_existingTargets","__PRIVATE_newTargets","__PRIVATE_addedTargets","__PRIVATE_removedTargets","__PRIVATE_localClientId","__PRIVATE_escapedPersistenceKey","SEQUENCE_NUMBER_KEY_PREFIX","ONLINE_STATE_KEY_PREFIX","__PRIVATE_MemorySharedClientState","GeneratorIds","__PRIVATE_TargetIdGenerator","__PRIVATE_nextId","__PRIVATE_GeneratorIds","__PRIVATE_previousChanges","__PRIVATE_changeSet","__PRIVATE_oldDocumentSet","__PRIVATE_newMutatedKeys","__PRIVATE_newDocumentSet","__PRIVATE_needsRefill","__PRIVATE_lastDocInLimit","__PRIVATE_firstDocInLimit","first","__PRIVATE_newMaybeDoc","__PRIVATE_oldDoc","__PRIVATE_oldDocHadPendingMutations","__PRIVATE_newDocHasPendingMutations","__PRIVATE_changeApplied","track","Hl","Xl","Zl","$i","__PRIVATE_updateLimboDocuments","__PRIVATE_c1","__PRIVATE_c2","__PRIVATE_limboChanges","__PRIVATE_newSyncState","__PRIVATE_SyncState","ed","__PRIVATE_oldLimboDocuments","__PRIVATE_queryResult","__PRIVATE__syncedDocuments","__PRIVATE_generatorId","seed","view","__PRIVATE_userPromise","__PRIVATE_commitError","__PRIVATE_userPromiseError","updateFunction","__PRIVATE_SyncEngine","__PRIVATE_syncEngineListener","__PRIVATE_queryView","status_1","listen","__PRIVATE_viewDocChanges","__PRIVATE_synthesizedTargetChange","__PRIVATE_queries","q","__PRIVATE_userCallback","__PRIVATE_deferred","__PRIVATE_limboResolution","__PRIVATE_ignoreIfPrimaryLeaseLoss","__PRIVATE_OnlineStateSource","__PRIVATE_newViewSnapshots","__PRIVATE_limboKey","__PRIVATE_batchState","__PRIVATE_mutationBatchResult","__PRIVATE_highestBatchId","__PRIVATE_callbacks","__PRIVATE_newCallbacks","__PRIVATE_limboKeys","__PRIVATE_limboTargetId","__PRIVATE_limboChange","__PRIVATE_newSnaps","__PRIVATE_docChangesInAllViews","__PRIVATE_queriesProcessed","__PRIVATE_LocalViewChanges","__PRIVATE_fnName","__PRIVATE_userChanged","__PRIVATE_activeQueries","p_1","__PRIVATE_synthesizedRemoteEvent","__PRIVATE_RemoteEvent","__PRIVATE_added","this_1","disableNetwork","__PRIVATE_keySet","__PRIVATE_EventManager","__PRIVATE_firstListen","__PRIVATE_queryInfo","__PRIVATE_lastListen","__PRIVATE_viewSnaps","__PRIVATE_raisedEvent","__PRIVATE_viewSnap","onError","observer","__PRIVATE_snap","includeMetadataChanges","__PRIVATE_QueryListener","__PRIVATE_maybeOnline","__PRIVATE_hasPendingWritesChanged","__PRIVATE_escapeChar","__PRIVATE_encodedSeparatorChar","__PRIVATE_encodedNul","__PRIVATE_encodedEscape","__PRIVATE_queryObserver","__PRIVATE_syncEngine","subscribe","__PRIVATE_remoteStore","__PRIVATE_sharedClientState","encode","__PRIVATE_encodeSeparator","__PRIVATE_encodeSegment","__PRIVATE_resultBuf","decode","__PRIVATE_lastReasonableEscapeIndex","__PRIVATE_segmentBuilder","__PRIVATE_currentPiece","__PRIVATE_schemaConverter","__PRIVATE_SimpleDb","indexedDB","open","onsuccess","db","onblocked","onerror","onupgradeneeded","oldVersion","createOrUpgrade","SCHEMA_VERSION","__PRIVATE_wrapRequest","deleteDatabase","__PRIVATE_ua","__PRIVATE_iOSVersion","__PRIVATE_isUnsupportedIOS","__PRIVATE_androidVersion","__PRIVATE_isUnsupportedAndroid","__PRIVATE_process","store","__PRIVATE_iOSVersionRegex","__PRIVATE_androidVersionRegex","__PRIVATE_versionChangeListener","onversionchange","__PRIVATE_objectStores","__PRIVATE_transactionFn","__PRIVATE_readonly","startsWith","__PRIVATE_idempotent","endsWith","__PRIVATE_attemptNumber","__PRIVATE_SimpleDbTransaction","__PRIVATE_transactionFnResult","abort","__PRIVATE_retryable","error_1","__PRIVATE_IterationController","objectStoreNames","aborted","__PRIVATE_storeName","objectStore","__PRIVATE_SimpleDbStore","__PRIVATE_keyOrValue","__PRIVATE_indexOrRange","control","__PRIVATE_optionsOrCallback","__PRIVATE_cursorRequest","__PRIVATE_checkForAndReportiOSError","primaryKey","__PRIVATE_shouldContinue","continue","controller","__PRIVATE_userResult","__PRIVATE_indexName","reverse","openKeyCursor","openCursor","oncomplete","onabort","__PRIVATE_dbCursor","__PRIVATE_reportedIOSError","__PRIVATE_IOS_ERROR","__PRIVATE_newError","__PRIVATE_referenceDelegate","empty","IDBKeyRange","__PRIVATE_mutationsStore","DbMutationBatch","userMutationsIndex","__PRIVATE_convertStreamToken","__PRIVATE_mutationQueuesStore","__PRIVATE_documentStore","__PRIVATE_documentMutationsStore","__PRIVATE_mutationStore","__PRIVATE_dbBatch","__PRIVATE_collectionParents","__PRIVATE_l","__PRIVATE_indexKey","DbDocumentMutation","PLACEHOLDER","__PRIVATE_nextBatchId","lowerBound","__PRIVATE_foundBatch","__PRIVATE_dbBatches","__PRIVATE_indexPrefix","prefixForPath","__PRIVATE_indexStart","__PRIVATE_userID","__PRIVATE_encodedPath","EncodedResourcePath.decode","__PRIVATE_uniqueBatchIDs","__PRIVATE_batchID","__PRIVATE_queryPath","__PRIVATE_immediateChildrenLength","__PRIVATE_batchIDs","__PRIVATE_removeMutationBatch","__PRIVATE_startRange","prefixForUser","__PRIVATE_danglingMutationReferences","__PRIVATE_mutationQueueContainsKey","DbMutationQueue","__PRIVATE_containsKey","Rv","keyPath","__PRIVATE_indexTxn","only","__PRIVATE_numDeleted","__PRIVATE_removePromise","__PRIVATE_IndexedDbPersistence","highestTargetId","after","__PRIVATE_getHighestListenSequenceNumber","highestListenSequenceNumber","__PRIVATE_targetsStore","__PRIVATE_retrieveMetadata","DbTargetGlobal","updated","DbTarget","queryTargetsIndexName","__PRIVATE_documentTargetStore","EncodedResourcePath.encode","DbTargetDocument","__PRIVATE_immediateSuccessor","documentTargetsIndex","__PRIVATE_targetGlobal","__PRIVATE_remoteDocumentsStore","__PRIVATE_dbKey","__PRIVATE_IndexedDbRemoteDocumentCache","__PRIVATE_sizeDelta","getMetadata","byteSize","__PRIVATE_dbRemoteDoc","$v","__PRIVATE_dbDocumentSize","__PRIVATE_sizeMap","nw","iw","__PRIVATE_keyIter","__PRIVATE_nextKey","__PRIVATE_potentialKeyRaw","__PRIVATE_potentialKey","__PRIVATE_immediateChildrenPathLength","__PRIVATE_iterationOptions","__PRIVATE_collectionKey","__PRIVATE_readTimeKey","DbRemoteDocument","collectionReadTimeIndex","__PRIVATE_lastReadTime","__PRIVATE_documentsStore","readTimeIndex","lc","__PRIVATE_documentGlobalStore","DbRemoteDocumentGlobal","__PRIVATE_previousSize","__PRIVATE_deletedDoc","updateMetadata","__PRIVATE_getResult","__PRIVATE_maybeDocuments","__PRIVATE_documentCache","__PRIVATE_trackRemovals","unknownDocument","noDocument","collectionPath","__PRIVATE_MemoryCollectionParentIndex","parentPath","__PRIVATE_existingParents","SchemaConverter","__PRIVATE_simpleDbTransaction","createObjectStore","DbPrimaryClient","autoIncrement","createIndex","userMutationsKeyPath","unique","__PRIVATE_createQueryCache","deleteObjectStore","__PRIVATE_globalStore","__PRIVATE_existingMutations","__PRIVATE_v3MutationsStore","__PRIVATE_writeAll","DbClientMetadata","removeAcknowledgedMutations","addDocumentGlobal","ensureSequenceNumbers","createCollectionParentIndex","__PRIVATE_remoteDocumentStore","readTimeIndexPath","collectionReadTimeIndexPath","__PRIVATE_byteCount","__PRIVATE_queuesStore","__PRIVATE_queues","lastAcknowledgedBatchId","__PRIVATE_currentSequenceNumber","__PRIVATE_docSentinelKey","__PRIVATE_maybeSentinel","__PRIVATE_addEntry","cache","__PRIVATE_collectionParentsStore","DbCollectionParent","__PRIVATE_pathSegments","ownerId","allowTabSynchronization","leaseTimestampMs","localWriteTimeMs","lastListenSequenceNumber","documentTargetsKeyPath","queryTargetsKeyPath","inForeground","ALL_STORES","__PRIVATE_collectionParent","__PRIVATE_parentPaths","__PRIVATE_dbReadTime","readTime_1","DbNoDocument","readTime_2","DbUnknownDocument","__PRIVATE_dbTimestampKey","DbTimestamp","__PRIVATE_dbTimestamp","__PRIVATE_serializedBaseMutations","__PRIVATE_serializedMutations","__PRIVATE_encodedKeys","__PRIVATE_encodedPaths","__PRIVATE_dbTarget","__PRIVATE_queryProto","__PRIVATE_dbLastLimboFreeTimestamp","__PRIVATE_remoteSerializer","__PRIVATE_PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","__PRIVATE_primaryStateListener","__PRIVATE_primaryState","__PRIVATE_databaseDeletedListener","newVersion","__PRIVATE_clientMetadataStore","__PRIVATE_canActAsPrimary","__PRIVATE_primaryClientStore","__PRIVATE_primaryClient","__PRIVATE_metadataStore","active","__PRIVATE_inactive","__PRIVATE_client","__PRIVATE_inactiveClient","__PRIVATE_currentPrimary","__PRIVATE_otherClient","__PRIVATE_otherClientHasBetterNetworkState","__PRIVATE_otherClientHasBetterVisibility","__PRIVATE_otherClientHasSameNetworkState","__PRIVATE_clients","__PRIVATE_activityThresholdMs","__PRIVATE_clientMetadata","__PRIVATE_dbName","__PRIVATE_IndexedDbMutationQueue","__PRIVATE_transactionOperation","__PRIVATE_persistenceTransaction","__PRIVATE_simpleDbMode","__PRIVATE_simpleDbTxn","__PRIVATE_holdsPrimaryLease","__PRIVATE_newPrimary","__PRIVATE_databaseInfo","__PRIVATE_maxAgeMs","visibilityState","__PRIVATE_isZombied","__PRIVATE_ZOMBIED_CLIENTS_KEY_PREFIX","__PRIVATE_lruParams","LocalSerializer","__PRIVATE_docCountPromise","__PRIVATE_docCount","__PRIVATE_orphanedCount","__PRIVATE_inMemoryPins","__PRIVATE_writeSentinelKey","__PRIVATE_changeBuffer","__PRIVATE_documentCount","__PRIVATE_isPinned","__PRIVATE_IndexedDbLruDelegate","__PRIVATE_nextPath","__PRIVATE_nextToReport","__PRIVATE_localDocuments","__PRIVATE_previousResults","__PRIVATE_getLogLevel","__PRIVATE_updatedResults","__PRIVATE_sortedPreviousResults","__PRIVATE_limboFreeSnapshotVersion","__PRIVATE_docAtLimitEdge","__PRIVATE_batchIndex","__PRIVATE_check","__PRIVATE_rawIndex","__PRIVATE_startPath","__PRIVATE_rowKeyPath","__PRIVATE_references","__PRIVATE_currentSize","__PRIVATE_MemoryRemoteDocumentCache","__PRIVATE_nextTargetId","__PRIVATE_removals","__PRIVATE_matchingKeys","__PRIVATE_MemoryPersistence","__PRIVATE_vs","__PRIVATE_MemoryEagerDelegate","__PRIVATE_isReferenced","__PRIVATE_MemoryLruDelegate","__PRIVATE_documentSize","__PRIVATE_orphanedAt","cacheSizeBytes","__PRIVATE_FirestoreClient","__PRIVATE_persistenceSettings","__PRIVATE_initializationDone","__PRIVATE_persistenceResult","__PRIVATE_initialized","__PRIVATE_maybeLruGc","DOMException","settings","nr","synchronizeTabs","Wc","Sw","gw","__PRIVATE_remoteStoreOnlineStateChangedHandler","__PRIVATE_sharedClientStateOnlineStateChangedHandler","terminate","__PRIVATE_AsyncObserver","muted","eventHandler","__PRIVATE_AutoId","__PRIVATE_referenceDelegateFactory","__PRIVATE_sizer","CACHE_SIZE_UNLIMITED","__PRIVATE_FirestoreSettings","Firestore","__PRIVATE_settingsLiteral","__PRIVATE_newSettings","getAuthHeaderValueForFirstParty","__PRIVATE_makeCredentialsProvider","experimentalTabSynchronization","__PRIVATE_objUtils.__PRIVATE_defaulted","clearPersistence","e_1","app","_removeServiceInstance","waitForPendingWrites","__PRIVATE_isPartialObserver","__PRIVATE_asyncObserver","DocumentReference","__PRIVATE_thisDb","__PRIVATE_otherDb","firestore","__PRIVATE_pathString","CollectionReference","WriteBatch","level","log.setLogLevel","documentRef","__PRIVATE_validateReference","DocumentSnapshot","__PRIVATE_validateBetweenNumberOfArgs","__PRIVATE_validateSetOptions","__PRIVATE_convertedValue","merge","mergeFields","__PRIVATE_fieldOrUpdateData","__PRIVATE_currArg","__PRIVATE_validateOptionNames","__PRIVATE_validateNamedOptionalType","__PRIVATE_internalOptions","__PRIVATE_validateOptionalArgType","complete","__PRIVATE_errHandler","__PRIVATE_internalListener","__PRIVATE_InternalQuery","__PRIVATE_validateGetOptions","__PRIVATE_unlisten","ov","SnapshotMetadata","__PRIVATE_validateSnapshotOptions","QueryDocumentSnapshot","fromFirestore","__PRIVATE_FieldValueOptions","opStr","__PRIVATE_validateDefined","__PRIVATE_enums","__PRIVATE_validateStringEnum","operator","__PRIVATE_referenceList","directionStr","__PRIVATE_validatePositiveNumber","__PRIVATE_docOrField","_p","__PRIVATE_allFields","components","__PRIVATE_rawValue","__PRIVATE_wrapped","QuerySnapshot","__PRIVATE_firestoreClient","__PRIVATE_documentIdValue","isArray","__PRIVATE_arrayOps","__PRIVATE_disjunctiveOps","__PRIVATE_isArrayOp","__PRIVATE_isDisjunctiveOp","__PRIVATE_existingField","__PRIVATE_conflictingOp","__PRIVATE_inequality","__PRIVATE_lastDoc","index_1","oldIndex","newIndex","__PRIVATE_indexTracker","__PRIVATE_resultChangeType","__PRIVATE__firestore","__PRIVATE__originalQuery","__PRIVATE__snapshot","__PRIVATE__converter","__PRIVATE__query","__PRIVATE__key","__PRIVATE__document","__PRIVATE__fromCache","__PRIVATE__hasPendingWrites","__PRIVATE__transaction","__PRIVATE_databaseIdOrApp","external_1","experimentalForceLongPolling","property","defineProperty","__PRIVATE_docRef","__PRIVATE__path","__PRIVATE_typeDescription","__PRIVATE_validator","__PRIVATE_validateOptionalArrayElements","__PRIVATE_validateNamedOptionalPropertyEquals","toFirestore","__PRIVATE_PublicFirestore","__PRIVATE_PublicTransaction","__PRIVATE_PublicWriteBatch","__PRIVATE_PublicDocumentReference","__PRIVATE_PublicDocumentSnapshot","__PRIVATE_PublicQueryDocumentSnapshot","__PRIVATE_PublicQuery","__PRIVATE_PublicQuerySnapshot","__PRIVATE_PublicCollectionReference","__PRIVATE_firestoreNamespace","__PRIVATE_StreamBridge","__PRIVATE_RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","__PRIVATE_X_GOOG_API_CLIENT_VALUE","__PRIVATE_header","__PRIVATE_xhr","listenOnce","getLastErrorCode","json","getResponseJson","getStatus","getResponseText","__PRIVATE_responseError","__PRIVATE_firestoreErrorCode","__PRIVATE_serverError","toLowerCase","getLastError","__PRIVATE_jsonObj","__PRIVATE_requestString","Content-Type","__PRIVATE_urlParts","__PRIVATE_webchannelTransport","backgroundChannelTest","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","ua","isIE","runtime","chrome","browser","isBrowserExtension","__PRIVATE_unguardedEventListen","createWebChannel","__PRIVATE_opened","closed","__PRIVATE_streamBridge","Jp","Yp","__PRIVATE_msgData","__PRIVATE_msgDataOrError","status_2","__PRIVATE_urlRpcName","__PRIVATE_BrowserPlatform","__PRIVATE_BrowserConnectivityMonitor","__PRIVATE_encoded","raw","registerComponent","container","getProvider","setServiceProps","registerVersion"],"mappings":"4RAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MACpDN,EAAGC,IAGrB,SAASO,EAAUR,EAAGC,GAEzB,SAASQ,IAAOC,KAAKC,YAAcX,EADnCD,EAAcC,EAAGC,GAEjBD,EAAEY,UAAkB,OAANX,EAAaC,OAAOW,OAAOZ,IAAMQ,EAAGG,UAAYX,EAAEW,UAAW,IAAIH,GAG5E,ICIKK,EAAAA,EDJDC,EAAW,WAQlB,OAPAA,EAAWb,OAAOc,QAAU,SAAkBC,GAC1C,IAAK,IAAIC,EAAGC,EAAI,EAAGC,EAAIC,UAAUC,OAAQH,EAAIC,EAAGD,IAE5C,IAAK,IAAIb,KADTY,EAAIG,UAAUF,GACOjB,OAAOU,UAAUL,eAAegB,KAAKL,EAAGZ,KAAIW,EAAEX,GAAKY,EAAEZ,IAE9E,OAAO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