mirror of
https://github.com/musix-org/musix-oss
synced 2024-11-10 11:20:19 +00:00
1 line
2.4 MiB
1 line
2.4 MiB
{"version":3,"file":"firebase-firestore.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/platform/platform.ts","../firestore/src/util/error.ts","../firestore/src/util/api.ts","../firestore/src/util/obj.ts","../firestore/src/util/input_validation.ts","../firestore/src/util/misc.ts","../firestore/src/api/blob.ts","../firestore/src/core/database_info.ts","../firestore/src/core/listen_sequence.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/util/promise.ts","../firestore/src/util/async_queue.ts","../firestore/src/local/encoded_resource_path.ts","../firestore/src/api/timestamp.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/collections.ts","../firestore/src/model/mutation_batch.ts","../firestore/src/local/persistence_promise.ts","../firestore/src/local/simple_db.ts","../firestore/src/local/indexeddb_mutation_queue.ts","../firestore/src/core/target_id_generator.ts","../firestore/src/local/indexeddb_target_cache.ts","../firestore/src/model/mutation.ts","../firestore/src/model/field_value.ts","../firestore/src/model/document.ts","../firestore/src/util/obj_map.ts","../firestore/src/local/remote_document_change_buffer.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/target_data.ts","../firestore/src/local/indexeddb_index_manager.ts","../firestore/src/local/local_serializer.ts","../firestore/src/local/local_documents_view.ts","../firestore/src/local/persistence.ts","../firestore/src/local/reference_set.ts","../firestore/src/local/local_store.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/local/indexeddb_persistence.ts","../firestore/src/util/types.ts","../firestore/src/core/target.ts","../firestore/src/core/query.ts","../firestore/src/local/index_free_query_engine.ts","../firestore/src/local/memory_mutation_queue.ts","../firestore/src/local/memory_remote_document_cache.ts","../firestore/src/local/memory_target_cache.ts","../firestore/src/local/memory_persistence.ts","../firestore/src/remote/backoff.ts","../firestore/src/remote/persistent_stream.ts","../firestore/src/remote/datastore.ts","../firestore/src/core/transaction.ts","../firestore/src/core/types.ts","../firestore/src/remote/online_state_tracker.ts","../firestore/src/remote/rpc_error.ts","../firestore/src/model/document_set.ts","../firestore/src/core/view_snapshot.ts","../firestore/src/remote/remote_event.ts","../firestore/src/remote/watch_change.ts","../firestore/src/remote/remote_store.ts","../firestore/src/api/geo_point.ts","../firestore/src/model/transform_operation.ts","../firestore/src/remote/existence_filter.ts","../firestore/src/remote/serializer.ts","../firestore/src/core/event_manager.ts","../firestore/src/local/local_view_changes.ts","../firestore/src/core/view.ts","../firestore/src/core/transaction_runner.ts","../firestore/src/core/sync_engine.ts","../firestore/src/auth/user.ts","../firestore/src/local/shared_client_state_schema.ts","../firestore/src/local/shared_client_state.ts","../firestore/src/core/firestore_client.ts","../firestore/src/util/async_observer.ts","../firestore/src/api/field_path.ts","../firestore/src/api/credentials.ts","../firestore/src/api/observer.ts","../firestore/src/api/field_value.ts","../firestore/src/api/user_data_converter.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 closure’s 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_, '&')\r\n .replace(goog.string.internal.LT_RE_, '<')\r\n .replace(goog.string.internal.GT_RE_, '>')\r\n .replace(goog.string.internal.QUOT_RE_, '"')\r\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, ''')\r\n .replace(goog.string.internal.NULL_RE_, '�');\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_, '&');\r\n }\r\n if (str.indexOf('<') != -1) {\r\n str = str.replace(goog.string.internal.LT_RE_, '<');\r\n }\r\n if (str.indexOf('>') != -1) {\r\n str = str.replace(goog.string.internal.GT_RE_, '>');\r\n }\r\n if (str.indexOf('\"') != -1) {\r\n str = str.replace(goog.string.internal.QUOT_RE_, '"');\r\n }\r\n if (str.indexOf('\\'') != -1) {\r\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, ''');\r\n }\r\n if (str.indexOf('\\x00') != -1) {\r\n str = str.replace(goog.string.internal.NULL_RE_, '�');\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, '  '), 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_, 'e');\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 = {'&': '&', '<': '<', '>': '>', '"': '\"'};\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. ) 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. ) 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, '  '), 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 { 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 * 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 { 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 { 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 { 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 { 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\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 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 '../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\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 { 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 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 { 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 './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 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 { 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 { 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 { 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 { 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 { 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 { 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\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 { 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 { 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 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 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 { 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 { 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 { 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 { 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 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 { 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 * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\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 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 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 { 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 { 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 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 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 { 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 { 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 {\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 { 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 { 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 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 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\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 { 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 { 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 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 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 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 { 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 SyncEngine’s 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\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 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 { 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 { 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 * 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 { 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\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 { 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 * 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","logClient","getLogLevel","FirebaseLogLevel","SILENT","setLogLevel","newLevel","debug","tag","msg","argToString","platform","PlatformSupport","getPlatform","formatJSON","fail","failure","assert","assertion","emptyByteString","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","makeConstructorPrivate","cls","optionalMessage","PublicConstructor","FirestoreError","staticProperty","contains","defaulted","defaultValue","forEachNumber","num","forEach","isEmpty","validateNoArgs","functionName","formatPlural","validateExactNumberOfArgs","numberOfArgs","validateAtLeastNumberOfArgs","minNumberOfArgs","validateBetweenNumberOfArgs","maxNumberOfArgs","validateArgType","position","argument","validateType","ordinal","validateOptionalArgType","validateNamedType","optionName","validateNamedOptionalType","validateOptionalArrayElements","typeDescription","validator","valueDescription","validateArrayElements","validateNamedOptionalPropertyEquals","inputName","input","expected","expectedDescription","expected_1","actualDescription","join","validateNamedPropertyEquals","isPlainObject","description","getPrototypeOf","substring","JSON","stringify","customObjectName","results","exec","tryGetCustomObjectType","validateDefined","validateOptionNames","optionNames","obj.forEach","indexOf","invalidClassError","validatePositiveNumber","AutoId","chars","autoId","charAt","floor","random","primitiveComparator","arrayEquals","isEqual","immediateSuccessor","assertUint8ArrayAvailable","Uint8Array","assertBase64Available","base64Available","Blob","base64","atob","char","fromCharCode","btoa","_binaryString","charCodeAt","toBase64","other","binaryString","PublicBlob","databaseId","persistenceKey","host","ssl","forceLongPolling","DEFAULT_DATABASE_NAME","DatabaseId","database","projectId","ListenSequence","externalPreviousValue","previousValue","max","nextValue","writeNewSequenceNumber","sequenceNumberSyncer","sequenceNumberHandler","sequenceNumber","setPreviousValue","writeSequenceNumber","DOCUMENT_KEY_NAME","BasePath","len","comparator","nameOrPath","limit","construct","potentialChild","end","p1","p2","min","ResourcePath","toArray","canonicalString","split","filter","identifierRegExp","FieldPath","test","isValidIdentifier","current","addCurrentSegment","inBackticks","DocumentKey","collectionId","k1","k2","fromString","isDocumentKey","TimerId","DelayedOperation","asyncQueue","timerId","delayMs","removalCallback","delayedOp","start","timerHandle","setTimeout","handleDelayElapsed","reason","clearTimeout","deferred","enqueueAndForget","targetTimeMs","Deferred","bind","catch","AsyncQueue","_isShuttingDown","enqueue","verifyNotFailed","enqueueInternal","enqueueEvenAfterShutdown","newTail","tail","operationInProgress","stack","log.error","timerIdsToSkip","createAndSchedule","removedOp","removeDelayedOperation","delayedOperations","lastTimerId","drain","All","containsDelayedOperation","sort","skipDelay","splice","escapeChar","encodedSeparatorChar","encodedNul","encodedEscape","encode","encodeSeparator","encodeSegment","resultBuf","decode","EMPTY_PATH","lastReasonableEscapeIndex","segmentBuilder","currentPiece","Timestamp","fromMillis","date","getTime","milliseconds","seconds","toMillis","nanoseconds","SnapshotVersion","MIN","timestamp","_compareTo","SortedMap","root","insert","copy","LLRBNode","BLACK","node","cmp","prunedNodes","minKey","maxKey","action","inorderTraversal","descriptions","reverseTraversal","SortedMapIterator","EMPTY","nodeStack","isReverse","startKey","color","fixUp","isRed","moveRedLeft","removeMin","smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","nl","RED","nr","blackDepth","check","pow","LLRBEmptyNode","SortedSet","add","elem","cb","range","iter","getIteratorFrom","hasNext","getNext","getIterator","SortedSetIterator","has","thisIt","otherIt","thisElem","otherElem","targetId","EMPTY_MAYBE_DOCUMENT_MAP","maybeDocumentMap","nullableMaybeDocumentMap","EMPTY_DOCUMENT_MAP","documentMap","EMPTY_DOCUMENT_VERSION_MAP","documentVersionMap","EMPTY_DOCUMENT_KEY_SET","documentKeySet","set","keys_1","EMPTY_TARGET_ID_SET","targetIdSet","MutationBatch","docKey","maybeDoc","batchResult","mutationResults","mutations","mutation","mutationResult","applyToRemoteDocument","baseMutations","applyToLocalView","localWriteTime","baseDoc","_c","maybeDocs","mutatedDocuments","mutatedDocument","reduce","batchId","misc.arrayEquals","MutationBatchResult","batch","commitVersion","streamToken","versionMap","docVersions","PersistencePromise","nextFn","catchFn","callbackAttached","isDone","wrapFailure","wrapSuccess","nextCallback","catchCallback","wrapUserFunction","all","expectedCount","resolvedCount","predicates","predicate","isTrue","predicates_1","collection","promises","waitFor","LOG_TAG","SimpleDb","schemaConverter","isAvailable","window","indexedDB","open","onsuccess","event","db","onblocked","onerror","onupgradeneeded","oldVersion","createOrUpgrade","transaction","SCHEMA_VERSION","toPromise","wrapRequest","deleteDatabase","isMockPersistence","ua","iOSVersion","getIOSVersion","isUnsupportedIOS","androidVersion","getAndroidVersion","isUnsupportedAndroid","process","env","USE_MOCK_PERSISTENCE","txn","store","iOSVersionRegex","match","androidVersionRegex","versionChangeListener","onversionchange","objectStores","transactionFn","readonly","startsWith","idempotent","endsWith","attemptNumber","SimpleDbTransaction","this_1","transactionFnResult","abort","completionPromise","retryable","error_1","close","IterationController","shouldStop","nextKey","dbCursor","delete","objectStoreNames","completionDeferred","aborted","storeName","objectStore","SimpleDbStore","oncomplete","onabort","checkForAndReportiOSError","keyOrValue","indexOrRange","cursor","iterateCursor","keysOnly","control","optionsOrCallback","cursorRequest","primaryKey","shouldContinue","continue","controller","userResult","userPromise","skipToKey","indexName","direction","reverse","openKeyCursor","openCursor","reportedIOSError","IOS_ERROR","newError_1","IndexedDbMutationQueue","user","serializer","indexManager","referenceDelegate","uid","isAuthenticated","empty","IDBKeyRange","bound","userId","NEGATIVE_INFINITY","POSITIVE_INFINITY","mutationsStore","iterate","DbMutationBatch","userMutationsIndex","getMutationQueueMetadata","lastStreamToken","convertStreamToken","mutationQueuesStore","documentStore","documentMutationsStore","mutationStore","dbBatch","toDbMutationBatch","collectionParents","mutations_1","indexKey","DbDocumentMutation","popLast","PLACEHOLDER","parent","addToCollectionParentIndex","addOnCommittedListener","documentKeysByBatchId","fromDbMutationBatch","lookupMutationBatch","nextBatchId","lowerBound","foundBatch","upperBound","loadAll","dbBatches","documentKey","indexPrefix","prefixForPath","indexStart","userID","encodedPath","EncodedResourcePath.decode","documentKeys","uniqueBatchIDs","batchID","lookupMutationBatches","isDocumentQuery","isCollectionGroupQuery","queryPath","immediateChildrenLength","isPrefixOf","batchIDs","removeMutationBatch","simpleDbTransaction","removedDocuments","removeCachedMutationKeys","removeMutationReference","checkEmpty","startRange","prefixForUser","danglingMutationReferences","mutationQueueContainsKey","DbMutationQueue","keyPath","indexTxn","only","numDeleted","removePromise","token","IndexedDbPersistence","getStore","GeneratorIds","TargetIdGenerator","nextId","seek","generatorId","QueryCache","SyncEngine","seed","IndexedDbTargetCache","retrieveMetadata","highestTargetId","targetIdGenerator","after","saveMetadata","fromTimestamp","lastRemoteSnapshotVersion","getHighestListenSequenceNumber","highestListenSequenceNumber","toTimestamp","targetData","saveTargetData","targetCount","updateMetadataFromTargetData","removeMatchingKeysForTargetId","targetsStore","activeTargetIds","fromDbTarget","removeTargetData","DbTargetGlobal","globalTargetStore","toDbTarget","updated","canonicalId","DbTarget","queryTargetsIndexName","found","documentTargetStore","EncodedResourcePath.encode","DbTargetDocument","addReference","removeReference","documentTargetsIndex","forTargetCache","targetGlobal","FieldMask","fields","fieldsAsSet","fieldPath","fieldMaskPath","FieldTransform","field","transform","MutationType","transformResults","Precondition","exists","updateTime","Document","isNone","misc.equals","Mutation","SetMutation","verifyKeyMatches","hasCommittedMutations","precondition","isValidFor","getPostMutationVersion","hasLocalMutations","Set","PatchMutation","UnknownDocument","newData","patchDocument","fieldMask","ObjectValue","patchObject","newValue","Patch","TransformMutation","requireDocument","serverTransformResults","transformObject","localTransformResults","baseObject","fieldTransforms","fieldTransform","existingValue","coercedValue","computeBaseValue","Transform","DeleteMutation","NoDocument","forDeletedDoc","Delete","TypeOrder","ServerTimestampBehavior","VerifyMutation","Verify","FieldValueOptions","timestampsInSnapshots","serverTimestamps","Estimate","Previous","Default","serverTimestampBehavior","FieldValue","typeOrder","NullValue","defaultCompareTo","BooleanValue","internalValue","TRUE","FALSE","NumberValue","numericComparator","numericEquals","IntegerValue","DoubleValue","NaN","Infinity","StringValue","TimestampValue","toDate","ServerTimestampValue","approximateByteSize","BlobValue","_approximateByteSize","RefValue","compareTo","GeoPointValue","it1","it2","next1","next2","to","setChild","firstSegment","child","newChild","popFirst","pathSegment","currentPath","nestedFields","nestedPath","fromSet","childName","ArrayValue","minLength","totalSize","MaybeDocument","d1","d2","objectValue","fieldValueCache","Map","canonicalPath","fieldValue","protoValue","getProtoField","converter","result_1","proto","mapValue","v1","v2","ObjectMap","id","mapKeyFn","matches","inner","matches_1","otherKey","objUtil.forEach","entries","entries_1","objUtil.isEmpty","RemoteDocumentChangeBuffer","_readTime","maybeDocument","readTime","assertNotApplied","changes","bufferedEntry","getFromCache","getAllFromCache","changesApplied","applyChanges","IndexedDbRemoteDocumentCache","remoteDocumentsStore","dbKey","sizeDelta","getMetadata","byteSize","setMetadata","dbRemoteDoc","maybeDecodeDocument","dbDocumentSize","forEachDbEntry","sizeMap","maybeDocuments","first","last","keyIter","potentialKeyRaw","potentialKey","fromSegments","skip","sinceReadTime","immediateChildrenPathLength","iterationOptions","collectionKey","readTimeKey","toDbTimestampKey","DbRemoteDocument","collectionReadTimeIndex","fromDbRemoteDocument","changedDocs","lastReadTime","documentsStore","readTimeIndex","fromDbTimestampKey","trackRemovals","documentGlobalStore","DbRemoteDocumentGlobal","class_1","previousSize","documentSizes","documentCache","toDbRemoteDocument","addEntry","deletedDoc","removeEntry","updateMetadata","getSizedEntry","getResult","getSizedEntries","document","unknownDocument","noDocument","MemoryIndexManager","collectionPath","collectionParentIndex","getEntries","MemoryCollectionParentIndex","lastSegment","parentPath","existingParents","added","SchemaConverter","fromVersion","toVersion","createObjectStore","DbPrimaryClient","createPrimaryClientStore","autoIncrement","createIndex","userMutationsKeyPath","unique","createMutationQueue","createQueryCache","createRemoteDocumentCache","deleteObjectStore","dropQueryCache","globalStore","writeEmptyTargetGlobalEntry","existingMutations","v3MutationsStore","writeAll","upgradeMutationBatchSchemaAndMigrateData","DbClientMetadata","createClientMetadataStore","removeAcknowledgedMutations","createDocumentGlobalStore","addDocumentGlobal","ensureSequenceNumbers","createCollectionParentIndex","dropRemoteDocumentChangesStore","remoteDocumentStore","readTimeIndexPath","collectionReadTimeIndexPath","createRemoteDocumentReadTimeIndex","byteCount","queuesStore","queues","queue","lastAcknowledgedBatchId","currentSequenceNumber","docSentinelKey","sentinelKey","maybeSentinel","writeSentinelKey","cache","collectionParentsStore","DbCollectionParent","pathSegments","ownerId","allowTabSynchronization","leaseTimestampMs","localWriteTimeMs","resumeToken","lastListenSequenceNumber","lastLimboFreeSnapshotVersion","documentTargetsKeyPath","queryTargetsKeyPath","clientId","updateTimeMs","networkEnabled","inForeground","TargetPurpose","ALL_STORES","IndexedDbIndexManager","collectionParentsCache","collectionParent","parentPaths","entry","TargetData","purpose","snapshotVersion","LocalSerializer","remoteDoc","remoteSerializer","fromDocument","fromDbTimestamp","dbReadTime","toDocument","readTime_1","toDbTimestamp","DbNoDocument","readTime_2","DbUnknownDocument","dbTimestampKey","DbTimestamp","dbTimestamp","serializedBaseMutations","toMutation","serializedMutations","fromMutation","encodedKeys","encodedPaths","encodedPaths_1","dbTarget","dbQuery","documents","fromDocumentsTarget","fromQueryTarget","Listen","queryProto","dbLastLimboFreeTimestamp","toDocumentsTarget","toQueryTarget","LocalDocumentsView","mutationQueue","getAllMutationBatchesAffectingDocumentKey","batches","getDocumentInternal","inBatches","remoteDocumentCache","getEntry","inBatches_1","docs","localView","batches_1","getLocalViewOfDocuments","baseDocs","getAllMutationBatchesAffectingDocumentKeys","applyLocalMutationsToDocuments","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","docPath","getDocument","collectionGroup","getCollectionParents","parents","collectionQuery","asCollectionQueryAtPath","mutationBatches","getDocumentsMatchingQuery","queryResults","getAllMutationBatchesAffectingQuery","matchingMutationBatches","addMissingBaseDocuments","mergedDocuments","mutationBatches_1","mutatedDoc","existingDocuments","missingBaseDocEntriesForPatching","matchingMutationBatches_1","missingBaseDocs","PRIMARY_LEASE_LOST_ERROR_MSG","PersistenceTransaction","onCommittedListeners","ReferenceSet","refsByKey","ref","DocReference","refsByTarget","removeRef","emptyKey","startRef","endRef","forEachInRange","firstRef","firstAfterOrEqual","compareByKey","compareByTargetId","targetOrBatchId","LocalStore","synchronizeLastDocumentChangeReadTime","newMutationQueue","newLocalDocuments","localDocuments","persistence","runTransaction","oldBatches","getAllMutationBatches","promisedOldBatches","getMutationQueue","remoteDocuments","getIndexManager","newBatches","removedBatchIds","addedBatchIds","changedKeys","oldBatches_1","newBatches_1","_e","_d","getDocuments","affectedDocuments","queryEngine","setLocalDocumentsView","existingDocs","baseValue","extractBaseValue","addMutationBatch","applyToLocalDocumentSet","lookupMutationKeys","affected","documentBuffer","newChangeBuffer","acknowledgeBatch","applyWriteToRemoteDocuments","performConsistencyCheck","affectedKeys","getHighestUnacknowledgedBatchId","getLastStreamToken","setLastStreamToken","targetCache","getLastRemoteSnapshotVersion","remoteEvent","remoteVersion","newTargetDataByTargetMap","targetDataByTarget","objUtils.forEachNumber","targetChanges","change","oldTargetData","removeMatchingKeys","addMatchingKeys","addedDocuments","newTargetData","withResumeToken","withSequenceNumber","shouldPersistTargetData","updateTargetData","updatedKeys","documentUpdates","existingDoc","hasPendingWrites","log.debug","resolvedLimboDocuments","updateLimboDocument","updateRemoteVersion","setTargetsMetadata","toMicroseconds","RESUME_TOKEN_MAX_AGE_MICROS","modifiedDocuments","viewChanges","viewChanges_1","viewChange","localViewReferences","addReferences","addedKeys","removeReferences","removedKeys","fromCache","updatedTargetData","withLastLimboFreeSnapshotVersion","afterBatchId","getNextMutationBatchAfterBatchId","getTargetData","cached","allocateTargetId","addTargetData","targetIdByTarget","keepPersistedTargetData","removed","removeReferencesForId","removeTarget","usePreviousResults","remoteKeys","toTarget","getMatchingKeysForTargetId","getActiveClients","setNetworkEnabled","docKeys","promiseChain","ackVersion","garbageCollector","collect","cachedTargetData","getTargetDataForTarget","getNewDocumentChanges","lastDocumentChangeReadTime","getLastReadTime","initialUser","started","setInMemoryPins","getRemoteDocumentCache","getTargetCache","ignoreIfPrimaryLeaseLoss","bufferEntryComparator","aSequence","aIndex","bSequence","bIndex","seqCmp","RollingSequenceNumberBuffer","previousIndex","nextIndex","maxElements","highestValue","GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","LruParams","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","COLLECTION_DISABLED","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","LruScheduler","gcTask","scheduleGC","cancel","delay","hasRun","enqueueAfterDelay","LruGarbageCollection","localStore","collectGarbage","LruGarbageCollector","percentile","delegate","getSequenceNumberCount","INVALID","forEachTarget","addElement","forEachOrphanedDocumentSequenceNumber","maxValue","removeTargets","removeOrphanedDocuments","getCacheSize","runGarbageCollection","upperBoundSequenceNumber","sequenceNumbersToCollect","countedTargetsTs","foundUpperBoundTs","removedTargetsTs","removedDocumentsTs","startTs","calculateTargetCount","sequenceNumbers","nthSequenceNumber","numTargetsRemoved","log.getLogLevel","log.LogLevel","PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","IndexedDbTransaction","lruParams","openOrCreate","dbName","simpleDb","updateClientMetadataAndTryBecomePrimary","attachVisibilityHandler","attachWindowUnloadHook","scheduleClientMetadataAndPrimaryLeaseRefreshes","listenSequence","_started","primaryStateListener","primaryState","isPrimary","databaseDeletedListener","setVersionChangeListener","newVersion","clientMetadataStore","verifyPrimaryLease","success","canActAsPrimary","releasePrimaryLeaseIfHeld","acquireOrExtendPrimaryLease","primaryClientStore","primaryClient","isLocalClient","isWithinAge","lastGarbageCollectionTime","metadataStore","existingClients","active","filterActiveClients","inactive","client","inactiveClient","localStorage","removeItem","zombiedClientLocalStorageKey","clientMetadataRefresher","ClientMetadataRefresh","maybeGarbageCollectMultiClientState","currentPrimary","isClientZombied","find","otherClient","otherClientHasBetterNetworkState","otherClientHasBetterVisibility","otherClientHasSameNetworkState","markClientZombied","detachVisibilityHandler","detachWindowUnloadHook","removeClientMetadata","removeClientZombiedEntry","clients","activityThresholdMs","clientMetadata","MAIN_DATABASE","forUser","transactionOperation","persistenceTransaction","simpleDbMode","simpleDbTxn","holdsPrimaryLease","verifyAllowTabSynchronization","raiseOnCommittedEvent","newPrimary","databaseInfo","isDefaultDatabase","maxAgeMs","addEventListener","documentVisibilityHandler","visibilityState","removeEventListener","windowUnloadHandler","shutdown","isZombied","webStorage","getItem","setItem","ZOMBIED_CLIENTS_KEY_PREFIX","IndexedDbLruDelegate","docCountPromise","orphanedDocmentCount","getTargetCount","docCount","orphanedCount","forEachOrphanedDocument","inMemoryPins","iterateSerial","mutationQueuesContainKey","changeBuffer","documentCount","isPinned","nextPath","nextToReport","getSize","sentinelRow","NumberAsAny","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","isInteger","isFinite","isNullOrUndefined","isSafeInteger","LimitType","Target","memoizedCanonicalId","filters","orderBy","startAt","endAt","Query","memoizedOrderBy","inequalityField","getInequalityFilterField","firstOrderByField","getFirstOrderByField","isKeyField","KEY_ORDERING_ASC","OrderBy","foundKeyOrdering","explicitOrderBy","lastDirection","dir","Direction","ASCENDING","KEY_ORDERING_DESC","FieldFilter","isInequality","newFilters","concat","limitType","newOrderBy","First","Last","comparedOnKeyField","comp","compare","matchesPathAndCollectionGroup","matchesOrderBy","matchesFilters","matchesBounds","operators","memoizedTarget","orderBys","DESCENDING","Bound","before","hasCollectionId","isImmediateParentOf","sortsBeforeDocument","assertValidBound","Operator","LESS_THAN","LESS_THAN_OR_EQUAL","EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","ARRAY_CONTAINS","IN","ARRAY_CONTAINS_ANY","Filter","every","KeyFieldInFilter","KeyFieldFilter","INSTANCE","NAN","ArrayContainsFilter","InFilter","ArrayContainsAnyFilter","matchesComparison","comparison","refValue","some","arrayValue","lhsElem","orderByComponent","component","docValue","thisPosition","otherPosition","isKeyOrderBy","compareByField","keyField","IndexFreeQueryEngine","localDocumentsView","matchesAllDocuments","executeFullCollectionScan","previousResults","applyQuery","hasLimitToFirst","hasLimitToLast","needsRefill","updatedResults","docComparator","sortedPreviousResults","limboFreeSnapshotVersion","docAtLimitEdge","MemoryMutationQueue","batchIndex","indexOfExistingBatchId","batchesByDocumentKey","findMutationBatch","mutationBatch","rawIndex","indexOfBatchId","findMutationBatches","startPath","forEachWhile","rowKeyPath","shift","references","MemoryRemoteDocumentCache","currentSize","sizer","MemoryTargetCache","targets","highestSequenceNumber","nextTargetId","removals","matchingKeys","referencesForId","MemoryPersistence","MemoryLruDelegate","MemoryEagerDelegate","mutationQueues","toKey","MemoryTransaction","onTransactionStarted","onTransactionCommitted","or","vs","obj\r\n .values","referenceDelegateFactory","documentSize","_orphanedDocuments","orphanedDocuments","isReferenced","orphanedDocumentCount","orphanedSequenceNumbers","forEachDocumentKey","orphanedAt","ExponentialBackoff","currentBaseMs","maxDelayMs","desiredDelayWithJitterMs","jitterDelayMs","delaySoFarMs","lastAttemptTime","remainingDelayMs","timerPromise","backoffFactor","initialDelayMs","PersistentStreamState","PersistentStream","state","Starting","Open","Backoff","Initial","auth","performBackoff","isStarted","backoff","isOpen","idleTimer","idleTimerId","handleIdleCloseTimer","cancelIdleCheck","stream","send","finalState","closeCount","resetToMax","credentialsProvider","invalidateToken","tearDown","onClose","dispatchIfNotClosed","getCloseGuardedDispatcher","getToken","startStream","rpcError","handleStreamClose","startRpc","onOpen","onMessage","backoffAndRun","startCloseCount","connectionTimerId","connection","PersistentListenStream","openStream","watchChangeProto","watchChange","fromWatchChange","snapshot","versionFromListenResponse","onWatchChange","encodedDatabaseId","addTarget","labels","toListenRequestLabels","sendRequest","credentials","ListenStreamConnectionBackoff","ListenStreamIdle","PersistentWriteStream","handshakeComplete_","writeMutations","responseProto","fromWriteResults","writeResults","commitTime","onMutationResult","onHandshakeComplete","writes","WriteStreamConnectionBackoff","WriteStreamIdle","Datastore","invokeRPC","toName","invokeStreamingRPC","fromMaybeDocument","rpcName","OnlineState","OnlineStateSource","Transaction","ensureCommitNotCalled","datastore","lookup","recordVersion","write","toMutations","writtenDocs","preconditionForUpdate","lastWriteError","unwritten","readVersions","_version","commit","committed","docVersion","existingVersion","NONE","RpcCode","OnlineStateTracker","watchStreamFailures","setAndBroadcast","Unknown","onlineStateTimer","OnlineStateTimeout","logClientOfflineWarningIfNecessary","Offline","Online","clearOnlineStateTimer","newState","shouldWarnClientIsOffline","onlineStateHandler","details","isPermanentError","mapCodeFromRpcCode","ChangeType","SyncState","DocumentSet","oldSet","keyedMap","sortedSet","thisDoc","otherDoc","docStrings","newSet","DocumentChangeSet","oldChange","changeMap","Added","Metadata","Removed","Modified","ViewSnapshot","mutatedKeys","emptySet","syncStateChanged","oldDocs","docChanges","otherChanges","excludesMetadataChanges","RemoteEvent","TargetChange","createSynthesizedTargetChangeForCurrentChange","targetMismatches","WatchTargetChangeState","updatedTargetIds","removedTargetIds","newDoc","existenceFilter","targetIds","cause","TargetState","_current","_resumeToken","pendingResponses","_hasPendingChanges","documentChanges","changeType","snapshotChangesMap","WatchChangeAggregator","docChange","addDocumentToTarget","removeDocumentFromTarget","targetChange","targetState","ensureTargetState","NoChange","isActiveTarget","updateResumeToken","recordTargetResponse","isPending","clearPendingChanges","Current","markCurrent","Reset","resetTarget","targetStates","targetDataForActiveTarget","getCurrentDocumentCountForTarget","pendingTargetResets","pendingDocumentUpdates","targetContainsDocument","hasPendingChanges","toTargetChange","pendingDocumentTargetMapping","isOnlyLimboTarget","LimboResolution","documentTargetMap","addDocumentChange","ensureDocumentTargetMapping","updatedDocument","removeDocumentChange","metadataProvider","getRemoteKeysForTarget","recordPendingTargetRequest","targetMapping","targetActive","RemoteStore","enableNetwork","canUseNetwork","writeStream","shouldStartWatchStream","startWatchStream","onlineStateTracker","fillWritePipeline","disableNetworkInternal","watchStream","writePipeline","cleanUpWatchStreamState","connectivityMonitor","objUtils.contains","listenTargets","sendWatchRequest","sendUnwatchRequest","objUtils.isEmpty","markIdle","syncEngine","watchChangeAggregator","watch","unwatch","handleWatchStreamStart","handleWatchStreamFailure","WatchTargetChange","handleTargetError","DocumentWatchChange","handleDocumentChange","ExistenceFilterChange","handleExistenceFilter","handleTargetChange","raiseWatchSnapshot","createRemoteEvent","requestTargetData","ExistenceFilterMismatch","applyRemoteEvent","rejectListen","canAddToWritePipeline","lastBatchIdRetrieved","nextMutationBatch","addToWritePipeline","shouldStartWriteStream","startWriteStream","handshakeComplete","writeHandshake","from","applySuccessfulWrite","handleWriteError","handleHandshakeError","isPermanentWriteError","inhibitBackoff","rejectFailedWrite","restartNetwork","addCallback","newPersistentWatchStream","onWatchStreamOpen","onWatchStreamClose","onWatchStreamChange","newPersistentWriteStream","onWriteStreamOpen","onWriteStreamClose","onWriteHandshakeComplete","GeoPoint","_lat","_long","latitude","longitude","ServerTimestampTransform","transformResult","ArrayUnionTransformOperation","coercedFieldValuesArray","toUnion","elements","ArrayRemoveTransformOperation","toRemove","NumericIncrementTransformOperation","operand","sum","ExistenceFilter","dirs","DIRECTIONS","OPERATORS","ISO_REG_EXP","RegExp","assertPresent","typeUtils.isNullOrUndefined","parseInt64","JsonProtoSerializer","useProto3Json","byteString","nanos","fromIso8601String","utc","fraction","nanoStr","substr","bytes","unsafeCastProtoByteString","toUint8Array","blob","fromBase64String","fromUint8Array","fullyQualifiedPrefixPath","resource","isValidResourceName","toResourceName","fromResourceName","extractLocalPathFromResourceName","resourceName","fieldValue.NullValue","nullValue","fieldValue.BooleanValue","booleanValue","fieldValue.IntegerValue","integerValue","fieldValue.DoubleValue","doubleValue","fieldValue.StringValue","stringValue","fieldValue.ObjectValue","toMapValue","fieldValue.ArrayValue","toArrayValue","fieldValue.TimestampValue","timestampValue","fieldValue.GeoPointValue","geoPointValue","fieldValue.BlobValue","bytesValue","toBytes","fieldValue.RefValue","referenceValue","of","fromFields","fromValue","fromBlob","dbId","toFields","fromName","toValue","missing","fromFound","fromMissing","documentChange","documentDelete","documentRemove","mapRpcCodeFromCode","targetChangeType","toWatchTargetChangeState","fromWatchTargetChangeState","causeProto","fromRpcStatus","entityChange","docDelete","docRemove","update","toMutationDocument","updateMask","toDocumentMask","toFieldTransform","verify","currentDocument","toPrecondition","fromPrecondition","fromDocumentMask","fromFieldTransform","MutationResult","protos","fromWriteResult","setToServerValue","appendMissingElements","removeAllFromArray","increment","fieldValue.NumberValue","fromServerFormat","toQueryPath","documentsTarget","atPath","fromQueryPath","structuredQuery","allDescendants","where","toFilter","toOrder","toInt32Value","toCursor","fromCount","filterBy","fromFilter","fromOrder","fromInt32Value","fromCursor","toLabel","goog-listen-tags","toUnaryOrFieldFilter","compositeFilter","unaryFilter","fromUnaryFilter","fieldFilter","fromFieldFilter","accum","toPropertyOrder","fromPropertyOrder","fieldReference","toFieldPathReference","toDirection","fromFieldPathReference","fromDirection","fromOperatorName","toOperatorName","nanField","nullField","canonicalFields","fieldPaths","fromArray","EventManager","firstListen","queryInfo","queries","QueryListenersInfo","listeners","applyOnlineStateChange","onlineState","viewSnap","onViewSnapshot","raiseSnapshotsInSyncEvent","listen","lastListen","unlisten","viewSnaps","raisedEvent","viewSnaps_1","onError","observer","snapshotsInSyncListeners","q","subscribe","QueryListener","snap","includeMetadataChanges","raisedInitialEvent","shouldRaiseEvent","queryObserver","shouldRaiseInitialEvent","raiseInitialEvent","maybeOnline","waitForSyncWhenOnline","hasPendingWritesChanged","fromInitialDocuments","LocalViewChanges","viewSnapshot","View","_syncedDocuments","previousChanges","changeSet","oldDocumentSet","documentSet","newMutatedKeys","newDocumentSet","lastDocInLimit","firstDocInLimit","newMaybeDoc","oldDoc","oldDocHadPendingMutations","newDocHasPendingMutations","changeApplied","track","shouldWaitForSyncedDocument","updateLimboDocuments","getChanges","c1","c2","compareChangeType","applyTargetChange","limboChanges","newSyncState","limboDocuments","Synced","Local","syncState","oldLimboDocuments","shouldBeInLimbo","RemovedLimboDocument","AddedLimboDocument","queryResult","computeDocChanges","TransactionRunner","runWithBackOff","remoteStore","createTransaction","tryRunUpdateFunction","commitError","handleTransactionError","userPromiseError","updateFunction","retries","isRetryableTransactionError","RetryTransaction","view","syncEngineListener","assertSubscribed","queryView","queryViewsByQuery","sharedClientState","addLocalQueryTarget","computeInitialSnapshot","allocateTarget","status_1","initializeViewAndComputeSnapshot","executeQuery","viewDocChanges","synthesizedTargetChange","QueryView","queriesByTarget","synchronizeWithPersistedState","updateTrackedLimbos","removeLocalQueryTarget","isActiveQueryTarget","releaseTarget","clearQueryState","removeAndCleanupTarget","userCallback","localWrite","addPendingMutation","addMutationCallback","emitNewSnapsAndNotifyLocalStore","run","objUtils.forEach","limboResolution","limboResolutionsByTarget","receivedDocument","SharedClientState","newViewSnapshots_1","onOnlineStateChange","setOnlineState","updateQueryState","limboKey","limboTargetsByKey","event_1","batchState","lookupMutationDocuments","processUserCallback","removeCachedMutationBatchMetadata","mutationBatchResult","triggerPendingWritesCallbacks","updateMutationState","rejectBatch","highestBatchId","callbacks","pendingWritesCallbacks","errorMessage","newCallbacks","mutationUserCallbacks","currentUser","onWatchError","limboKeys","limboDocumentRefs","removeLimboTarget","limboTargetId","limboChanges_1","limboChange","trackLimboChange","limboTargetIdGenerator","newSnaps","docChangesInAllViews","queriesProcessed","fromSnapshot","notifyLocalViewChanges","fnName","userChanged","rejectOutstandingPendingWritesCallbacks","handleUserChange","handleCredentialChange","applyPrimaryState","activeTargets","getAllActiveQueryTargets","synchronizeQueryViewsAndRaiseSnapshots","activeQueries","activeQueries_1","activeTargets_1","p_1","isLocalQueryTarget","resetLimboDocuments","removeAllReferences","newViewSnapshots","targets_1","queries_1","synchronizeViewAndComputeSnapshot","getTarget","synthesizeTargetToQuery","synthesizedRemoteEvent","createSynthesizedRemoteEventForCurrentChange","added_1","removed_1","disableNetwork","keySet","queries_2","unionWith","syncedDocuments","forSyncEngine","User","otherUser","CLIENT_STATE_KEY_PREFIX","createWebStorageClientStateKey","MUTATION_BATCH_KEY_PREFIX","createWebStorageMutationBatchKey","mutationKey","QUERY_TARGET_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","ONLINE_STATE_KEY_PREFIX","SEQUENCE_NUMBER_KEY_PREFIX","MutationMetadata","parse","validData","firestoreError","batchMetadata","QueryTargetMetadata","RemoteClientState","clientState","activeTargetIdsSet","SharedOnlineState","LocalClientState","WebStorageSharedClientState","existingClients_1","localClientId","storageItem","fromWebStorageEntry","activeClients","persistClientState","onlineStateJSON","storage","onlineStateKey","fromWebStorageOnlineState","handleOnlineStateEvent","earlyEvents","handleWebStorageEvent","sequenceNumberKey","persistMutationState","removeMutationState","queryState","localClientState","addQueryTarget","removeQueryTarget","persistQueryTargetState","persistOnlineState","storageListener","localClientStorageKey","storageArea","clientStateKeyRe","fromWebStorageClientStateKey","handleClientStateEvent","fromWebStorageClientState","mutationBatchKeyRe","mutationMetadata","fromWebStorageMutationMetadata","handleMutationBatchEvent","queryTargetKeyRe","queryTargetMetadata","fromWebStorageQueryTargetMetadata","handleQueryTargetEvent","seqString","parsed","fromWebStorageSequenceNumber","toWebStorageJSON","mutationState","targetKey","targetMetadata","applyBatchState","applyTargetState","existingTargets","newTargets","addedTargets","removedTargets","applyActiveTargetsChange","escapedPersistenceKey","createWebStorageSequenceNumberKey","createWebStorageOnlineStateKey","MemorySharedClientState","localState","IndexedDbPersistenceSettings","withCacheSize","cacheSizeBytes","synchronizeTabs","FirestoreClient","persistenceSettings","verifyNotTerminated","initializationDone","persistenceResult","initialized","setChangeListener","initializePersistence","maybeLruGc","initializeRest","startIndexedDbPersistence","canFallback","startMemoryPersistence","DOMException","isShuttingDown","settings","buildStoragePrefix","createIndexedDbPersistence","createEagerPersistence","loadConnection","lruScheduler","newConnectivityMonitor","newSerializer","remoteStoreOnlineStateChangedHandler","sharedClientStateOnlineStateChangedHandler","eventMgr","setPrimaryStateListener","setDatabaseDeletedListener","terminate","verifyOperationInProgress","enqueueAndInitiateShutdown","removeChangeListener","registerPendingWritesCallback","clientTerminated","readDocument","addSnapshotsInSyncListener","removeSnapshotsInSyncListener","newId","AsyncObserver","scheduleEvent","muted","eventHandler","_DOCUMENT_ID","_internalPath","InternalFieldPath","fieldNames","minNumberOfElements","validateNamedArrayAtLeastNumberOfElements","RESERVED","authHeaders","EmptyCredentialsProvider","changeListener","FirebaseCredentialsProvider","tokenListener","initialTokenCounter","tokenCounter","forceRefresh","tokenData","accessToken","OAuthToken","receivedInitialUser","removeAuthTokenListener","currentUid","getUid","authProvider","getUser","getImmediate","optional","addAuthTokenListener","FirstPartyToken","X-Goog-AuthUser","sessionIndex","authHeader","gapi","getAuthHeaderValueForFirstParty","FIRST_PARTY","FirstPartyCredentialsProvider","isPartialObserver","methods","methods_1","implementsAnyMethods","FieldValueImpl","DeleteFieldValueImpl","ServerTimestampFieldValueImpl","ArrayUnionFieldValueImpl","ArrayRemoveFieldValueImpl","NumericIncrementFieldValueImpl","_methodName","_elements","_operand","PublicFieldValue","RESERVED_FIELD_REGEX","ParsedSetData","UserDataSource","ParsedUpdateData","isWrite","dataSource","MergeSet","Update","Argument","ArrayArgument","ParseContext","childPath","context","validatePathSegment","validatePath","fieldDescription","createError","arrayElement","UserDataConverter","validatePlainObject","updateData","parseData","validatedFieldPaths","fieldPaths_1","stringOrFieldPath","ExternalFieldPath","fieldPathFromDotSeparatedString","covers","fieldMaskPaths","childContext","childContextForFieldPath","runPreConverter","parsedValue","mask","moreFieldsAndValues","fieldPathFromArgument","value_1","allowArrays","preConverter","looksLikeJsonObject","parseObject","parseSentinelFieldValue","parseArray","parseScalarValue","childContextForField","entryIndex","array_1","parsedEntry","childContextForArray","parsedElements","parseArrayTransformElements","arrayUnion","arrayRemove","parseQueryValue","numericIncrement","typeUtils.isSafeInteger","fromDate","DocumentKeyReference","search","fromDotSeparatedString","CACHE_SIZE_UNLIMITED","FirestoreSettings","objUtils.defaulted","DEFAULT_CACHE_SIZE_BYTES","MINIMUM_CACHE_SIZE_BYTES","experimentalForceLongPolling","Firestore","settingsLiteral","newSettings","_firestoreClient","_settings","_credentials","makeCredentialsProvider","ensureClientConfigured","experimentalTabSynchronization","configureClient","makeDatabaseInfo","_queue","enqueueAndForgetEvenAfterShutdown","clearPersistence","e_1","app","_removeServiceInstance","waitForPendingWrites","onSnapshotsInSyncInternal","asyncObserver","mute","MemoryPersistenceSettings","DatabaseInfo","_databaseId","_persistenceKey","DocumentReference","thisDb","otherDb","firestore","_key","_firebaseApp","pathString","CollectionReference","forPath","InternalQuery","WriteBatch","level","log.setLogLevel","databaseIdOrApp","databaseIdFromApp","external_1","_dataConverter","createDataConverter","documentRef","validateReference","_firestore","_transaction","DocumentSnapshot","_converter","validateSetOptions","convertedValue","merge","mergeFields","parseMergeData","parseSetData","fieldOrUpdateData","parseUpdateVarargs","parseUpdateData","verifyNotCommitted","_mutations","_committed","currArg","internalOptions","complete","onSnapshotInternal","errHandler","internalListener","validateGetOptions","getDocumentFromLocalCache","getViaSnapshotListener","SnapshotMetadata","validateSnapshotOptions","_document","QueryDocumentSnapshot","_fromCache","_hasPendingWrites","fromFirestore","toJSObject","fromSnapshotOptions","_areTimestampsInSnapshotsEnabled","toJSValue","toJSArray","opStr","enums","validateStringEnum","operator","validateDisjunctiveFilterElements","referenceList","parseDocumentIdValue","validateNewFilter","_query","addFilter","directionStr","validateNewOrderBy","addOrderBy","withLimitToFirst","withLimitToLast","docOrField","boundFromDocOrFields","withStartAt","withEndAt","boundFromDocument","allFields","boundFromFields","components","rawValue","wrapped","validateHasExplicitOrderByForLimitToLast","QuerySnapshot","firestoreClient","getDocumentsFromLocalCache","documentIdValue","isArray","arrayOps","disjunctiveOps","isArrayOp","isDisjunctiveOp","existingField","validateOrderByAndInequalityMatch","conflictingOp","findFilterOperator","inequality","_snapshot","convertToDocumentImpl","_originalQuery","_cachedChanges","_cachedChangesIncludeMetadataChanges","lastDoc_1","index_1","oldIndex","newIndex","indexTracker_1","resultChangeType","changesFromSnapshot","property","defineProperty","throwDocChangesMethodError","docRef","_path","applyFirestoreDataConverter","toFirestore","PublicFirestore","PublicTransaction","PublicWriteBatch","PublicDocumentReference","PublicDocumentSnapshot","PublicQueryDocumentSnapshot","PublicQuery","PublicQuerySnapshot","PublicCollectionReference","firestoreNamespace","configureForFirebase","registerComponent","container","getProvider","setServiceProps","shallowCopy","NoopConnectivityMonitor","BrowserConnectivityMonitor","networkAvailableListener","networkUnavailableListener","onNetworkAvailable","onNetworkUnavailable","configureNetworkMonitoring","StreamBridge","wrappedOnOpen","wrappedOnClose","wrappedOnMessage","closeFn","sendFn","RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","X_GOOG_API_CLIENT_VALUE","WebChannelConnection","makeUrl","listenOnce","getLastErrorCode","json","getResponseJson","getStatus","getResponseText","responseError","firestoreErrorCode","serverError","toLowerCase","mapCodeFromHttpResponseErrorStatus","getLastError","jsonObj","requestString","Content-Type","modifyHeadersForRequest","urlParts","baseUrl","webchannelTransport","backgroundChannelTest","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","isIE","runtime","chrome","browser","isBrowserExtension","unguardedEventListen","createWebChannel","opened","closed","streamBridge","callOnClose","msgData","msgDataOrError","status_2","mapCodeFromRpcStatus","callOnMessage","callOnOpen","urlRpcName","BrowserPlatform","raw","setPlatform","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,OAAOW,IAEKO,MAA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