{"version":3,"file":"firebase-firestore.js","sources":["../logger/dist/index.esm.js","../../node_modules/tslib/tslib.es6.js","../webchannel-wrapper/dist/index.js","../firestore/dist/index.esm.js"],"sourcesContent":["/**\r\n * Copyright 2017 Google Inc.\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 * A container for all of the Logger instances\r\n */\r\nvar instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\n/**\r\n * The default log level\r\n */\r\nvar defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nvar defaultLogHandler = function (instance, logType) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n if (logType < instance.logLevel)\r\n return;\r\n var now = new Date().toISOString();\r\n switch (logType) {\r\n /**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\n case LogLevel.DEBUG:\r\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.VERBOSE:\r\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.INFO:\r\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.WARN:\r\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.ERROR:\r\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n default:\r\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\r\n }\r\n};\r\nvar Logger = /** @class */ (function () {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n function Logger(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The log handler for the Logger instance.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n Object.defineProperty(Logger.prototype, \"logLevel\", {\r\n get: function () {\r\n return this._logLevel;\r\n },\r\n set: function (val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError('Invalid value assigned to `logLevel`');\r\n }\r\n this._logLevel = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Logger.prototype, \"logHandler\", {\r\n get: function () {\r\n return this._logHandler;\r\n },\r\n set: function (val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n Logger.prototype.debug = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\r\n };\r\n Logger.prototype.log = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\r\n };\r\n Logger.prototype.info = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\r\n };\r\n Logger.prototype.warn = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\r\n };\r\n Logger.prototype.error = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\r\n };\r\n return Logger;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nfunction setLogLevel(level) {\r\n instances.forEach(function (inst) {\r\n inst.logLevel = level;\r\n });\r\n}\n\nexport { setLogLevel, Logger, LogLevel };\n","/*! *****************************************************************************\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 = 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\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 = 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\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++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\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 = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [0, 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 __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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\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];\r\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\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","(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function n(a,b){a=a.split(\".\");b=b||k;for(var c=0;c>>0),fa=0;function ha(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ia(a,b,c){if(!a)throw Error();if(2b?null:l(a)?a.charAt(b):a[b]}function ua(a){if(!p(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function va(a){return Array.prototype.concat.apply([],arguments)}function wa(a){var b=a.length;if(0b?1:0};var x;a:{var Aa=k.navigator;if(Aa){var Ba=Aa.userAgent;if(Ba){x=Ba;break a}}x=\"\"}function y(a){return-1!=x.indexOf(a)};function Ca(a,b,c){for(var d in a)b.call(c,a[d],d,a)}function Da(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b}function Ea(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b}function Fa(a){var b={},c;for(c in a)b[c]=a[c];return b}var Ga=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");\nfunction Ha(a,b){for(var c,d,e=1;eparseFloat(Sa)){Ra=String(Ua);break a}}Ra=Sa}var Ka={};\nfunction Va(a){return Ja(a,function(){for(var b=0,c=ya(String(Ra)).split(\".\"),d=ya(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var db=\"closure_listenable_\"+(1E6*Math.random()|0),eb=0;function fb(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ga=e;this.key=++eb;this.Z=this.ba=!1}function gb(a){a.Z=!0;a.listener=null;a.proxy=null;a.src=null;a.ga=null};function hb(a){this.src=a;this.a={};this.b=0}hb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=ib(a,b,d,e);-1c.keyCode||void 0!=c.returnValue)){a:{var e=!1;if(0==c.keyCode)try{c.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==c.returnValue)c.returnValue=!0}c=[];for(e=b.a;e;e=e.parentNode)c.push(e);a=a.type;for(e=c.length-1;0<=e;e--){b.a=c[e];var f=xb(c[e],a,!0,b);d=d&&f}for(e=0;e>>0);function pb(a){if(da(a))return a;a[zb]||(a[zb]=function(b){return a.handleEvent(b)});return a[zb]};function B(){w.call(this);this.f=new hb(this);this.N=this;this.J=null}u(B,w);B.prototype[db]=!0;g=B.prototype;g.addEventListener=function(a,b,c,d){nb(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){vb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.J;if(c)for(b=[];c;c=c.J)b.push(c);c=this.N;var d=a.type||a;if(l(a))a=new A(a,c);else if(a instanceof A)a.target=a.target||c;else{var e=a;a=new A(d,c);Ha(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Ab(h,d,!0,a)&&e}h=a.a=c;e=Ab(h,d,!0,a)&&e;e=Ab(h,d,!1,a)&&e;if(b)for(f=0;fb.b&&(b.b++,a.next=b.a,b.a=a)}Wb=!1};function Xb(a,b){B.call(this);this.b=a||1;this.a=b||k;this.c=r(this.qb,this);this.g=t()}u(Xb,B);g=Xb.prototype;g.ea=!1;g.O=null;g.qb=function(){if(this.ea){var a=t()-this.g;0=nc(this).value)for(da(b)&&(b=b()),a=new fc(a,String(b),this.f),c&&(a.a=c),c=this;c;)c=c.a};\nvar oc={},pc=null;function qc(a){pc||(pc=new hc(\"\"),oc[\"\"]=pc,pc.c=lc);var b;if(!(b=oc[a])){b=new hc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=qc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;oc[a]=b}return b};function D(a,b){a&&a.log(jc,b,void 0)}function rc(a,b){a&&a.log(kc,b,void 0)}function E(a,b){a&&a.log(mc,b,void 0)};function sc(){this.a=qc(\"goog.labs.net.webChannel.WebChannelDebug\");this.b=!0}sc.prototype.Fa=function(){this.b=!1};function tc(a,b,c,d,e,f){F(a,function(){if(a.b)if(f){var h=\"\";for(var m=f.split(\"&\"),v=0;ve.length)){var f=e[1];if(p(f)&&!(1>f.length)){var h=f[0];if(\"noop\"!=h&&\"stop\"!=h&&\"close\"!=h)for(var m=1;mb||3==b&&!Na&&!a.a.V())){a.B||4!=b||7==c||(8==c||0>=d?Ac(3):Ac(2));bd(a);var e=a.a.W();a.C=e;(c=a.a.V())||H(a.b,function(){return\"No response text for uri \"+a.g+\" status \"+e});a.f=200==e;uc(a.b,a.o,a.g,a.c,a.T,b,e);if(a.f){if(d=cd(a))G(a.b,a.c,d,\"Initial handshake response via X-HTTP-Initial-Response\"),a.v=!0,dd(a,d);a.K?(ed(a,b,c),Na&&a.f&&3==b&&fd(a)):(G(a.b,a.c,c,null),dd(a,c));4==b&&gd(a);a.f&&!a.B&&(4==b?a.i.ta(a):(a.f=!1,Zc(a)))}else 400==\ne&&0b.length)return Uc;b=b.substr(d,c);a.G=d+c;return b}g.cancel=function(){this.B=!0;gd(this)};function Zc(a){a.U=t()+a.R;kd(a,a.R)}function kd(a,b){if(null!=a.s)throw Error(\"WatchDog timer not null\");a.s=Ec(r(a.lb,a),b)}function bd(a){a.s&&(k.clearTimeout(a.s),a.s=null)}\ng.lb=function(){this.s=null;var a=t();0<=a-this.U?(this.f&&J(this.b,\"Received watchdog timeout even though request loaded successfully\"),wc(this.b,this.g),2!=this.J&&(Ac(3),K(17)),gd(this),this.m=2,hd(this)):(D(this.b.a,\"WatchDog timer called too early\"),kd(this,this.U-a))};function hd(a){a.i.La()||a.B||a.i.ta(a)}function gd(a){bd(a);var b=a.I;b&&\"function\"==typeof b.$&&b.$();a.I=null;Yb(a.S);ec(a.L);a.a&&(b=a.a,a.a=null,b.abort(),b.$())}\nfunction dd(a,b){try{a.i.Oa(a,b),Ac(4)}catch(c){xc(a.b,c,\"Error in httprequest callback\")}};function ld(a){if(a.A&&\"function\"==typeof a.A)return a.A();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&nd(a),!0):!1}function nd(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function vd(a,b,c){b instanceof yd?(a.c=b,Ed(a.c,a.h)):(c||(b=zd(b,Fd)),a.c=new yd(b,a.h))}\nfunction R(a,b,c){a.c.set(b,c)}function $c(a,b,c){p(c)||(c=[String(c)]);Gd(a.c,b,c)}function Wc(a){R(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36));return a}function Hd(a){return a instanceof Q?M(a):new Q(a,void 0)}function Id(a,b,c,d){var e=new Q(null,void 0);a&&sd(e,a);b&&td(e,b);c&&ud(e,c);d&&(e.a=d);return e}function xd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction zd(a,b,c){return l(a)?(a=encodeURI(a).replace(b,Jd),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Jd(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var Ad=/[#\\/\\?@]/g,Cd=/[#\\?:]/g,Bd=/[#\\?]/g,Fd=/[#\\?@]/g,Dd=/#/g;function yd(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b}function S(a){a.a||(a.a=new O,a.b=0,a.c&&rd(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=yd.prototype;\ng.add=function(a,b){S(this);this.c=null;a=Kd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function Ld(a,b){S(a);b=Kd(a,b);P(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,pd(a.a,b))}function Md(a,b){S(a);b=Kd(a,b);return P(a.a.b,b)}g.forEach=function(a,b){S(this);this.a.forEach(function(c,d){ra(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.M=function(){S(this);for(var a=this.a.A(),b=this.a.M(),c=[],d=0;d=a.f:!1}\nfunction ee(a,b){a.b?a=a.b==b:a.a?(b=Yd(b),a=P(a.a.a.b,b)):a=!1;return a}function ce(a,b){a.a?a.a.add(b):a.b=b}function fe(a,b){if(a.b&&a.b==b)a.b=null;else{var c;if(c=a.a)c=Yd(b),c=P(a.a.a.b,c);c&&pd(a.a.a,Yd(b))}}$d.prototype.cancel=function(){this.c=ge(this);this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ra(this.a.A(),function(a){a.cancel()}),od(this.a.a))};\nfunction ge(a){if(null!=a.b)return a.c.concat(a.b.u);if(null!=a.a&&0!=a.a.a.c){var b=a.c;ra(a.a.A(),function(a){b=b.concat(a.u)});return b}return wa(a.c)}function he(a,b){a.c=a.c.concat(b)};function ie(){}ie.prototype.stringify=function(a){return k.JSON.stringify(a,void 0)};ie.prototype.parse=function(a){return k.JSON.parse(a,void 0)};function je(){this.a=new ie}function ke(a,b,c){var d=c||\"\";try{md(a,function(a,c){var e=a;ea(a)&&(e=Db(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function le(a,b){var c=new sc;H(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ja(me,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ja(me,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ja(me,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ja(me,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function me(a,b,c,d,e){try{H(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){xc(a,f)}};function T(a){B.call(this);this.headers=new O;this.s=a||null;this.c=!1;this.D=this.a=null;this.K=this.B=\"\";this.j=0;this.g=\"\";this.h=this.I=this.u=this.G=!1;this.l=0;this.C=null;this.L=ne;this.v=this.o=!1}u(T,B);var ne=\"\";T.prototype.b=qc(\"goog.net.XhrIo\");var oe=/^https?$/i,pe=[\"POST\",\"PUT\"];g=T.prototype;\ng.fa=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.B+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.B=a;this.g=\"\";this.j=0;this.K=b;this.G=!1;this.c=!0;this.a=this.s?Qc(this.s):Qc(Oc);this.D=this.s?Ic(this.s):Ic(Oc);this.a.onreadystatechange=r(this.Na,this);try{E(this.b,U(this,\"Opening Xhr\")),this.I=!0,this.a.open(b,String(a),!0),this.I=!1}catch(f){E(this.b,U(this,\"Error opening Xhr: \"+f.message));qe(this,f);return}a=c||\"\";var e=new O(this.headers);\nd&&md(d,function(a,b){e.set(b,a)});d=sa(e.M());c=k.FormData&&a instanceof k.FormData;!(0<=qa(pe,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.L&&(this.a.responseType=this.L);\"withCredentials\"in this.a&&this.a.withCredentials!==this.o&&(this.a.withCredentials=this.o);try{re(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}R(a,b,c);return a};function ye(a){this.ya=0;this.g=[];this.a=new sc;this.I=new Wd;this.X=this.ua=this.D=this.ja=this.b=this.K=this.j=this.U=this.h=this.L=this.i=null;this.Za=this.R=0;this.Xa=!!n(\"internalChannelParams.failFast\",a);this.ka=this.C=this.s=this.l=this.m=this.f=null;this.u=this.xa=this.N=-1;this.T=this.B=this.v=0;this.Wa=n(\"internalChannelParams.baseRetryDelayMs\",a)||5E3;this.$a=n(\"internalChannelParams.retryDelaySeedMs\",a)||1E4;this.Ya=n(\"internalChannelParams.forwardChannelMaxRetries\",a)||2;this.wa=n(\"internalChannelParams.forwardChannelRequestTimeoutMs\",\na)||2E4;this.Ta=a&&a.Kb||void 0;this.G=void 0;this.S=a&&a.supportsCrossDomainXhr||!1;this.J=\"\";this.c=new $d(a&&a.concurrentRequestLimit);this.la=new je;this.o=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;(this.va=a&&a.fastHandshake||!1)&&!this.o&&(D(this.a.a,\"Force backgroundChannelTest when fastHandshake is enabled.\"),this.o=!0);a&&a.Fa&&this.a.Fa()}g=ye.prototype;g.na=8;g.F=1;\nfunction ze(a){H(a.a,\"disconnect()\");Ae(a);if(3==a.F){var b=a.R++,c=M(a.D);R(c,\"SID\",a.J);R(c,\"RID\",b);R(c,\"TYPE\",\"terminate\");Be(a,c);b=new L(a,a.a,b,void 0);b.J=2;b.h=Wc(M(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.h.toString(),\"\"));!c&&k.Image&&((new Image).src=b.h,c=!0);c||(b.a=b.i.ca(null),b.a.fa(b.h));b.D=t();Zc(b)}Ce(a)}\nfunction Ae(a){a.C&&(a.C.abort(),a.C=null);a.b&&(a.b.cancel(),a.b=null);a.l&&(k.clearTimeout(a.l),a.l=null);De(a);a.c.cancel();a.m&&(k.clearTimeout(a.m),a.m=null)}function Ee(a,b){1E3==a.g.length&&J(a.a,function(){return\"Already have 1000 queued maps upon queueing \"+Db(b)});a.g.push(new Zd(a.Za++,b));3==a.F&&Fe(a)}g.La=function(){return 0==this.F};function Fe(a){de(a.c)||a.m||(a.m=Ec(r(a.Qa,a),0),a.v=0)}\nfunction Ge(a,b){var c=a.c;if((c.b?1:c.a?c.a.a.c:0)>=a.c.f-(a.m?1:0))return J(a.a,\"Unexpected retry request is scheduled.\"),!1;if(a.m)return H(a.a,\"Use the retry request that is already scheduled.\"),a.g=b.u.concat(a.g),!0;if(1==a.F||2==a.F||a.v>=(a.Xa?0:a.Ya))return!1;H(a.a,\"Going to retry POST\");a.m=Ec(r(a.Qa,a,b),He(a,a.v));a.v++;return!0}\ng.Qa=function(a){this.m=null;H(this.a,\"startForwardChannel_\");if(1==this.F)if(a)J(this.a,\"Not supposed to retry the open\");else{H(this.a,\"open_()\");this.R=Math.floor(1E5*Math.random());a=this.R++;var b=new L(this,this.a,a,void 0),c=this.i;this.L&&(c?(c=Fa(c),Ha(c,this.L)):c=this.L);null===this.h&&(b.j=c);var d=Ie(this,b),e=M(this.D);R(e,\"RID\",a);R(e,\"CVER\",22);this.o&&this.j&&R(e,\"X-HTTP-Session-Id\",this.j);Be(this,e);this.h&&c&&xe(e,this.h,c);ce(this.c,b);this.va?(R(e,\"$req\",d),R(e,\"SID\",\"null\"),\nb.X=!0,Vc(b,e,null)):Vc(b,e,d);this.F=2}else 3==this.F&&(a?Je(this,a):0==this.g.length?H(this.a,\"startForwardChannel_ returned: nothing to send\"):de(this.c)?J(this.a,\"startForwardChannel_ returned: connection already in progress\"):(Je(this),H(this.a,\"startForwardChannel_ finished, sent request\")))};\nfunction Je(a,b){var c;b?c=b.c:c=a.R++;var d=M(a.D);R(d,\"SID\",a.J);R(d,\"RID\",c);R(d,\"AID\",a.N);Be(a,d);a.h&&a.i&&xe(d,a.h,a.i);c=new L(a,a.a,c,a.v+1);null===a.h&&(c.j=a.i);b&&(a.g=b.u.concat(a.g));b=Ie(a,c);c.setTimeout(Math.round(.5*a.wa)+Math.round(.5*a.wa*Math.random()));ce(a.c,c);Vc(c,d,b)}function Be(a,b){a.f&&md({},function(a,d){R(b,d,a)})}\nfunction Ie(a,b){var c=Math.min(a.g.length,1E3),d=a.f?r(a.f.ab,a.f,a):null;a:for(var e=a.g,f=-1;;){var h=[\"count=\"+c];-1==f?0I)f=Math.max(0,e[v].a-100),m=!1;else try{ke(X,h,\"req\"+I+\"_\")}catch(Mb){d&&d(X)}}if(m){d=h.join(\"&\");break a}}a=a.g.splice(0,c);b.u=a;return d}function Ke(a){if(!a.b&&!a.l){a.T=1;var b=a.Pa;Tb||Ub();Wb||(Tb(),Wb=!0);Pb.add(b,a);a.B=0}}\nfunction Le(a){if(a.b||a.l)return J(a.a,\"Request already in progress\"),!1;if(3<=a.B)return!1;H(a.a,\"Going to retry GET\");a.T++;a.l=Ec(r(a.Pa,a),He(a,a.B));a.B++;return!0}\ng.Pa=function(){this.l=null;H(this.a,\"Creating new HttpRequest\");this.b=new L(this,this.a,\"rpc\",this.T);null===this.h&&(this.b.j=this.i);this.b.N=0;var a=M(this.ua);R(a,\"RID\",\"rpc\");R(a,\"SID\",this.J);R(a,\"CI\",this.ka?\"0\":\"1\");R(a,\"AID\",this.N);Be(this,a);R(a,\"TYPE\",\"xmlhttp\");this.h&&this.i&&xe(a,this.h,this.i);this.G&&this.b.setTimeout(this.G);Yc(this.b,a,!0,this.X);H(this.a,\"New Request created\")};\nfunction Td(a,b,c){H(a.a,\"Test Connection Finished\");var d=b.l;d&&be(a.c,d);a.ka=c;a.u=b.f;H(a.a,\"connectChannel_()\");a.D=Me(a,a.ja);Fe(a)}function Vd(a,b){H(a.a,\"Test Connection Failed\");a.u=b.f;V(a,2)}\ng.Oa=function(a,b){if(0!=this.F&&(this.b==a||ee(this.c,a)))if(this.u=a.C,!a.v&&ee(this.c,a)&&3==this.F){try{var c=this.la.a.parse(b)}catch(f){c=null}if(p(c)&&3==c.length)if(b=c,0==b[0])a:if(H(this.a,\"Server claims our backchannel is missing.\"),this.l)H(this.a,\"But we are currently starting the request.\");else{if(this.b)if(this.b.D+3E3b&&this.ka&&0==this.B&&!this.s&&(this.s=Ec(r(this.ib,this),6E3)));else H(this.a,\"Bad POST response data returned\"),V(this,11)}else if((a.v||this.b==a)&&De(this),!xa(b))for(b=c=this.la.a.parse(b),c=0;cthis.c)throw Error(Ze);this.a=new Ve;this.b=new Xd;this.g=null;this.aa()}u(Ye,w);var Ze=\"[goog.structs.Pool] Min can not be greater than max\";g=Ye.prototype;g.da=function(){var a=t();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.a.length){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}cf.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)ua(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.ma=function(a){Y.H.ma.call(this,a);this.ra()};g.aa=function(){Y.H.aa.call(this);this.ra()};g.w=function(){Y.H.w.call(this);k.clearTimeout(void 0);ua(this.f.a);this.f=null};function Z(a,b,c,d){this.l=a;this.j=!!d;Y.call(this,b,c)}u(Z,Y);Z.prototype.pa=function(){var a=new T,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.o=!0);return a};Z.prototype.sa=function(a){return!a.i&&!a.a};Qe.prototype.createWebChannel=Qe.prototype.a;W.prototype.send=W.prototype.gb;W.prototype.open=W.prototype.fb;W.prototype.close=W.prototype.close;Fc.NO_ERROR=0;Fc.TIMEOUT=8;Fc.HTTP_ERROR=6;Gc.COMPLETE=\"complete\";Kc.EventType=Lc;Lc.OPEN=\"a\";Lc.CLOSE=\"b\";Lc.ERROR=\"c\";Lc.MESSAGE=\"d\";B.prototype.listen=B.prototype.Ia;Z.prototype.getObject=Z.prototype.da;Z.prototype.releaseObject=Z.prototype.ob;T.prototype.listenOnce=T.prototype.Ja;T.prototype.getLastError=T.prototype.hb;T.prototype.getLastErrorCode=T.prototype.Ga;\nT.prototype.getStatus=T.prototype.W;T.prototype.getStatusText=T.prototype.Ha;T.prototype.getResponseJson=T.prototype.eb;T.prototype.getResponseText=T.prototype.V;T.prototype.getResponseText=T.prototype.V;T.prototype.send=T.prototype.fa;module.exports={createWebChannelTransport:Ue,ErrorCode:Fc,EventType:Gc,WebChannel:Kc,XhrIoPool:Z};}).call(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})\n","import firebase from '@firebase/app';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { __extends, __awaiter, __generator } from 'tslib';\nimport { ErrorCode, EventType, WebChannel, XhrIoPool, createWebChannelTransport } from '@firebase/webchannel-wrapper';\n\n/**\r\n * Copyright 2017 Google Inc.\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/** The semver (www.semver.org) version of the SDK. */\r\nvar SDK_VERSION = firebase.SDK_VERSION;\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar logClient = new Logger('@firebase/firestore');\r\nvar LogLevel$1;\r\n(function (LogLevel$$1) {\r\n LogLevel$$1[LogLevel$$1[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel$$1[LogLevel$$1[\"ERROR\"] = 1] = \"ERROR\";\r\n LogLevel$$1[LogLevel$$1[\"SILENT\"] = 2] = \"SILENT\";\r\n})(LogLevel$1 || (LogLevel$1 = {}));\r\n// Helper methods are needed because variables can't be exported as read/write\r\nfunction getLogLevel() {\r\n if (logClient.logLevel === LogLevel.DEBUG) {\r\n return LogLevel$1.DEBUG;\r\n }\r\n else if (logClient.logLevel === LogLevel.SILENT) {\r\n return LogLevel$1.SILENT;\r\n }\r\n else {\r\n return LogLevel$1.ERROR;\r\n }\r\n}\r\nfunction setLogLevel(newLevel) {\r\n /**\r\n * Map the new log level to the associated Firebase Log Level\r\n */\r\n switch (newLevel) {\r\n case LogLevel$1.DEBUG:\r\n logClient.logLevel = LogLevel.DEBUG;\r\n break;\r\n case LogLevel$1.ERROR:\r\n logClient.logLevel = LogLevel.ERROR;\r\n break;\r\n case LogLevel$1.SILENT:\r\n logClient.logLevel = LogLevel.SILENT;\r\n break;\r\n default:\r\n logClient.error(\"Firestore (\" + SDK_VERSION + \"): Invalid value passed to `setLogLevel`\");\r\n }\r\n}\r\nfunction debug(tag, msg) {\r\n var obj = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n obj[_i - 2] = arguments[_i];\r\n }\r\n if (logClient.logLevel <= LogLevel.DEBUG) {\r\n var args = obj.map(argToString);\r\n logClient.debug.apply(logClient, [\"Firestore (\" + SDK_VERSION + \") [\" + tag + \"]: \" + msg].concat(args));\r\n }\r\n}\r\nfunction error(msg) {\r\n var obj = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n obj[_i - 1] = arguments[_i];\r\n }\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n var args = obj.map(argToString);\r\n logClient.error.apply(logClient, [\"Firestore (\" + SDK_VERSION + \"): \" + msg].concat(args));\r\n }\r\n}\r\n/**\r\n * Converts an additional log parameter to a string representation.\r\n */\r\nfunction argToString(obj) {\r\n if (typeof obj === 'string') {\r\n return obj;\r\n }\r\n else {\r\n var platform = PlatformSupport.getPlatform();\r\n try {\r\n return platform.formatJSON(obj);\r\n }\r\n catch (e) {\r\n // Converting to JSON failed, just log the object directly\r\n return obj;\r\n }\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Unconditionally fails, throwing an Error with the given message.\r\n *\r\n * Returns any so it can be used in expressions:\r\n * @example\r\n * let futureVar = fail('not implemented yet');\r\n */\r\nfunction fail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\r\n error(message);\r\n // NOTE: We don't use FirestoreError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n */\r\nfunction assert(assertion, message) {\r\n if (!assertion) {\r\n fail(message);\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Provides singleton helpers where setup code can inject a platform at runtime.\r\n * setPlatform needs to be set before Firestore is used and must be set exactly\r\n * once.\r\n */\r\nvar PlatformSupport = /** @class */ (function () {\r\n function PlatformSupport() {\r\n }\r\n PlatformSupport.setPlatform = function (platform) {\r\n if (PlatformSupport.platform) {\r\n fail('Platform already defined');\r\n }\r\n PlatformSupport.platform = platform;\r\n };\r\n PlatformSupport.getPlatform = function () {\r\n if (!PlatformSupport.platform) {\r\n fail('Platform not set');\r\n }\r\n return PlatformSupport.platform;\r\n };\r\n return PlatformSupport;\r\n}());\r\n/**\r\n * Returns the representation of an empty \"proto\" byte string for the\r\n * platform.\r\n */\r\nfunction emptyByteString() {\r\n return PlatformSupport.getPlatform().emptyByteString;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\r\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\r\nvar Code = {\r\n // Causes are copied from:\r\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\r\n /** Not an error; returned on success. */\r\n OK: 'ok',\r\n /** The operation was cancelled (typically by the caller). */\r\n CANCELLED: 'cancelled',\r\n /** Unknown error or an error from a different error domain. */\r\n UNKNOWN: 'unknown',\r\n /**\r\n * Client specified an invalid argument. Note that this differs from\r\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\r\n * problematic regardless of the state of the system (e.g., a malformed file\r\n * name).\r\n */\r\n INVALID_ARGUMENT: 'invalid-argument',\r\n /**\r\n * Deadline expired before operation could complete. For operations that\r\n * change the state of the system, this error may be returned even if the\r\n * operation has completed successfully. For example, a successful response\r\n * from a server could have been delayed long enough for the deadline to\r\n * expire.\r\n */\r\n DEADLINE_EXCEEDED: 'deadline-exceeded',\r\n /** Some requested entity (e.g., file or directory) was not found. */\r\n NOT_FOUND: 'not-found',\r\n /**\r\n * Some entity that we attempted to create (e.g., file or directory) already\r\n * exists.\r\n */\r\n ALREADY_EXISTS: 'already-exists',\r\n /**\r\n * The caller does not have permission to execute the specified operation.\r\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\r\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\r\n * PERMISSION_DENIED must not be used if the caller can not be identified\r\n * (use UNAUTHENTICATED instead for those errors).\r\n */\r\n PERMISSION_DENIED: 'permission-denied',\r\n /**\r\n * The request does not have valid authentication credentials for the\r\n * operation.\r\n */\r\n UNAUTHENTICATED: 'unauthenticated',\r\n /**\r\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\r\n * entire file system is out of space.\r\n */\r\n RESOURCE_EXHAUSTED: 'resource-exhausted',\r\n /**\r\n * Operation was rejected because the system is not in a state required for\r\n * the operation's execution. For example, directory to be deleted may be\r\n * non-empty, an rmdir operation is applied to a non-directory, etc.\r\n *\r\n * A litmus test that may help a service implementor in deciding\r\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\r\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\r\n * (b) Use ABORTED if the client should retry at a higher-level\r\n * (e.g., restarting a read-modify-write sequence).\r\n * (c) Use FAILED_PRECONDITION if the client should not retry until\r\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\r\n * fails because the directory is non-empty, FAILED_PRECONDITION\r\n * should be returned since the client should not retry unless\r\n * they have first fixed up the directory by deleting files from it.\r\n * (d) Use FAILED_PRECONDITION if the client performs conditional\r\n * REST Get/Update/Delete on a resource and the resource on the\r\n * server does not match the condition. E.g., conflicting\r\n * read-modify-write on the same resource.\r\n */\r\n FAILED_PRECONDITION: 'failed-precondition',\r\n /**\r\n * The operation was aborted, typically due to a concurrency issue like\r\n * sequencer check failures, transaction aborts, etc.\r\n *\r\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\r\n * and UNAVAILABLE.\r\n */\r\n ABORTED: 'aborted',\r\n /**\r\n * Operation was attempted past the valid range. E.g., seeking or reading\r\n * past end of file.\r\n *\r\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\r\n * if the system state changes. For example, a 32-bit file system will\r\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\r\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\r\n * an offset past the current file size.\r\n *\r\n * There is a fair bit of overlap between FAILED_PRECONDITION and\r\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\r\n * when it applies so that callers who are iterating through a space can\r\n * easily look for an OUT_OF_RANGE error to detect when they are done.\r\n */\r\n OUT_OF_RANGE: 'out-of-range',\r\n /** Operation is not implemented or not supported/enabled in this service. */\r\n UNIMPLEMENTED: 'unimplemented',\r\n /**\r\n * Internal errors. Means some invariants expected by underlying System has\r\n * been broken. If you see one of these errors, Something is very broken.\r\n */\r\n INTERNAL: 'internal',\r\n /**\r\n * The service is currently unavailable. This is a most likely a transient\r\n * condition and may be corrected by retrying with a backoff.\r\n *\r\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\r\n * and UNAVAILABLE.\r\n */\r\n UNAVAILABLE: 'unavailable',\r\n /** Unrecoverable data loss or corruption. */\r\n DATA_LOSS: 'data-loss'\r\n};\r\n/**\r\n * An error class used for Firestore-generated errors. Ideally we should be\r\n * using FirebaseError, but integrating with it is overly arduous at the moment,\r\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\r\n * and compatible `code` and `message` fields.)\r\n */\r\nvar FirestoreError = /** @class */ (function (_super) {\r\n __extends(FirestoreError, _super);\r\n function FirestoreError(code, message) {\r\n var _this = _super.call(this, message) || this;\r\n _this.code = code;\r\n _this.message = message;\r\n _this.name = 'FirebaseError';\r\n // HACK: We write a toString property directly because Error is not a real\r\n // class and so inheritance does not work correctly. We could alternatively\r\n // do the same \"back-door inheritance\" trick that FirebaseError does.\r\n _this.toString = function () { return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message; };\r\n return _this;\r\n }\r\n return FirestoreError;\r\n}(Error));\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Helper function to prevent instantiation through the constructor.\r\n *\r\n * This method creates a new constructor that throws when it's invoked.\r\n * The prototype of that constructor is then set to the prototype of the hidden\r\n * \"class\" to expose all the prototype methods and allow for instanceof\r\n * checks.\r\n *\r\n * To also make all the static methods available, all properties of the\r\n * original constructor are copied to the new constructor.\r\n */\r\nfunction makeConstructorPrivate(cls, optionalMessage) {\r\n function PublicConstructor() {\r\n var error = 'This constructor is private.';\r\n if (optionalMessage) {\r\n error += ' ';\r\n error += optionalMessage;\r\n }\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\r\n }\r\n // Make sure instanceof checks work and all methods are exposed on the public\r\n // constructor\r\n PublicConstructor.prototype = cls.prototype;\r\n // Copy any static methods/members\r\n for (var staticProperty in cls) {\r\n if (cls.hasOwnProperty(staticProperty)) {\r\n PublicConstructor[staticProperty] = cls[staticProperty];\r\n }\r\n }\r\n return PublicConstructor;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\n/** Returns the given value if it's defined or the defaultValue otherwise. */\r\nfunction defaulted(value, defaultValue) {\r\n return value !== undefined ? value : defaultValue;\r\n}\r\nfunction forEachNumber(obj, fn) {\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n var num = Number(key);\r\n if (!isNaN(num)) {\r\n fn(num, obj[key]);\r\n }\r\n }\r\n }\r\n}\r\nfunction forEach(obj, fn) {\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n fn(key, obj[key]);\r\n }\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction shallowCopy(obj) {\r\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\r\n var result = {};\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n result[key] = obj[key];\r\n }\r\n }\r\n return result;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Validates the invocation of functionName has the exact number of arguments.\r\n *\r\n * Forward the magic \"arguments\" variable as second parameter on which the\r\n * parameter validation is performed:\r\n * validateExactNumberOfArgs('myFunction', arguments, 2);\r\n */\r\nfunction validateExactNumberOfArgs(functionName, args, numberOfArgs) {\r\n if (args.length !== numberOfArgs) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" +\r\n formatPlural(numberOfArgs, 'argument') +\r\n ', but was called with ' +\r\n formatPlural(args.length, 'argument') +\r\n '.');\r\n }\r\n}\r\n/**\r\n * Validates the invocation of functionName has at least the provided number of\r\n * arguments (but can have many more).\r\n *\r\n * Forward the magic \"arguments\" variable as second parameter on which the\r\n * parameter validation is performed:\r\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\r\n */\r\nfunction validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\r\n if (args.length < minNumberOfArgs) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" +\r\n formatPlural(minNumberOfArgs, 'argument') +\r\n ', but was called with ' +\r\n formatPlural(args.length, 'argument') +\r\n '.');\r\n }\r\n}\r\n/**\r\n * Validates the invocation of functionName has number of arguments between\r\n * the values provided.\r\n *\r\n * Forward the magic \"arguments\" variable as second parameter on which the\r\n * parameter validation is performed:\r\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\r\n */\r\nfunction validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\r\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\r\n (maxNumberOfArgs + \" arguments, but was called with \") +\r\n formatPlural(args.length, 'argument') +\r\n '.');\r\n }\r\n}\r\n/**\r\n * Validates the provided argument is an array and has as least the expected\r\n * number of elements.\r\n */\r\nfunction validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\r\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\r\n 'array with at least ' +\r\n (formatPlural(minNumberOfElements, 'element') + \".\"));\r\n }\r\n}\r\n/**\r\n * Validates the provided positional argument has the native JavaScript type\r\n * using typeof checks.\r\n */\r\nfunction validateArgType(functionName, type, position, argument) {\r\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\r\n}\r\n/**\r\n * Validates the provided argument has the native JavaScript type using\r\n * typeof checks or is undefined.\r\n */\r\nfunction validateOptionalArgType(functionName, type, position, argument) {\r\n if (argument !== undefined) {\r\n validateArgType(functionName, type, position, argument);\r\n }\r\n}\r\n/**\r\n * Validates the provided named option has the native JavaScript type using\r\n * typeof checks.\r\n */\r\nfunction validateNamedType(functionName, type, optionName, argument) {\r\n validateType(functionName, type, optionName + \" option\", argument);\r\n}\r\n/**\r\n * Validates the provided named option has the native JavaScript type using\r\n * typeof checks or is undefined.\r\n */\r\nfunction validateNamedOptionalType(functionName, type, optionName, argument) {\r\n if (argument !== undefined) {\r\n validateNamedType(functionName, type, optionName, argument);\r\n }\r\n}\r\n/**\r\n * Validates that the provided named option equals one of the expected values.\r\n */\r\nfunction validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\r\n var expectedDescription = [];\r\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\r\n var val = expected_1[_i];\r\n if (val === input) {\r\n return;\r\n }\r\n expectedDescription.push(valueDescription(val));\r\n }\r\n var actualDescription = valueDescription(input);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', '));\r\n}\r\n/**\r\n * Validates that the provided named option equals one of the expected values or\r\n * is undefined.\r\n */\r\nfunction validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\r\n if (input !== undefined) {\r\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\r\n }\r\n}\r\n/** Helper to validate the type of a provided input. */\r\nfunction validateType(functionName, type, inputName, input) {\r\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\r\n var description = valueDescription(input);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\r\n (\"to be of type \" + type + \", but it was: \" + description));\r\n }\r\n}\r\n/**\r\n * Returns true iff it's a non-null object without a custom prototype\r\n * (i.e. excludes Array, Date, etc.).\r\n */\r\nfunction isPlainObject(input) {\r\n return (typeof input === 'object' &&\r\n input !== null &&\r\n Object.getPrototypeOf(input) === Object.prototype);\r\n}\r\n/** Returns a string describing the type / value of the provided input. */\r\nfunction valueDescription(input) {\r\n if (input === undefined) {\r\n return 'undefined';\r\n }\r\n else if (input === null) {\r\n return 'null';\r\n }\r\n else if (typeof input === 'string') {\r\n if (input.length > 20) {\r\n input = input.substring(0, 20) + \"...\";\r\n }\r\n return JSON.stringify(input);\r\n }\r\n else if (typeof input === 'number' || typeof input === 'boolean') {\r\n return '' + input;\r\n }\r\n else if (typeof input === 'object') {\r\n if (input instanceof Array) {\r\n return 'an array';\r\n }\r\n else {\r\n var customObjectName = tryGetCustomObjectType(input);\r\n if (customObjectName) {\r\n return \"a custom \" + customObjectName + \" object\";\r\n }\r\n else {\r\n return 'an object';\r\n }\r\n }\r\n }\r\n else if (typeof input === 'function') {\r\n return 'a function';\r\n }\r\n else {\r\n return fail('Unknown wrong type: ' + typeof input);\r\n }\r\n}\r\n/** Hacky method to try to get the constructor name for an object. */\r\nfunction tryGetCustomObjectType(input) {\r\n if (input.constructor) {\r\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\r\n var results = funcNameRegex.exec(input.constructor.toString());\r\n if (results && results.length > 1) {\r\n return results[1];\r\n }\r\n }\r\n return null;\r\n}\r\n/** Validates the provided argument is defined. */\r\nfunction validateDefined(functionName, position, argument) {\r\n if (argument === undefined) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\r\n \"argument, but it was undefined.\");\r\n }\r\n}\r\n/**\r\n * Validates the provided positional argument is an object, and its keys and\r\n * values match the expected keys and types provided in optionTypes.\r\n */\r\nfunction validateOptionNames(functionName, options, optionNames) {\r\n forEach(options, function (key, _) {\r\n if (optionNames.indexOf(key) < 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\r\n 'Available options: ' +\r\n optionNames.join(', '));\r\n }\r\n });\r\n}\r\n/**\r\n * Helper method to throw an error that the provided argument did not pass\r\n * an instanceof check.\r\n */\r\nfunction invalidClassError(functionName, type, position, argument) {\r\n var description = valueDescription(argument);\r\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\r\n (\"argument to be a \" + type + \", but it was: \" + description));\r\n}\r\n/** Converts a number to its english word representation */\r\nfunction ordinal(num) {\r\n switch (num) {\r\n case 1:\r\n return 'first';\r\n case 2:\r\n return 'second';\r\n case 3:\r\n return 'third';\r\n default:\r\n return num + 'th';\r\n }\r\n}\r\n/**\r\n * Formats the given word as plural conditionally given the preceding number.\r\n */\r\nfunction formatPlural(num, str) {\r\n return num + \" \" + str + (num === 1 ? '' : 's');\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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// tslint:disable-next-line:class-as-namespace\r\nvar AutoId = /** @class */ (function () {\r\n function AutoId() {\r\n }\r\n AutoId.newId = function () {\r\n // Alphanumeric characters\r\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\r\n var autoId = '';\r\n for (var i = 0; i < 20; i++) {\r\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\r\n }\r\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\r\n return autoId;\r\n };\r\n return AutoId;\r\n}());\r\nfunction primitiveComparator(left, right) {\r\n if (left < right)\r\n return -1;\r\n if (left > right)\r\n return 1;\r\n return 0;\r\n}\r\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\r\nfunction equals(left, right) {\r\n if (left !== null && left !== undefined) {\r\n return !!(right && left.isEqual(right));\r\n }\r\n else {\r\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\r\n // smart enough.\r\n return left === right;\r\n }\r\n}\r\n/** Helper to compare arrays using isEqual(). */\r\nfunction arrayEquals(left, right) {\r\n if (left.length !== right.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < left.length; i++) {\r\n if (!left[i].isEqual(right[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * Returns the largest lexicographically smaller string of equal or smaller\r\n * length. Returns an empty string if there is no such predecessor (if the input\r\n * is empty).\r\n *\r\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\r\n * in use for indexeddb because that depends on lexicographical ordering but\r\n * shouldn't be used elsewhere.\r\n */\r\nfunction immediatePredecessor(s) {\r\n // We can decrement the last character in the string and be done\r\n // unless that character is 0 (0x0000), in which case we have to erase the\r\n // last character.\r\n var lastIndex = s.length - 1;\r\n if (s.length === 0) {\r\n // Special case the empty string.\r\n return '';\r\n }\r\n else if (s.charAt(lastIndex) === '\\0') {\r\n return s.substring(0, lastIndex);\r\n }\r\n else {\r\n return (s.substring(0, lastIndex) +\r\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\r\n }\r\n}\r\n/**\r\n * Returns the immediate lexicographically-following string. This is useful to\r\n * construct an inclusive range for indexeddb iterators.\r\n */\r\nfunction immediateSuccessor(s) {\r\n // Return the input string, with an additional NUL byte appended.\r\n return s + '\\0';\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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/** Helper function to assert Uint8Array is available at runtime. */\r\nfunction assertUint8ArrayAvailable() {\r\n if (typeof Uint8Array === 'undefined') {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\r\n }\r\n}\r\n/** Helper function to assert Base64 functions are available at runtime. */\r\nfunction assertBase64Available() {\r\n if (!PlatformSupport.getPlatform().base64Available) {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\r\n }\r\n}\r\n/**\r\n * Immutable class holding a blob (binary data).\r\n * This class is directly exposed in the public API.\r\n *\r\n * Note that while you can't hide the constructor in JavaScript code, we are\r\n * using the hack above to make sure no-one outside this module can call it.\r\n */\r\nvar Blob = /** @class */ (function () {\r\n function Blob(binaryString) {\r\n assertBase64Available();\r\n this._binaryString = binaryString;\r\n }\r\n Blob.fromBase64String = function (base64) {\r\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\r\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\r\n assertBase64Available();\r\n try {\r\n var binaryString = PlatformSupport.getPlatform().atob(base64);\r\n return new Blob(binaryString);\r\n }\r\n catch (e) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\r\n }\r\n };\r\n Blob.fromUint8Array = function (array) {\r\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\r\n assertUint8ArrayAvailable();\r\n if (!(array instanceof Uint8Array)) {\r\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\r\n }\r\n // We can't call array.map directly because it expects the return type to\r\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\r\n // map on the Array prototype.\r\n var binaryString = Array.prototype.map\r\n .call(array, function (char) {\r\n return String.fromCharCode(char);\r\n })\r\n .join('');\r\n return new Blob(binaryString);\r\n };\r\n Blob.prototype.toBase64 = function () {\r\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\r\n assertBase64Available();\r\n return PlatformSupport.getPlatform().btoa(this._binaryString);\r\n };\r\n Blob.prototype.toUint8Array = function () {\r\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\r\n assertUint8ArrayAvailable();\r\n var buffer = new Uint8Array(this._binaryString.length);\r\n for (var i = 0; i < this._binaryString.length; i++) {\r\n buffer[i] = this._binaryString.charCodeAt(i);\r\n }\r\n return buffer;\r\n };\r\n Blob.prototype.toString = function () {\r\n return 'Blob(base64: ' + this.toBase64() + ')';\r\n };\r\n Blob.prototype.isEqual = function (other) {\r\n return this._binaryString === other._binaryString;\r\n };\r\n /**\r\n * Actually private to JS consumers of our API, so this function is prefixed\r\n * with an underscore.\r\n */\r\n Blob.prototype._compareTo = function (other) {\r\n return primitiveComparator(this._binaryString, other._binaryString);\r\n };\r\n return Blob;\r\n}());\r\n// Public instance that disallows construction at runtime. This constructor is\r\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\r\n// publicly. Internally we still use Blob which has a type checked private\r\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\r\n// instanceof checks.\r\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\r\n// we need to use Blob as type and export it too.\r\n// tslint:disable-next-line:variable-name We're treating this as a class name.\r\nvar PublicBlob = makeConstructorPrivate(Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Immutable class representing a geo point as latitude-longitude pair.\r\n * This class is directly exposed in the public API, including its constructor.\r\n */\r\nvar GeoPoint = /** @class */ (function () {\r\n function GeoPoint(latitude, longitude) {\r\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\r\n validateArgType('GeoPoint', 'number', 1, latitude);\r\n validateArgType('GeoPoint', 'number', 2, longitude);\r\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\r\n }\r\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\r\n }\r\n this._lat = latitude;\r\n this._long = longitude;\r\n }\r\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\r\n /**\r\n * Returns the latitude of this geo point, a number between -90 and 90.\r\n */\r\n get: function () {\r\n return this._lat;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\r\n /**\r\n * Returns the longitude of this geo point, a number between -180 and 180.\r\n */\r\n get: function () {\r\n return this._long;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n GeoPoint.prototype.isEqual = function (other) {\r\n return this._lat === other._lat && this._long === other._long;\r\n };\r\n /**\r\n * Actually private to JS consumers of our API, so this function is prefixed\r\n * with an underscore.\r\n */\r\n GeoPoint.prototype._compareTo = function (other) {\r\n return (primitiveComparator(this._lat, other._lat) ||\r\n primitiveComparator(this._long, other._long));\r\n };\r\n return GeoPoint;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar Timestamp = /** @class */ (function () {\r\n function Timestamp(seconds, nanoseconds) {\r\n this.seconds = seconds;\r\n this.nanoseconds = nanoseconds;\r\n if (nanoseconds < 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);\r\n }\r\n if (nanoseconds >= 1e9) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);\r\n }\r\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\r\n if (seconds < -62135596800) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);\r\n }\r\n // This will break in the year 10,000.\r\n if (seconds >= 253402300800) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);\r\n }\r\n }\r\n Timestamp.now = function () {\r\n return Timestamp.fromMillis(Date.now());\r\n };\r\n Timestamp.fromDate = function (date) {\r\n return Timestamp.fromMillis(date.getTime());\r\n };\r\n Timestamp.fromMillis = function (milliseconds) {\r\n var seconds = Math.floor(milliseconds / 1000);\r\n var nanos = (milliseconds - seconds * 1000) * 1e6;\r\n return new Timestamp(seconds, nanos);\r\n };\r\n Timestamp.prototype.toDate = function () {\r\n return new Date(this.toMillis());\r\n };\r\n Timestamp.prototype.toMillis = function () {\r\n return this.seconds * 1000 + this.nanoseconds / 1e6;\r\n };\r\n Timestamp.prototype._compareTo = function (other) {\r\n if (this.seconds === other.seconds) {\r\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\r\n }\r\n return primitiveComparator(this.seconds, other.seconds);\r\n };\r\n Timestamp.prototype.isEqual = function (other) {\r\n return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds);\r\n };\r\n Timestamp.prototype.toString = function () {\r\n return ('Timestamp(seconds=' +\r\n this.seconds +\r\n ', nanoseconds=' +\r\n this.nanoseconds +\r\n ')');\r\n };\r\n return Timestamp;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar DatabaseInfo = /** @class */ (function () {\r\n /**\r\n * Constructs a DatabaseInfo using the provided host, databaseId and\r\n * persistenceKey.\r\n *\r\n * @param databaseId The database to use.\r\n * @param persistenceKey A unique identifier for this Firestore's local\r\n * storage (used in conjunction with the databaseId).\r\n * @param host The Firestore backend host to connect to.\r\n * @param ssl Whether to use SSL when connecting.\r\n */\r\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\r\n this.databaseId = databaseId;\r\n this.persistenceKey = persistenceKey;\r\n this.host = host;\r\n this.ssl = ssl;\r\n }\r\n return DatabaseInfo;\r\n}());\r\n/** The default database name for a project. */\r\nvar DEFAULT_DATABASE_NAME = '(default)';\r\n/** Represents the database ID a Firestore client is associated with. */\r\nvar DatabaseId = /** @class */ (function () {\r\n function DatabaseId(projectId, database) {\r\n this.projectId = projectId;\r\n this.database = database ? database : DEFAULT_DATABASE_NAME;\r\n }\r\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\r\n get: function () {\r\n return this.database === DEFAULT_DATABASE_NAME;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n DatabaseId.prototype.isEqual = function (other) {\r\n return (other instanceof DatabaseId &&\r\n other.projectId === this.projectId &&\r\n other.database === this.database);\r\n };\r\n DatabaseId.prototype.compareTo = function (other) {\r\n return (primitiveComparator(this.projectId, other.projectId) ||\r\n primitiveComparator(this.database, other.database));\r\n };\r\n return DatabaseId;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar DOCUMENT_KEY_NAME = '__name__';\r\n/**\r\n * Path represents an ordered sequence of string segments.\r\n */\r\nvar Path = /** @class */ (function () {\r\n function Path(segments, offset, length) {\r\n this.init(segments, offset, length);\r\n }\r\n /**\r\n * An initialization method that can be called from outside the constructor.\r\n * We need this so that we can have a non-static construct method that returns\r\n * the polymorphic `this` type.\r\n */\r\n Path.prototype.init = function (segments, offset, length) {\r\n if (offset === undefined) {\r\n offset = 0;\r\n }\r\n else if (offset > segments.length) {\r\n fail('offset ' + offset + ' out of range ' + segments.length);\r\n }\r\n if (length === undefined) {\r\n length = segments.length - offset;\r\n }\r\n else if (length > segments.length - offset) {\r\n fail('length ' + length + ' out of range ' + (segments.length - offset));\r\n }\r\n this.segments = segments;\r\n this.offset = offset;\r\n this.len = length;\r\n };\r\n /**\r\n * Constructs a new instance of Path using the same concrete type as `this`.\r\n * We need this instead of using the normal constructor, because polymorphic\r\n * `this` doesn't work on static methods.\r\n */\r\n Path.prototype.construct = function (segments, offset, length) {\r\n var path = Object.create(Object.getPrototypeOf(this));\r\n path.init(segments, offset, length);\r\n return path;\r\n };\r\n Object.defineProperty(Path.prototype, \"length\", {\r\n get: function () {\r\n return this.len;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Path.prototype.isEqual = function (other) {\r\n return Path.comparator(this, other) === 0;\r\n };\r\n Path.prototype.child = function (nameOrPath) {\r\n var segments = this.segments.slice(this.offset, this.limit());\r\n if (nameOrPath instanceof Path) {\r\n nameOrPath.forEach(function (segment) {\r\n segments.push(segment);\r\n });\r\n }\r\n else if (typeof nameOrPath === 'string') {\r\n segments.push(nameOrPath);\r\n }\r\n else {\r\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\r\n }\r\n return this.construct(segments);\r\n };\r\n /** The index of one past the last segment of the path. */\r\n Path.prototype.limit = function () {\r\n return this.offset + this.length;\r\n };\r\n Path.prototype.popFirst = function (size) {\r\n size = size === undefined ? 1 : size;\r\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\r\n return this.construct(this.segments, this.offset + size, this.length - size);\r\n };\r\n Path.prototype.popLast = function () {\r\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\r\n return this.construct(this.segments, this.offset, this.length - 1);\r\n };\r\n Path.prototype.firstSegment = function () {\r\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\r\n return this.segments[this.offset];\r\n };\r\n Path.prototype.lastSegment = function () {\r\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\r\n return this.segments[this.limit() - 1];\r\n };\r\n Path.prototype.get = function (index) {\r\n assert(index < this.length, 'Index out of range');\r\n return this.segments[this.offset + index];\r\n };\r\n Path.prototype.isEmpty = function () {\r\n return this.length === 0;\r\n };\r\n Path.prototype.isPrefixOf = function (other) {\r\n if (other.length < this.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.length; i++) {\r\n if (this.get(i) !== other.get(i)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n Path.prototype.forEach = function (fn) {\r\n for (var i = this.offset, end = this.limit(); i < end; i++) {\r\n fn(this.segments[i]);\r\n }\r\n };\r\n Path.prototype.toArray = function () {\r\n return this.segments.slice(this.offset, this.limit());\r\n };\r\n Path.comparator = function (p1, p2) {\r\n var len = Math.min(p1.length, p2.length);\r\n for (var i = 0; i < len; i++) {\r\n var left = p1.get(i);\r\n var right = p2.get(i);\r\n if (left < right)\r\n return -1;\r\n if (left > right)\r\n return 1;\r\n }\r\n if (p1.length < p2.length)\r\n return -1;\r\n if (p1.length > p2.length)\r\n return 1;\r\n return 0;\r\n };\r\n return Path;\r\n}());\r\n/**\r\n * A slash-separated path for navigating resources (documents and collections)\r\n * within Firestore.\r\n */\r\nvar ResourcePath = /** @class */ (function (_super) {\r\n __extends(ResourcePath, _super);\r\n function ResourcePath() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n ResourcePath.prototype.canonicalString = function () {\r\n // NOTE: The client is ignorant of any path segments containing escape\r\n // sequences (e.g. __id123__) and just passes them through raw (they exist\r\n // for legacy reasons and should not be used frequently).\r\n return this.toArray().join('/');\r\n };\r\n ResourcePath.prototype.toString = function () {\r\n return this.canonicalString();\r\n };\r\n /**\r\n * Creates a resource path from the given slash-delimited string.\r\n */\r\n ResourcePath.fromString = function (path) {\r\n // NOTE: The client is ignorant of any path segments containing escape\r\n // sequences (e.g. __id123__) and just passes them through raw (they exist\r\n // for legacy reasons and should not be used frequently).\r\n if (path.indexOf('//') >= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\r\n }\r\n // We may still have an empty segment at the beginning or end if they had a\r\n // leading or trailing slash (which we allow).\r\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\r\n return new ResourcePath(segments);\r\n };\r\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\r\n return ResourcePath;\r\n}(Path));\r\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\r\n/** A dot-separated path for navigating sub-objects within a document. */\r\nvar FieldPath = /** @class */ (function (_super) {\r\n __extends(FieldPath, _super);\r\n function FieldPath() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n /**\r\n * Returns true if the string could be used as a segment in a field path\r\n * without escaping.\r\n */\r\n FieldPath.isValidIdentifier = function (segment) {\r\n return identifierRegExp.test(segment);\r\n };\r\n FieldPath.prototype.canonicalString = function () {\r\n return this.toArray()\r\n .map(function (str) {\r\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\r\n if (!FieldPath.isValidIdentifier(str)) {\r\n str = '`' + str + '`';\r\n }\r\n return str;\r\n })\r\n .join('.');\r\n };\r\n FieldPath.prototype.toString = function () {\r\n return this.canonicalString();\r\n };\r\n /**\r\n * Returns true if this field references the key of a document.\r\n */\r\n FieldPath.prototype.isKeyField = function () {\r\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\r\n };\r\n /**\r\n * The field designating the key of a document.\r\n */\r\n FieldPath.keyField = function () {\r\n return new FieldPath([DOCUMENT_KEY_NAME]);\r\n };\r\n /**\r\n * Parses a field string from the given server-formatted string.\r\n *\r\n * - Splitting the empty string is not allowed (for now at least).\r\n * - Empty segments within the string (e.g. if there are two consecutive\r\n * separators) are not allowed.\r\n *\r\n * TODO(b/37244157): we should make this more strict. Right now, it allows\r\n * non-identifier path components, even if they aren't escaped.\r\n */\r\n FieldPath.fromServerFormat = function (path) {\r\n var segments = [];\r\n var current = '';\r\n var i = 0;\r\n var addCurrentSegment = function () {\r\n if (current.length === 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\r\n \"with '.', end with '.', or contain '..'\");\r\n }\r\n segments.push(current);\r\n current = '';\r\n };\r\n var inBackticks = false;\r\n while (i < path.length) {\r\n var c = path[i];\r\n if (c === '\\\\') {\r\n if (i + 1 === path.length) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\r\n }\r\n var next = path[i + 1];\r\n if (!(next === '\\\\' || next === '.' || next === '`')) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\r\n }\r\n current += next;\r\n i += 2;\r\n }\r\n else if (c === '`') {\r\n inBackticks = !inBackticks;\r\n i++;\r\n }\r\n else if (c === '.' && !inBackticks) {\r\n addCurrentSegment();\r\n i++;\r\n }\r\n else {\r\n current += c;\r\n i++;\r\n }\r\n }\r\n addCurrentSegment();\r\n if (inBackticks) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\r\n }\r\n return new FieldPath(segments);\r\n };\r\n FieldPath.EMPTY_PATH = new FieldPath([]);\r\n return FieldPath;\r\n}(Path));\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar DocumentKey = /** @class */ (function () {\r\n function DocumentKey(path) {\r\n this.path = path;\r\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\r\n path.toArray().join('/'));\r\n }\r\n DocumentKey.prototype.isEqual = function (other) {\r\n return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);\r\n };\r\n DocumentKey.prototype.toString = function () {\r\n return this.path.toString();\r\n };\r\n DocumentKey.comparator = function (k1, k2) {\r\n return ResourcePath.comparator(k1.path, k2.path);\r\n };\r\n DocumentKey.isDocumentKey = function (path) {\r\n return path.length % 2 === 0;\r\n };\r\n /**\r\n * Creates and returns a new document key with the given segments.\r\n *\r\n * @param path The segments of the path to the document\r\n * @return A new instance of DocumentKey\r\n */\r\n DocumentKey.fromSegments = function (segments) {\r\n return new DocumentKey(new ResourcePath(segments.slice()));\r\n };\r\n /**\r\n * Creates and returns a new document key using '/' to split the string into\r\n * segments.\r\n *\r\n * @param path The slash-separated path string to the document\r\n * @return A new instance of DocumentKey\r\n */\r\n DocumentKey.fromPathString = function (path) {\r\n return new DocumentKey(ResourcePath.fromString(path));\r\n };\r\n DocumentKey.EMPTY = new DocumentKey(new ResourcePath([]));\r\n return DocumentKey;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar Document = /** @class */ (function () {\r\n function Document(key, version, data, options) {\r\n this.key = key;\r\n this.version = version;\r\n this.data = data;\r\n this.hasLocalMutations = options.hasLocalMutations;\r\n }\r\n Document.prototype.field = function (path) {\r\n return this.data.field(path);\r\n };\r\n Document.prototype.fieldValue = function (path) {\r\n var field = this.field(path);\r\n return field ? field.value() : undefined;\r\n };\r\n Document.prototype.value = function () {\r\n return this.data.value();\r\n };\r\n Document.prototype.isEqual = function (other) {\r\n return (other instanceof Document &&\r\n this.key.isEqual(other.key) &&\r\n this.version.isEqual(other.version) &&\r\n this.data.isEqual(other.data) &&\r\n this.hasLocalMutations === other.hasLocalMutations);\r\n };\r\n Document.prototype.toString = function () {\r\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\r\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\r\n };\r\n Document.compareByKey = function (d1, d2) {\r\n return DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n Document.compareByField = function (field, d1, d2) {\r\n var v1 = d1.field(field);\r\n var v2 = d2.field(field);\r\n if (v1 !== undefined && v2 !== undefined) {\r\n return v1.compareTo(v2);\r\n }\r\n else {\r\n return fail(\"Trying to compare documents on fields that don't exist\");\r\n }\r\n };\r\n return Document;\r\n}());\r\n/**\r\n * A class representing a deleted document.\r\n * Version is set to 0 if we don't point to any specific time, otherwise it\r\n * denotes time we know it didn't exist at.\r\n */\r\nvar NoDocument = /** @class */ (function () {\r\n function NoDocument(key, version) {\r\n this.key = key;\r\n this.version = version;\r\n }\r\n NoDocument.prototype.toString = function () {\r\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\r\n };\r\n NoDocument.prototype.isEqual = function (other) {\r\n return (other &&\r\n other.version.isEqual(this.version) &&\r\n other.key.isEqual(this.key));\r\n };\r\n NoDocument.compareByKey = function (d1, d2) {\r\n return DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n return NoDocument;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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// An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n// tree.\r\nvar SortedMap = /** @class */ (function () {\r\n function SortedMap(comparator, root) {\r\n this.comparator = comparator;\r\n this.root = root ? root : LLRBNode.EMPTY;\r\n }\r\n // Returns a copy of the map, with the specified key/value added or replaced.\r\n SortedMap.prototype.insert = function (key, value) {\r\n return new SortedMap(this.comparator, this.root\r\n .insert(key, value, this.comparator)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n };\r\n // Returns a copy of the map, with the specified key removed.\r\n SortedMap.prototype.remove = function (key) {\r\n return new SortedMap(this.comparator, this.root\r\n .remove(key, this.comparator)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n };\r\n // Returns the value of the node with the given key, or null.\r\n SortedMap.prototype.get = function (key) {\r\n var node = this.root;\r\n while (!node.isEmpty()) {\r\n var cmp = this.comparator(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n };\r\n // Returns the index of the element in this sorted map, or -1 if it doesn't\r\n // exist.\r\n SortedMap.prototype.indexOf = function (key) {\r\n // Number of nodes that were pruned when descending right\r\n var prunedNodes = 0;\r\n var node = this.root;\r\n while (!node.isEmpty()) {\r\n var cmp = this.comparator(key, node.key);\r\n if (cmp === 0) {\r\n return prunedNodes + node.left.size;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else {\r\n // Count all nodes left of the node plus the node itself\r\n prunedNodes += node.left.size + 1;\r\n node = node.right;\r\n }\r\n }\r\n // Node not found\r\n return -1;\r\n };\r\n SortedMap.prototype.isEmpty = function () {\r\n return this.root.isEmpty();\r\n };\r\n Object.defineProperty(SortedMap.prototype, \"size\", {\r\n // Returns the total number of nodes in the map.\r\n get: function () {\r\n return this.root.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n // Returns the minimum key in the map.\r\n SortedMap.prototype.minKey = function () {\r\n return this.root.minKey();\r\n };\r\n // Returns the maximum key in the map.\r\n SortedMap.prototype.maxKey = function () {\r\n return this.root.maxKey();\r\n };\r\n // Traverses the map in key order and calls the specified action function\r\n // for each key/value pair. If action returns true, traversal is aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n SortedMap.prototype.inorderTraversal = function (action) {\r\n return this.root.inorderTraversal(action);\r\n };\r\n SortedMap.prototype.forEach = function (fn) {\r\n this.inorderTraversal(function (k, v) {\r\n fn(k, v);\r\n return false;\r\n });\r\n };\r\n // Traverses the map in reverse key order and calls the specified action\r\n // function for each key/value pair. If action returns true, traversal is\r\n // aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n SortedMap.prototype.reverseTraversal = function (action) {\r\n return this.root.reverseTraversal(action);\r\n };\r\n // Returns an iterator over the SortedMap.\r\n SortedMap.prototype.getIterator = function () {\r\n return new SortedMapIterator(this.root, null, this.comparator, false);\r\n };\r\n SortedMap.prototype.getIteratorFrom = function (key) {\r\n return new SortedMapIterator(this.root, key, this.comparator, false);\r\n };\r\n SortedMap.prototype.getReverseIterator = function () {\r\n return new SortedMapIterator(this.root, null, this.comparator, true);\r\n };\r\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\r\n return new SortedMapIterator(this.root, key, this.comparator, true);\r\n };\r\n return SortedMap;\r\n}()); // end SortedMap\r\n// An iterator over an LLRBNode.\r\nvar SortedMapIterator = /** @class */ (function () {\r\n function SortedMapIterator(node, startKey, comparator, isReverse) {\r\n this.isReverse = isReverse;\r\n this.nodeStack = [];\r\n var cmp = 1;\r\n while (!node.isEmpty()) {\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse)\r\n cmp *= -1;\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack,\r\n // but stop iterating;\r\n this.nodeStack.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move\r\n // to the next one\r\n this.nodeStack.push(node);\r\n if (this.isReverse) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n SortedMapIterator.prototype.getNext = function () {\r\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\r\n var node = this.nodeStack.pop();\r\n var result = { key: node.key, value: node.value };\r\n if (this.isReverse) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n };\r\n SortedMapIterator.prototype.hasNext = function () {\r\n return this.nodeStack.length > 0;\r\n };\r\n SortedMapIterator.prototype.peek = function () {\r\n if (this.nodeStack.length === 0)\r\n return null;\r\n var node = this.nodeStack[this.nodeStack.length - 1];\r\n return { key: node.key, value: node.value };\r\n };\r\n return SortedMapIterator;\r\n}()); // end SortedMapIterator\r\n// Represents a node in a Left-leaning Red-Black tree.\r\nvar LLRBNode = /** @class */ (function () {\r\n function LLRBNode(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left = left != null ? left : LLRBNode.EMPTY;\r\n this.right = right != null ? right : LLRBNode.EMPTY;\r\n this.size = this.left.size + 1 + this.right.size;\r\n }\r\n // Returns a copy of the current node, optionally replacing pieces of it.\r\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\r\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\r\n };\r\n LLRBNode.prototype.isEmpty = function () {\r\n return false;\r\n };\r\n // Traverses the tree in key order and calls the specified action function\r\n // for each node. If action returns true, traversal is aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n LLRBNode.prototype.inorderTraversal = function (action) {\r\n return (this.left.inorderTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n };\r\n // Traverses the tree in reverse key order and calls the specified action\r\n // function for each node. If action returns true, traversal is aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n LLRBNode.prototype.reverseTraversal = function (action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n };\r\n // Returns the minimum node in the tree.\r\n LLRBNode.prototype.min = function () {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min();\r\n }\r\n };\r\n // Returns the maximum key in the tree.\r\n LLRBNode.prototype.minKey = function () {\r\n return this.min().key;\r\n };\r\n // Returns the maximum key in the tree.\r\n LLRBNode.prototype.maxKey = function () {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n };\r\n // Returns new tree, with the key/value added.\r\n LLRBNode.prototype.insert = function (key, value, comparator) {\r\n var n = this;\r\n var cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp();\r\n };\r\n LLRBNode.prototype.removeMin = function () {\r\n if (this.left.isEmpty()) {\r\n return LLRBNode.EMPTY;\r\n }\r\n var n = this;\r\n if (!n.left.isRed() && !n.left.left.isRed())\r\n n = n.moveRedLeft();\r\n n = n.copy(null, null, null, n.left.removeMin(), null);\r\n return n.fixUp();\r\n };\r\n // Returns new tree, with the specified item removed.\r\n LLRBNode.prototype.remove = function (key, comparator) {\r\n var smallest;\r\n var n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\r\n n = n.moveRedLeft();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed())\r\n n = n.rotateRight();\r\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\r\n n = n.moveRedRight();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return LLRBNode.EMPTY;\r\n }\r\n else {\r\n smallest = n.right.min();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp();\r\n };\r\n LLRBNode.prototype.isRed = function () {\r\n return this.color;\r\n };\r\n // Returns new tree after performing any needed rotations.\r\n LLRBNode.prototype.fixUp = function () {\r\n var n = this;\r\n if (n.right.isRed() && !n.left.isRed())\r\n n = n.rotateLeft();\r\n if (n.left.isRed() && n.left.left.isRed())\r\n n = n.rotateRight();\r\n if (n.left.isRed() && n.right.isRed())\r\n n = n.colorFlip();\r\n return n;\r\n };\r\n LLRBNode.prototype.moveRedLeft = function () {\r\n var n = this.colorFlip();\r\n if (n.right.left.isRed()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight());\r\n n = n.rotateLeft();\r\n n = n.colorFlip();\r\n }\r\n return n;\r\n };\r\n LLRBNode.prototype.moveRedRight = function () {\r\n var n = this.colorFlip();\r\n if (n.left.left.isRed()) {\r\n n = n.rotateRight();\r\n n = n.colorFlip();\r\n }\r\n return n;\r\n };\r\n LLRBNode.prototype.rotateLeft = function () {\r\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n };\r\n LLRBNode.prototype.rotateRight = function () {\r\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n };\r\n LLRBNode.prototype.colorFlip = function () {\r\n var left = this.left.copy(null, null, !this.left.color, null, null);\r\n var right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n };\r\n // For testing.\r\n LLRBNode.prototype.checkMaxDepth = function () {\r\n var blackDepth = this.check();\r\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\r\n // leaves is equal on both sides. This function verifies that or asserts.\r\n LLRBNode.prototype.check = function () {\r\n if (this.isRed() && this.left.isRed()) {\r\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed()) {\r\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n var blackDepth = this.left.check();\r\n if (blackDepth !== this.right.check()) {\r\n throw fail('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed() ? 0 : 1);\r\n }\r\n };\r\n // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\r\n LLRBNode.EMPTY = null;\r\n LLRBNode.RED = true;\r\n LLRBNode.BLACK = false;\r\n return LLRBNode;\r\n}()); // end LLRBNode\r\n// Represents an empty node (a leaf node in the Red-Black Tree).\r\nvar LLRBEmptyNode = /** @class */ (function () {\r\n function LLRBEmptyNode() {\r\n this.size = 0;\r\n }\r\n // Returns a copy of the current node.\r\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\r\n return this;\r\n };\r\n // Returns a copy of the tree, with the specified key/value added.\r\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\r\n return new LLRBNode(key, value);\r\n };\r\n // Returns a copy of the tree, with the specified key removed.\r\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\r\n return this;\r\n };\r\n LLRBEmptyNode.prototype.isEmpty = function () {\r\n return true;\r\n };\r\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\r\n return false;\r\n };\r\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\r\n return false;\r\n };\r\n LLRBEmptyNode.prototype.minKey = function () {\r\n return null;\r\n };\r\n LLRBEmptyNode.prototype.maxKey = function () {\r\n return null;\r\n };\r\n LLRBEmptyNode.prototype.isRed = function () {\r\n return false;\r\n };\r\n // For testing.\r\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\r\n return true;\r\n };\r\n LLRBEmptyNode.prototype.check = function () {\r\n return 0;\r\n };\r\n return LLRBEmptyNode;\r\n}()); // end LLRBEmptyNode\r\nLLRBNode.EMPTY = new LLRBEmptyNode();\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar TypeOrder;\r\n(function (TypeOrder) {\r\n // This order is defined by the backend.\r\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\r\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\r\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\r\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\r\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\r\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\r\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\r\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\r\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\r\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\r\n})(TypeOrder || (TypeOrder = {}));\r\n/** Defines the return value for pending server timestamps. */\r\nvar ServerTimestampBehavior;\r\n(function (ServerTimestampBehavior) {\r\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\r\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\r\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\r\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\r\n/** Holds properties that define field value deserialization options. */\r\nvar FieldValueOptions = /** @class */ (function () {\r\n function FieldValueOptions(serverTimestampBehavior, timestampsInSnapshots) {\r\n this.serverTimestampBehavior = serverTimestampBehavior;\r\n this.timestampsInSnapshots = timestampsInSnapshots;\r\n }\r\n FieldValueOptions.fromSnapshotOptions = function (options, timestampsInSnapshots) {\r\n switch (options.serverTimestamps) {\r\n case 'estimate':\r\n return new FieldValueOptions(ServerTimestampBehavior.Estimate, timestampsInSnapshots);\r\n case 'previous':\r\n return new FieldValueOptions(ServerTimestampBehavior.Previous, timestampsInSnapshots);\r\n case 'none': // Fall-through intended.\r\n case undefined:\r\n return new FieldValueOptions(ServerTimestampBehavior.Default, timestampsInSnapshots);\r\n default:\r\n return fail('fromSnapshotOptions() called with invalid options.');\r\n }\r\n };\r\n return FieldValueOptions;\r\n}());\r\n/**\r\n * A field value represents a datatype as stored by Firestore.\r\n */\r\nvar FieldValue = /** @class */ (function () {\r\n function FieldValue() {\r\n }\r\n FieldValue.prototype.toString = function () {\r\n var val = this.value();\r\n return val === null ? 'null' : val.toString();\r\n };\r\n FieldValue.prototype.defaultCompareTo = function (other) {\r\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\r\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\r\n return cmp;\r\n };\r\n return FieldValue;\r\n}());\r\nvar NullValue = /** @class */ (function (_super) {\r\n __extends(NullValue, _super);\r\n function NullValue() {\r\n var _this = _super.call(this) || this;\r\n _this.typeOrder = TypeOrder.NullValue;\r\n // internalValue is unused but we add it to work around\r\n // https://github.com/Microsoft/TypeScript/issues/15585\r\n _this.internalValue = null;\r\n return _this;\r\n }\r\n NullValue.prototype.value = function (options) {\r\n return null;\r\n };\r\n NullValue.prototype.isEqual = function (other) {\r\n return other instanceof NullValue;\r\n };\r\n NullValue.prototype.compareTo = function (other) {\r\n if (other instanceof NullValue) {\r\n return 0;\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n NullValue.INSTANCE = new NullValue();\r\n return NullValue;\r\n}(FieldValue));\r\nvar BooleanValue = /** @class */ (function (_super) {\r\n __extends(BooleanValue, _super);\r\n function BooleanValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.BooleanValue;\r\n return _this;\r\n }\r\n BooleanValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n BooleanValue.prototype.isEqual = function (other) {\r\n return (other instanceof BooleanValue &&\r\n this.internalValue === other.internalValue);\r\n };\r\n BooleanValue.prototype.compareTo = function (other) {\r\n if (other instanceof BooleanValue) {\r\n return primitiveComparator(this, other);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n BooleanValue.of = function (value) {\r\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\r\n };\r\n BooleanValue.TRUE = new BooleanValue(true);\r\n BooleanValue.FALSE = new BooleanValue(false);\r\n return BooleanValue;\r\n}(FieldValue));\r\n/** Base class for IntegerValue and DoubleValue. */\r\nvar NumberValue = /** @class */ (function (_super) {\r\n __extends(NumberValue, _super);\r\n function NumberValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.NumberValue;\r\n return _this;\r\n }\r\n NumberValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n NumberValue.prototype.compareTo = function (other) {\r\n if (other instanceof NumberValue) {\r\n return numericComparator(this.internalValue, other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return NumberValue;\r\n}(FieldValue));\r\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\r\nfunction numericComparator(left, right) {\r\n if (left < right) {\r\n return -1;\r\n }\r\n else if (left > right) {\r\n return 1;\r\n }\r\n else if (left === right) {\r\n return 0;\r\n }\r\n else {\r\n // one or both are NaN.\r\n if (isNaN(left)) {\r\n return isNaN(right) ? 0 : -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n}\r\n/**\r\n * Utility function to check numbers for equality using Firestore semantics\r\n * (NaN === NaN, -0.0 !== 0.0).\r\n */\r\nfunction numericEquals(left, right) {\r\n // Implemented based on Object.is() polyfill from\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\r\n if (left === right) {\r\n // +0 != -0\r\n return left !== 0 || 1 / left === 1 / right;\r\n }\r\n else {\r\n // NaN == NaN\r\n return left !== left && right !== right;\r\n }\r\n}\r\nvar IntegerValue = /** @class */ (function (_super) {\r\n __extends(IntegerValue, _super);\r\n function IntegerValue(internalValue) {\r\n return _super.call(this, internalValue) || this;\r\n }\r\n IntegerValue.prototype.isEqual = function (other) {\r\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\r\n // but that doesn't make them equal via isEqual().\r\n if (other instanceof IntegerValue) {\r\n return numericEquals(this.internalValue, other.internalValue);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n return IntegerValue;\r\n}(NumberValue));\r\nvar DoubleValue = /** @class */ (function (_super) {\r\n __extends(DoubleValue, _super);\r\n function DoubleValue(internalValue) {\r\n var _this = _super.call(this, internalValue) || this;\r\n _this.internalValue = internalValue;\r\n return _this;\r\n }\r\n DoubleValue.prototype.isEqual = function (other) {\r\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\r\n // but that doesn't make them equal via isEqual().\r\n if (other instanceof DoubleValue) {\r\n return numericEquals(this.internalValue, other.internalValue);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n DoubleValue.NAN = new DoubleValue(NaN);\r\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\r\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\r\n return DoubleValue;\r\n}(NumberValue));\r\n// TODO(b/37267885): Add truncation support\r\nvar StringValue = /** @class */ (function (_super) {\r\n __extends(StringValue, _super);\r\n function StringValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.StringValue;\r\n return _this;\r\n }\r\n StringValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n StringValue.prototype.isEqual = function (other) {\r\n return (other instanceof StringValue && this.internalValue === other.internalValue);\r\n };\r\n StringValue.prototype.compareTo = function (other) {\r\n if (other instanceof StringValue) {\r\n return primitiveComparator(this.internalValue, other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return StringValue;\r\n}(FieldValue));\r\nvar TimestampValue = /** @class */ (function (_super) {\r\n __extends(TimestampValue, _super);\r\n function TimestampValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.TimestampValue;\r\n return _this;\r\n }\r\n TimestampValue.prototype.value = function (options) {\r\n if (options && options.timestampsInSnapshots) {\r\n return this.internalValue;\r\n }\r\n else {\r\n return this.internalValue.toDate();\r\n }\r\n };\r\n TimestampValue.prototype.isEqual = function (other) {\r\n return (other instanceof TimestampValue &&\r\n this.internalValue.isEqual(other.internalValue));\r\n };\r\n TimestampValue.prototype.compareTo = function (other) {\r\n if (other instanceof TimestampValue) {\r\n return this.internalValue._compareTo(other.internalValue);\r\n }\r\n else if (other instanceof ServerTimestampValue) {\r\n // Concrete timestamps come before server timestamps.\r\n return -1;\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n return TimestampValue;\r\n}(FieldValue));\r\n/**\r\n * Represents a locally-applied ServerTimestamp.\r\n *\r\n * Notes:\r\n * - ServerTimestampValue instances are created as the result of applying a\r\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\r\n * the local view of a document. Therefore they do not need to be parsed or\r\n * serialized.\r\n * - When evaluated locally (e.g. for snapshot.data()), they by default\r\n * evaluate to `null`. This behavior can be configured by passing custom\r\n * FieldValueOptions to value().\r\n * - With respect to other ServerTimestampValues, they sort by their\r\n * localWriteTime.\r\n */\r\nvar ServerTimestampValue = /** @class */ (function (_super) {\r\n __extends(ServerTimestampValue, _super);\r\n function ServerTimestampValue(localWriteTime, previousValue) {\r\n var _this = _super.call(this) || this;\r\n _this.localWriteTime = localWriteTime;\r\n _this.previousValue = previousValue;\r\n _this.typeOrder = TypeOrder.TimestampValue;\r\n return _this;\r\n }\r\n ServerTimestampValue.prototype.value = function (options) {\r\n if (options &&\r\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\r\n return new TimestampValue(this.localWriteTime).value(options);\r\n }\r\n else if (options &&\r\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\r\n return this.previousValue ? this.previousValue.value(options) : null;\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n ServerTimestampValue.prototype.isEqual = function (other) {\r\n return (other instanceof ServerTimestampValue &&\r\n this.localWriteTime.isEqual(other.localWriteTime));\r\n };\r\n ServerTimestampValue.prototype.compareTo = function (other) {\r\n if (other instanceof ServerTimestampValue) {\r\n return this.localWriteTime._compareTo(other.localWriteTime);\r\n }\r\n else if (other instanceof TimestampValue) {\r\n // Server timestamps come after all concrete timestamps.\r\n return 1;\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n ServerTimestampValue.prototype.toString = function () {\r\n return '';\r\n };\r\n return ServerTimestampValue;\r\n}(FieldValue));\r\nvar BlobValue = /** @class */ (function (_super) {\r\n __extends(BlobValue, _super);\r\n function BlobValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.BlobValue;\r\n return _this;\r\n }\r\n BlobValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n BlobValue.prototype.isEqual = function (other) {\r\n return (other instanceof BlobValue &&\r\n this.internalValue.isEqual(other.internalValue));\r\n };\r\n BlobValue.prototype.compareTo = function (other) {\r\n if (other instanceof BlobValue) {\r\n return this.internalValue._compareTo(other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return BlobValue;\r\n}(FieldValue));\r\nvar RefValue = /** @class */ (function (_super) {\r\n __extends(RefValue, _super);\r\n function RefValue(databaseId, key) {\r\n var _this = _super.call(this) || this;\r\n _this.databaseId = databaseId;\r\n _this.key = key;\r\n _this.typeOrder = TypeOrder.RefValue;\r\n return _this;\r\n }\r\n RefValue.prototype.value = function (options) {\r\n return this.key;\r\n };\r\n RefValue.prototype.isEqual = function (other) {\r\n if (other instanceof RefValue) {\r\n return (this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId));\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n RefValue.prototype.compareTo = function (other) {\r\n if (other instanceof RefValue) {\r\n var cmp = this.databaseId.compareTo(other.databaseId);\r\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return RefValue;\r\n}(FieldValue));\r\nvar GeoPointValue = /** @class */ (function (_super) {\r\n __extends(GeoPointValue, _super);\r\n function GeoPointValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.GeoPointValue;\r\n return _this;\r\n }\r\n GeoPointValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n GeoPointValue.prototype.isEqual = function (other) {\r\n return (other instanceof GeoPointValue &&\r\n this.internalValue.isEqual(other.internalValue));\r\n };\r\n GeoPointValue.prototype.compareTo = function (other) {\r\n if (other instanceof GeoPointValue) {\r\n return this.internalValue._compareTo(other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return GeoPointValue;\r\n}(FieldValue));\r\nvar ObjectValue = /** @class */ (function (_super) {\r\n __extends(ObjectValue, _super);\r\n function ObjectValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.ObjectValue;\r\n return _this;\r\n }\r\n ObjectValue.prototype.value = function (options) {\r\n var result = {};\r\n this.internalValue.inorderTraversal(function (key, val) {\r\n result[key] = val.value(options);\r\n });\r\n return result;\r\n };\r\n ObjectValue.prototype.forEach = function (action) {\r\n this.internalValue.inorderTraversal(action);\r\n };\r\n ObjectValue.prototype.isEqual = function (other) {\r\n if (other instanceof ObjectValue) {\r\n var it1 = this.internalValue.getIterator();\r\n var it2 = other.internalValue.getIterator();\r\n while (it1.hasNext() && it2.hasNext()) {\r\n var next1 = it1.getNext();\r\n var next2 = it2.getNext();\r\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\r\n return false;\r\n }\r\n }\r\n return !it1.hasNext() && !it2.hasNext();\r\n }\r\n return false;\r\n };\r\n ObjectValue.prototype.compareTo = function (other) {\r\n if (other instanceof ObjectValue) {\r\n var it1 = this.internalValue.getIterator();\r\n var it2 = other.internalValue.getIterator();\r\n while (it1.hasNext() && it2.hasNext()) {\r\n var next1 = it1.getNext();\r\n var next2 = it2.getNext();\r\n var cmp = primitiveComparator(next1.key, next2.key) ||\r\n next1.value.compareTo(next2.value);\r\n if (cmp) {\r\n return cmp;\r\n }\r\n }\r\n // Only equal if both iterators are exhausted\r\n return primitiveComparator(it1.hasNext(), it2.hasNext());\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n ObjectValue.prototype.set = function (path, to) {\r\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\r\n if (path.length === 1) {\r\n return this.setChild(path.firstSegment(), to);\r\n }\r\n else {\r\n var child = this.child(path.firstSegment());\r\n if (!(child instanceof ObjectValue)) {\r\n child = ObjectValue.EMPTY;\r\n }\r\n var newChild = child.set(path.popFirst(), to);\r\n return this.setChild(path.firstSegment(), newChild);\r\n }\r\n };\r\n ObjectValue.prototype.delete = function (path) {\r\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\r\n if (path.length === 1) {\r\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\r\n }\r\n else {\r\n // nested field\r\n var child = this.child(path.firstSegment());\r\n if (child instanceof ObjectValue) {\r\n var newChild = child.delete(path.popFirst());\r\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\r\n }\r\n else {\r\n // Don't actually change a primitive value to an object for a delete\r\n return this;\r\n }\r\n }\r\n };\r\n ObjectValue.prototype.contains = function (path) {\r\n return this.field(path) !== undefined;\r\n };\r\n ObjectValue.prototype.field = function (path) {\r\n assert(!path.isEmpty(), \"Can't get field of empty path\");\r\n var field = this;\r\n path.forEach(function (pathSegment) {\r\n if (field instanceof ObjectValue) {\r\n field = field.internalValue.get(pathSegment) || undefined;\r\n }\r\n else {\r\n field = undefined;\r\n }\r\n });\r\n return field;\r\n };\r\n ObjectValue.prototype.toString = function () {\r\n return JSON.stringify(this.value());\r\n };\r\n ObjectValue.prototype.child = function (childName) {\r\n return this.internalValue.get(childName) || undefined;\r\n };\r\n ObjectValue.prototype.setChild = function (childName, value) {\r\n return new ObjectValue(this.internalValue.insert(childName, value));\r\n };\r\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\r\n return ObjectValue;\r\n}(FieldValue));\r\nvar ArrayValue = /** @class */ (function (_super) {\r\n __extends(ArrayValue, _super);\r\n function ArrayValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.ArrayValue;\r\n return _this;\r\n }\r\n ArrayValue.prototype.value = function (options) {\r\n return this.internalValue.map(function (v) { return v.value(options); });\r\n };\r\n ArrayValue.prototype.forEach = function (action) {\r\n this.internalValue.forEach(action);\r\n };\r\n ArrayValue.prototype.isEqual = function (other) {\r\n if (other instanceof ArrayValue) {\r\n if (this.internalValue.length !== other.internalValue.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.internalValue.length; i++) {\r\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n ArrayValue.prototype.compareTo = function (other) {\r\n if (other instanceof ArrayValue) {\r\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\r\n for (var i = 0; i < minLength; i++) {\r\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\r\n if (cmp) {\r\n return cmp;\r\n }\r\n }\r\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n ArrayValue.prototype.toString = function () {\r\n return JSON.stringify(this.value());\r\n };\r\n return ArrayValue;\r\n}(FieldValue));\n\n/**\r\n * Copyright 2017 Google Inc.\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// Untyped Number alias we can use to check for ES6 methods / properties.\r\n// tslint:disable-next-line:no-any variable-name\r\nvar NumberAsAny = Number;\r\n/**\r\n * Minimum safe integer in Javascript because of floating point precision.\r\n * Added to not rely on ES6 features.\r\n */\r\nvar MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\r\n/**\r\n * Maximum safe integer in Javascript because of floating point precision.\r\n * Added to not rely on ES6 features.\r\n */\r\nvar MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\r\n/**\r\n * Returns whether an number is an integer, uses native implementation if\r\n * available.\r\n * Added to not rely on ES6 features.\r\n * @param value The value to test for being an integer\r\n */\r\nvar isInteger = NumberAsAny.isInteger ||\r\n (function (value) {\r\n return typeof value === 'number' &&\r\n isFinite(value) &&\r\n Math.floor(value) === value;\r\n });\r\n/**\r\n * Returns whether a variable is either undefined or null.\r\n */\r\nfunction isNullOrUndefined(value) {\r\n return value === null || value === undefined;\r\n}\r\n/**\r\n * Returns whether a value is an integer and in the safe integer range\r\n * @param value The value to test for being an integer and in the safe range\r\n */\r\nfunction isSafeInteger(value) {\r\n return (isInteger(value) &&\r\n value <= MAX_SAFE_INTEGER &&\r\n value >= MIN_SAFE_INTEGER);\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar Query = /** @class */ (function () {\r\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\r\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\r\n if (filters === void 0) { filters = []; }\r\n if (limit === void 0) { limit = null; }\r\n if (startAt === void 0) { startAt = null; }\r\n if (endAt === void 0) { endAt = null; }\r\n this.path = path;\r\n this.explicitOrderBy = explicitOrderBy;\r\n this.filters = filters;\r\n this.limit = limit;\r\n this.startAt = startAt;\r\n this.endAt = endAt;\r\n this.memoizedCanonicalId = null;\r\n this.memoizedOrderBy = null;\r\n if (this.startAt) {\r\n this.assertValidBound(this.startAt);\r\n }\r\n if (this.endAt) {\r\n this.assertValidBound(this.endAt);\r\n }\r\n }\r\n Query.atPath = function (path) {\r\n return new Query(path);\r\n };\r\n Object.defineProperty(Query.prototype, \"orderBy\", {\r\n get: function () {\r\n if (this.memoizedOrderBy === null) {\r\n var inequalityField = this.getInequalityFilterField();\r\n var firstOrderByField = this.getFirstOrderByField();\r\n if (inequalityField !== null && firstOrderByField === null) {\r\n // In order to implicitly add key ordering, we must also add the\r\n // inequality filter field for it to be a valid query.\r\n // Note that the default inequality field and key ordering is ascending.\r\n if (inequalityField.isKeyField()) {\r\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\r\n }\r\n else {\r\n this.memoizedOrderBy = [\r\n new OrderBy(inequalityField),\r\n KEY_ORDERING_ASC\r\n ];\r\n }\r\n }\r\n else {\r\n assert(inequalityField === null ||\r\n (firstOrderByField !== null &&\r\n inequalityField.isEqual(firstOrderByField)), 'First orderBy should match inequality field.');\r\n this.memoizedOrderBy = [];\r\n var foundKeyOrdering = false;\r\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n this.memoizedOrderBy.push(orderBy);\r\n if (orderBy.field.isKeyField()) {\r\n foundKeyOrdering = true;\r\n }\r\n }\r\n if (!foundKeyOrdering) {\r\n // The order of the implicit key ordering always matches the last\r\n // explicit order by\r\n var lastDirection = this.explicitOrderBy.length > 0\r\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\r\n : Direction.ASCENDING;\r\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\r\n ? KEY_ORDERING_ASC\r\n : KEY_ORDERING_DESC);\r\n }\r\n }\r\n }\r\n return this.memoizedOrderBy;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Query.prototype.addFilter = function (filter) {\r\n assert(this.getInequalityFilterField() == null ||\r\n !(filter instanceof RelationFilter) ||\r\n !filter.isInequality() ||\r\n filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\r\n assert(!DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\r\n var newFilters = this.filters.concat([filter]);\r\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\r\n };\r\n Query.prototype.addOrderBy = function (orderBy) {\r\n assert(!DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\r\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\r\n // TODO(dimond): validate that orderBy does not list the same key twice.\r\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\r\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\r\n };\r\n Query.prototype.withLimit = function (limit) {\r\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\r\n };\r\n Query.prototype.withStartAt = function (bound) {\r\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\r\n };\r\n Query.prototype.withEndAt = function (bound) {\r\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\r\n };\r\n // TODO(b/29183165): This is used to get a unique string from a query to, for\r\n // example, use as a dictionary key, but the implementation is subject to\r\n // collisions. Make it collision-free.\r\n Query.prototype.canonicalId = function () {\r\n if (this.memoizedCanonicalId === null) {\r\n var canonicalId = this.path.canonicalString();\r\n canonicalId += '|f:';\r\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\r\n var filter = _a[_i];\r\n canonicalId += filter.canonicalId();\r\n canonicalId += ',';\r\n }\r\n canonicalId += '|ob:';\r\n // TODO(dimond): make this collision resistant\r\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\r\n var orderBy = _c[_b];\r\n canonicalId += orderBy.canonicalId();\r\n canonicalId += ',';\r\n }\r\n if (!isNullOrUndefined(this.limit)) {\r\n canonicalId += '|l:';\r\n canonicalId += this.limit;\r\n }\r\n if (this.startAt) {\r\n canonicalId += '|lb:';\r\n canonicalId += this.startAt.canonicalId();\r\n }\r\n if (this.endAt) {\r\n canonicalId += '|ub:';\r\n canonicalId += this.endAt.canonicalId();\r\n }\r\n this.memoizedCanonicalId = canonicalId;\r\n }\r\n return this.memoizedCanonicalId;\r\n };\r\n Query.prototype.toString = function () {\r\n var str = 'Query(' + this.path.canonicalString();\r\n if (this.filters.length > 0) {\r\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\r\n }\r\n if (!isNullOrUndefined(this.limit)) {\r\n str += ', limit: ' + this.limit;\r\n }\r\n if (this.explicitOrderBy.length > 0) {\r\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\r\n }\r\n if (this.startAt) {\r\n str += ', startAt: ' + this.startAt.canonicalId();\r\n }\r\n if (this.endAt) {\r\n str += ', endAt: ' + this.endAt.canonicalId();\r\n }\r\n return str + ')';\r\n };\r\n Query.prototype.isEqual = function (other) {\r\n if (this.limit !== other.limit) {\r\n return false;\r\n }\r\n if (this.orderBy.length !== other.orderBy.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.orderBy.length; i++) {\r\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\r\n return false;\r\n }\r\n }\r\n if (this.filters.length !== other.filters.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.filters.length; i++) {\r\n if (!this.filters[i].isEqual(other.filters[i])) {\r\n return false;\r\n }\r\n }\r\n if (!this.path.isEqual(other.path)) {\r\n return false;\r\n }\r\n if (this.startAt !== null\r\n ? !this.startAt.isEqual(other.startAt)\r\n : other.startAt !== null) {\r\n return false;\r\n }\r\n return this.endAt !== null\r\n ? this.endAt.isEqual(other.endAt)\r\n : other.endAt === null;\r\n };\r\n Query.prototype.docComparator = function (d1, d2) {\r\n var comparedOnKeyField = false;\r\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n var comp = orderBy.compare(d1, d2);\r\n if (comp !== 0)\r\n return comp;\r\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\r\n }\r\n // Assert that we actually compared by key\r\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\r\n return 0;\r\n };\r\n Query.prototype.matches = function (doc) {\r\n return (this.matchesAncestor(doc) &&\r\n this.matchesOrderBy(doc) &&\r\n this.matchesFilters(doc) &&\r\n this.matchesBounds(doc));\r\n };\r\n Query.prototype.hasLimit = function () {\r\n return !isNullOrUndefined(this.limit);\r\n };\r\n Query.prototype.getFirstOrderByField = function () {\r\n return this.explicitOrderBy.length > 0\r\n ? this.explicitOrderBy[0].field\r\n : null;\r\n };\r\n Query.prototype.getInequalityFilterField = function () {\r\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\r\n var filter = _a[_i];\r\n if (filter instanceof RelationFilter && filter.isInequality()) {\r\n return filter.field;\r\n }\r\n }\r\n return null;\r\n };\r\n Query.prototype.isDocumentQuery = function () {\r\n return DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\r\n };\r\n Query.prototype.matchesAncestor = function (doc) {\r\n var docPath = doc.key.path;\r\n if (DocumentKey.isDocumentKey(this.path)) {\r\n // exact match for document queries\r\n return this.path.isEqual(docPath);\r\n }\r\n else {\r\n // shallow ancestor queries by default\r\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\r\n }\r\n };\r\n /**\r\n * A document must have a value for every ordering clause in order to show up\r\n * in the results.\r\n */\r\n Query.prototype.matchesOrderBy = function (doc) {\r\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n // order by key always matches\r\n if (!orderBy.field.isKeyField() &&\r\n doc.field(orderBy.field) === undefined) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n Query.prototype.matchesFilters = function (doc) {\r\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\r\n var filter = _a[_i];\r\n if (!filter.matches(doc)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n /**\r\n * Makes sure a document is within the bounds, if provided.\r\n */\r\n Query.prototype.matchesBounds = function (doc) {\r\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\r\n return false;\r\n }\r\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\r\n return false;\r\n }\r\n return true;\r\n };\r\n Query.prototype.assertValidBound = function (bound) {\r\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\r\n };\r\n return Query;\r\n}());\r\nvar RelationOp = /** @class */ (function () {\r\n function RelationOp(name) {\r\n this.name = name;\r\n }\r\n RelationOp.fromString = function (op) {\r\n switch (op) {\r\n case '<':\r\n return RelationOp.LESS_THAN;\r\n case '<=':\r\n return RelationOp.LESS_THAN_OR_EQUAL;\r\n case '==':\r\n return RelationOp.EQUAL;\r\n case '>=':\r\n return RelationOp.GREATER_THAN_OR_EQUAL;\r\n case '>':\r\n return RelationOp.GREATER_THAN;\r\n default:\r\n return fail('Unknown relation: ' + op);\r\n }\r\n };\r\n RelationOp.prototype.toString = function () {\r\n return this.name;\r\n };\r\n RelationOp.prototype.isEqual = function (other) {\r\n return this.name === other.name;\r\n };\r\n RelationOp.LESS_THAN = new RelationOp('<');\r\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\r\n RelationOp.EQUAL = new RelationOp('==');\r\n RelationOp.GREATER_THAN = new RelationOp('>');\r\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\r\n return RelationOp;\r\n}());\r\nvar RelationFilter = /** @class */ (function () {\r\n function RelationFilter(field, op, value) {\r\n this.field = field;\r\n this.op = op;\r\n this.value = value;\r\n }\r\n RelationFilter.prototype.matches = function (doc) {\r\n if (this.field.isKeyField()) {\r\n assert(this.value instanceof RefValue, 'Comparing on key, but filter value not a RefValue');\r\n var refValue = this.value;\r\n var comparison = DocumentKey.comparator(doc.key, refValue.key);\r\n return this.matchesComparison(comparison);\r\n }\r\n else {\r\n var val = doc.field(this.field);\r\n return val !== undefined && this.matchesValue(val);\r\n }\r\n };\r\n RelationFilter.prototype.matchesValue = function (value) {\r\n // Only compare types with matching backend order (such as double and int).\r\n if (this.value.typeOrder !== value.typeOrder) {\r\n return false;\r\n }\r\n return this.matchesComparison(value.compareTo(this.value));\r\n };\r\n RelationFilter.prototype.matchesComparison = function (comparison) {\r\n switch (this.op) {\r\n case RelationOp.LESS_THAN:\r\n return comparison < 0;\r\n case RelationOp.LESS_THAN_OR_EQUAL:\r\n return comparison <= 0;\r\n case RelationOp.EQUAL:\r\n return comparison === 0;\r\n case RelationOp.GREATER_THAN:\r\n return comparison > 0;\r\n case RelationOp.GREATER_THAN_OR_EQUAL:\r\n return comparison >= 0;\r\n default:\r\n return fail('Unknown relation op' + this.op);\r\n }\r\n };\r\n RelationFilter.prototype.isInequality = function () {\r\n return this.op !== RelationOp.EQUAL;\r\n };\r\n RelationFilter.prototype.canonicalId = function () {\r\n // TODO(b/29183165): Technically, this won't be unique if two values have\r\n // the same description, such as the int 3 and the string \"3\". So we should\r\n // add the types in here somehow, too.\r\n return (this.field.canonicalString() + this.op.toString() + this.value.toString());\r\n };\r\n RelationFilter.prototype.isEqual = function (other) {\r\n if (other instanceof RelationFilter) {\r\n return (this.op.isEqual(other.op) &&\r\n this.field.isEqual(other.field) &&\r\n this.value.isEqual(other.value));\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n RelationFilter.prototype.toString = function () {\r\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\r\n };\r\n return RelationFilter;\r\n}());\r\n/**\r\n * Filter that matches 'null' values.\r\n */\r\nvar NullFilter = /** @class */ (function () {\r\n function NullFilter(field) {\r\n this.field = field;\r\n }\r\n NullFilter.prototype.matches = function (doc) {\r\n var val = doc.field(this.field);\r\n return val !== undefined && val.value() === null;\r\n };\r\n NullFilter.prototype.canonicalId = function () {\r\n return this.field.canonicalString() + ' IS null';\r\n };\r\n NullFilter.prototype.toString = function () {\r\n return this.field.canonicalString() + \" IS null\";\r\n };\r\n NullFilter.prototype.isEqual = function (other) {\r\n if (other instanceof NullFilter) {\r\n return this.field.isEqual(other.field);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n return NullFilter;\r\n}());\r\n/**\r\n * Filter that matches 'NaN' values.\r\n */\r\nvar NanFilter = /** @class */ (function () {\r\n function NanFilter(field) {\r\n this.field = field;\r\n }\r\n NanFilter.prototype.matches = function (doc) {\r\n var val = doc.field(this.field).value();\r\n return typeof val === 'number' && isNaN(val);\r\n };\r\n NanFilter.prototype.canonicalId = function () {\r\n return this.field.canonicalString() + ' IS NaN';\r\n };\r\n NanFilter.prototype.toString = function () {\r\n return this.field.canonicalString() + \" IS NaN\";\r\n };\r\n NanFilter.prototype.isEqual = function (other) {\r\n if (other instanceof NanFilter) {\r\n return this.field.isEqual(other.field);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n return NanFilter;\r\n}());\r\n/**\r\n * Creates a filter based on the provided arguments.\r\n */\r\nfunction fieldFilter(field, op, value) {\r\n if (value.isEqual(NullValue.INSTANCE)) {\r\n if (op !== RelationOp.EQUAL) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\r\n }\r\n return new NullFilter(field);\r\n }\r\n else if (value.isEqual(DoubleValue.NAN)) {\r\n if (op !== RelationOp.EQUAL) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\r\n }\r\n return new NanFilter(field);\r\n }\r\n else {\r\n return new RelationFilter(field, op, value);\r\n }\r\n}\r\n/**\r\n * The direction of sorting in an order by.\r\n */\r\nvar Direction = /** @class */ (function () {\r\n function Direction(name) {\r\n this.name = name;\r\n }\r\n Direction.prototype.toString = function () {\r\n return this.name;\r\n };\r\n Direction.ASCENDING = new Direction('asc');\r\n Direction.DESCENDING = new Direction('desc');\r\n return Direction;\r\n}());\r\n/**\r\n * Represents a bound of a query.\r\n *\r\n * The bound is specified with the given components representing a position and\r\n * whether it's just before or just after the position (relative to whatever the\r\n * query order is).\r\n *\r\n * The position represents a logical index position for a query. It's a prefix\r\n * of values for the (potentially implicit) order by clauses of a query.\r\n *\r\n * Bound provides a function to determine whether a document comes before or\r\n * after a bound. This is influenced by whether the position is just before or\r\n * just after the provided values.\r\n */\r\nvar Bound = /** @class */ (function () {\r\n function Bound(position, before) {\r\n this.position = position;\r\n this.before = before;\r\n }\r\n Bound.prototype.canonicalId = function () {\r\n // TODO(b/29183165): Make this collision robust.\r\n var canonicalId = this.before ? 'b:' : 'a:';\r\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\r\n var component = _a[_i];\r\n canonicalId += component.toString();\r\n }\r\n return canonicalId;\r\n };\r\n /**\r\n * Returns true if a document sorts before a bound using the provided sort\r\n * order.\r\n */\r\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\r\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\r\n var comparison = 0;\r\n for (var i = 0; i < this.position.length; i++) {\r\n var orderByComponent = orderBy[i];\r\n var component = this.position[i];\r\n if (orderByComponent.field.isKeyField()) {\r\n assert(component instanceof RefValue, 'Bound has a non-key value where the key path is being used.');\r\n comparison = DocumentKey.comparator(component.key, doc.key);\r\n }\r\n else {\r\n var docValue = doc.field(orderByComponent.field);\r\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\r\n comparison = component.compareTo(docValue);\r\n }\r\n if (orderByComponent.dir === Direction.DESCENDING) {\r\n comparison = comparison * -1;\r\n }\r\n if (comparison !== 0) {\r\n break;\r\n }\r\n }\r\n return this.before ? comparison <= 0 : comparison < 0;\r\n };\r\n Bound.prototype.isEqual = function (other) {\r\n if (other === null) {\r\n return false;\r\n }\r\n if (this.before !== other.before ||\r\n this.position.length !== other.position.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.position.length; i++) {\r\n var thisPosition = this.position[i];\r\n var otherPosition = other.position[i];\r\n return thisPosition.isEqual(otherPosition);\r\n }\r\n return true;\r\n };\r\n return Bound;\r\n}());\r\n/**\r\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\r\n */\r\nvar OrderBy = /** @class */ (function () {\r\n function OrderBy(field, dir) {\r\n this.field = field;\r\n if (dir === undefined) {\r\n dir = Direction.ASCENDING;\r\n }\r\n this.dir = dir;\r\n this.isKeyOrderBy = field.isKeyField();\r\n }\r\n OrderBy.prototype.compare = function (d1, d2) {\r\n var comparison = this.isKeyOrderBy\r\n ? Document.compareByKey(d1, d2)\r\n : Document.compareByField(this.field, d1, d2);\r\n switch (this.dir) {\r\n case Direction.ASCENDING:\r\n return comparison;\r\n case Direction.DESCENDING:\r\n return -1 * comparison;\r\n default:\r\n return fail('Unknown direction: ' + this.dir);\r\n }\r\n };\r\n OrderBy.prototype.canonicalId = function () {\r\n // TODO(b/29183165): Make this collision robust.\r\n return this.field.canonicalString() + this.dir.toString();\r\n };\r\n OrderBy.prototype.toString = function () {\r\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\r\n };\r\n OrderBy.prototype.isEqual = function (other) {\r\n return this.dir === other.dir && this.field.isEqual(other.field);\r\n };\r\n return OrderBy;\r\n}());\r\nvar KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\r\nvar KEY_ORDERING_DESC = new OrderBy(FieldPath.keyField(), Direction.DESCENDING);\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A version of a document in Firestore. This corresponds to the version\r\n * timestamp, such as update_time or read_time.\r\n */\r\nvar SnapshotVersion = /** @class */ (function () {\r\n function SnapshotVersion(timestamp) {\r\n this.timestamp = timestamp;\r\n }\r\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\r\n // delete this constructor and use a timestamp-backed version everywhere.\r\n SnapshotVersion.fromMicroseconds = function (value) {\r\n var seconds = Math.floor(value / 1e6);\r\n var nanos = (value % 1e6) * 1e3;\r\n return new SnapshotVersion(new Timestamp(seconds, nanos));\r\n };\r\n SnapshotVersion.fromTimestamp = function (value) {\r\n return new SnapshotVersion(value);\r\n };\r\n SnapshotVersion.forDeletedDoc = function () {\r\n return SnapshotVersion.MIN;\r\n };\r\n SnapshotVersion.prototype.compareTo = function (other) {\r\n return this.timestamp._compareTo(other.timestamp);\r\n };\r\n SnapshotVersion.prototype.isEqual = function (other) {\r\n return this.timestamp.isEqual(other.timestamp);\r\n };\r\n /** Returns a number representation of the version for use in spec tests. */\r\n SnapshotVersion.prototype.toMicroseconds = function () {\r\n // Convert to microseconds.\r\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\r\n };\r\n SnapshotVersion.prototype.toString = function () {\r\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\r\n };\r\n SnapshotVersion.prototype.toTimestamp = function () {\r\n return this.timestamp;\r\n };\r\n SnapshotVersion.MIN = new SnapshotVersion(new Timestamp(0, 0));\r\n return SnapshotVersion;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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/** An enumeration of the different purposes we have for queries. */\r\nvar QueryPurpose;\r\n(function (QueryPurpose) {\r\n /** A regular, normal query. */\r\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\r\n /**\r\n * The query was used to refill a query after an existence filter mismatch.\r\n */\r\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\r\n /** The query was used to resolve a limbo document. */\r\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\r\n})(QueryPurpose || (QueryPurpose = {}));\r\n/**\r\n * An immutable set of metadata that the local store tracks for each query.\r\n */\r\nvar QueryData = /** @class */ (function () {\r\n function QueryData(\r\n /** The query being listened to. */\r\n query, \r\n /**\r\n * The target ID to which the query corresponds; Assigned by the\r\n * LocalStore for user listens and by the SyncEngine for limbo watches.\r\n */\r\n targetId, \r\n /** The purpose of the query. */\r\n purpose, \r\n /** The latest snapshot version seen for this target. */\r\n snapshotVersion, \r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data that\r\n * matches the query. The resume token essentially identifies a point in\r\n * time from which the server should resume sending results.\r\n */\r\n resumeToken) {\r\n if (snapshotVersion === void 0) { snapshotVersion = SnapshotVersion.MIN; }\r\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\r\n this.query = query;\r\n this.targetId = targetId;\r\n this.purpose = purpose;\r\n this.snapshotVersion = snapshotVersion;\r\n this.resumeToken = resumeToken;\r\n }\r\n /**\r\n * Creates a new query data instance with an updated snapshot version and\r\n * resume token.\r\n */\r\n QueryData.prototype.update = function (updated) {\r\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\r\n };\r\n QueryData.prototype.isEqual = function (other) {\r\n return (this.targetId === other.targetId &&\r\n this.purpose === other.purpose &&\r\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\r\n this.resumeToken === other.resumeToken &&\r\n this.query.isEqual(other.query));\r\n };\r\n return QueryData;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Provides a set of fields that can be used to partially patch a document.\r\n * FieldMask is used in conjunction with ObjectValue.\r\n * Examples:\r\n * foo - Overwrites foo entirely with the provided value. If foo is not\r\n * present in the companion ObjectValue, the field is deleted.\r\n * foo.bar - Overwrites only the field bar of the object foo.\r\n * If foo is not an object, foo is replaced with an object\r\n * containing foo\r\n */\r\nvar FieldMask = /** @class */ (function () {\r\n function FieldMask(fields) {\r\n this.fields = fields;\r\n // TODO(dimond): validation of FieldMask\r\n }\r\n FieldMask.prototype.isEqual = function (other) {\r\n return arrayEquals(this.fields, other.fields);\r\n };\r\n return FieldMask;\r\n}());\r\n/** Transforms a value into a server-generated timestamp. */\r\nvar ServerTimestampTransform = /** @class */ (function () {\r\n function ServerTimestampTransform() {\r\n }\r\n ServerTimestampTransform.prototype.isEqual = function (other) {\r\n return other instanceof ServerTimestampTransform;\r\n };\r\n ServerTimestampTransform.instance = new ServerTimestampTransform();\r\n return ServerTimestampTransform;\r\n}());\r\n/** A field path and the TransformOperation to perform upon it. */\r\nvar FieldTransform = /** @class */ (function () {\r\n function FieldTransform(field, transform) {\r\n this.field = field;\r\n this.transform = transform;\r\n }\r\n FieldTransform.prototype.isEqual = function (other) {\r\n return (this.field.isEqual(other.field) && this.transform.isEqual(other.transform));\r\n };\r\n return FieldTransform;\r\n}());\r\n/** The result of successfully applying a mutation to the backend. */\r\nvar MutationResult = /** @class */ (function () {\r\n function MutationResult(\r\n /**\r\n * The version at which the mutation was committed or null for a delete.\r\n */\r\n version, \r\n /**\r\n * The resulting fields returned from the backend after a\r\n * TransformMutation has been committed. Contains one FieldValue for each\r\n * FieldTransform that was in the mutation.\r\n *\r\n * Will be null if the mutation was not a TransformMutation.\r\n */\r\n transformResults) {\r\n this.version = version;\r\n this.transformResults = transformResults;\r\n }\r\n return MutationResult;\r\n}());\r\nvar MutationType;\r\n(function (MutationType) {\r\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\r\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\r\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\r\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\r\n})(MutationType || (MutationType = {}));\r\n/**\r\n * Encodes a precondition for a mutation. This follows the model that the\r\n * backend accepts with the special case of an explicit \"empty\" precondition\r\n * (meaning no precondition).\r\n */\r\nvar Precondition = /** @class */ (function () {\r\n function Precondition(updateTime, exists) {\r\n this.updateTime = updateTime;\r\n this.exists = exists;\r\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\r\n }\r\n /** Creates a new Precondition with an exists flag. */\r\n Precondition.exists = function (exists) {\r\n return new Precondition(undefined, exists);\r\n };\r\n /** Creates a new Precondition based on a version a document exists at. */\r\n Precondition.updateTime = function (version) {\r\n return new Precondition(version);\r\n };\r\n Object.defineProperty(Precondition.prototype, \"isNone\", {\r\n /** Returns whether this Precondition is empty. */\r\n get: function () {\r\n return this.updateTime === undefined && this.exists === undefined;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Returns true if the preconditions is valid for the given document\r\n * (or null if no document is available).\r\n */\r\n Precondition.prototype.isValidFor = function (maybeDoc) {\r\n if (this.updateTime !== undefined) {\r\n return (maybeDoc instanceof Document &&\r\n maybeDoc.version.isEqual(this.updateTime));\r\n }\r\n else if (this.exists !== undefined) {\r\n if (this.exists) {\r\n return maybeDoc instanceof Document;\r\n }\r\n else {\r\n return maybeDoc === null || maybeDoc instanceof NoDocument;\r\n }\r\n }\r\n else {\r\n assert(this.isNone, 'Precondition should be empty');\r\n return true;\r\n }\r\n };\r\n Precondition.prototype.isEqual = function (other) {\r\n return (equals(this.updateTime, other.updateTime) &&\r\n this.exists === other.exists);\r\n };\r\n Precondition.NONE = new Precondition();\r\n return Precondition;\r\n}());\r\n/**\r\n * A mutation describes a self-contained change to a document. Mutations can\r\n * create, replace, delete, and update subsets of documents.\r\n *\r\n * Mutations not only act on the value of the document but also it version.\r\n * In the case of Set, Patch, and Transform mutations we preserve the existing\r\n * version. In the case of Delete mutations, we reset the version to 0.\r\n *\r\n * Here's the expected transition table.\r\n *\r\n * MUTATION APPLIED TO RESULTS IN\r\n *\r\n * SetMutation Document(v3) Document(v3)\r\n * SetMutation NoDocument(v3) Document(v0)\r\n * SetMutation null Document(v0)\r\n * PatchMutation Document(v3) Document(v3)\r\n * PatchMutation NoDocument(v3) NoDocument(v3)\r\n * PatchMutation null null\r\n * TransformMutation Document(v3) Document(v3)\r\n * TransformMutation NoDocument(v3) NoDocument(v3)\r\n * TransformMutation null null\r\n * DeleteMutation Document(v3) NoDocument(v0)\r\n * DeleteMutation NoDocument(v3) NoDocument(v0)\r\n * DeleteMutation null NoDocument(v0)\r\n *\r\n * Note that TransformMutations don't create Documents (in the case of being\r\n * applied to a NoDocument), even though they would on the backend. This is\r\n * because the client always combines the TransformMutation with a SetMutation\r\n * or PatchMutation and we only want to apply the transform if the prior\r\n * mutation resulted in a Document (always true for a SetMutation, but not\r\n * necessarily for a PatchMutation).\r\n *\r\n * ## Subclassing Notes\r\n *\r\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\r\n * applyToLocalView() to implement the actual behavior of applying the mutation\r\n * to some source document.\r\n */\r\nvar Mutation = /** @class */ (function () {\r\n function Mutation() {\r\n }\r\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\r\n if (maybeDoc != null) {\r\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\r\n }\r\n };\r\n /**\r\n * Returns the version from the given document for use as the result of a\r\n * mutation. Mutations are defined to return the version of the base document\r\n * only if it is an existing document. Deleted and unknown documents have a\r\n * post-mutation version of SnapshotVersion.MIN.\r\n */\r\n Mutation.getPostMutationVersion = function (maybeDoc) {\r\n if (maybeDoc instanceof Document) {\r\n return maybeDoc.version;\r\n }\r\n else {\r\n return SnapshotVersion.MIN;\r\n }\r\n };\r\n return Mutation;\r\n}());\r\n/**\r\n * A mutation that creates or replaces the document at the given key with the\r\n * object value contents.\r\n */\r\nvar SetMutation = /** @class */ (function (_super) {\r\n __extends(SetMutation, _super);\r\n function SetMutation(key, value, precondition) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.value = value;\r\n _this.precondition = precondition;\r\n _this.type = MutationType.Set;\r\n return _this;\r\n }\r\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\r\n // Unlike applyToLocalView, if we're applying a mutation to a remote\r\n // document the server has accepted the mutation so the precondition must\r\n // have held.\r\n var version = Mutation.getPostMutationVersion(maybeDoc);\r\n return new Document(this.key, version, this.value, {\r\n hasLocalMutations: false\r\n });\r\n };\r\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var version = Mutation.getPostMutationVersion(maybeDoc);\r\n return new Document(this.key, version, this.value, {\r\n hasLocalMutations: true\r\n });\r\n };\r\n SetMutation.prototype.isEqual = function (other) {\r\n return (other instanceof SetMutation &&\r\n this.key.isEqual(other.key) &&\r\n this.value.isEqual(other.value) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n return SetMutation;\r\n}(Mutation));\r\n/**\r\n * A mutation that modifies fields of the document at the given key with the\r\n * given values. The values are applied through a field mask:\r\n *\r\n * * When a field is in both the mask and the values, the corresponding field\r\n * is updated.\r\n * * When a field is in neither the mask nor the values, the corresponding\r\n * field is unmodified.\r\n * * When a field is in the mask but not in the values, the corresponding field\r\n * is deleted.\r\n * * When a field is not in the mask but is in the values, the values map is\r\n * ignored.\r\n */\r\nvar PatchMutation = /** @class */ (function (_super) {\r\n __extends(PatchMutation, _super);\r\n function PatchMutation(key, data, fieldMask, precondition) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.data = data;\r\n _this.fieldMask = fieldMask;\r\n _this.precondition = precondition;\r\n _this.type = MutationType.Patch;\r\n return _this;\r\n }\r\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\r\n // TODO(mcg): Relax enforcement of this precondition\r\n //\r\n // We shouldn't actually enforce the precondition since it already passed on\r\n // the backend, but we may not have a local version of the document to\r\n // patch, so we use the precondition to prevent incorrectly putting a\r\n // partial document into our cache.\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var version = Mutation.getPostMutationVersion(maybeDoc);\r\n var newData = this.patchDocument(maybeDoc);\r\n return new Document(this.key, version, newData, {\r\n hasLocalMutations: false\r\n });\r\n };\r\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var version = Mutation.getPostMutationVersion(maybeDoc);\r\n var newData = this.patchDocument(maybeDoc);\r\n return new Document(this.key, version, newData, {\r\n hasLocalMutations: true\r\n });\r\n };\r\n PatchMutation.prototype.isEqual = function (other) {\r\n return (other instanceof PatchMutation &&\r\n this.key.isEqual(other.key) &&\r\n this.fieldMask.isEqual(other.fieldMask) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n /**\r\n * Patches the data of document if available or creates a new document. Note\r\n * that this does not check whether or not the precondition of this patch\r\n * holds.\r\n */\r\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\r\n var data;\r\n if (maybeDoc instanceof Document) {\r\n data = maybeDoc.data;\r\n }\r\n else {\r\n data = ObjectValue.EMPTY;\r\n }\r\n return this.patchObject(data);\r\n };\r\n PatchMutation.prototype.patchObject = function (data) {\r\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\r\n var fieldPath = _a[_i];\r\n var newValue = this.data.field(fieldPath);\r\n if (newValue !== undefined) {\r\n data = data.set(fieldPath, newValue);\r\n }\r\n else {\r\n data = data.delete(fieldPath);\r\n }\r\n }\r\n return data;\r\n };\r\n return PatchMutation;\r\n}(Mutation));\r\n/**\r\n * A mutation that modifies specific fields of the document with transform\r\n * operations. Currently the only supported transform is a server timestamp, but\r\n * IP Address, increment(n), etc. could be supported in the future.\r\n *\r\n * It is somewhat similar to a PatchMutation in that it patches specific fields\r\n * and has no effect when applied to a null or NoDocument (see comment on\r\n * Mutation for rationale).\r\n */\r\nvar TransformMutation = /** @class */ (function (_super) {\r\n __extends(TransformMutation, _super);\r\n function TransformMutation(key, fieldTransforms) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.fieldTransforms = fieldTransforms;\r\n _this.type = MutationType.Transform;\r\n // NOTE: We set a precondition of exists: true as a safety-check, since we\r\n // always combine TransformMutations with a SetMutation or PatchMutation which\r\n // (if successful) should end up with an existing document.\r\n _this.precondition = Precondition.exists(true);\r\n return _this;\r\n }\r\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\r\n var transformResults = mutationResult.transformResults;\r\n // TODO(mcg): Relax enforcement of this precondition\r\n //\r\n // We shouldn't actually enforce the precondition since it already passed on\r\n // the backend, but we may not have a local version of the document to\r\n // patch, so we use the precondition to prevent incorrectly putting a\r\n // partial document into our cache.\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var doc = this.requireDocument(maybeDoc);\r\n var newData = this.transformObject(doc.data, transformResults);\r\n return new Document(this.key, doc.version, newData, {\r\n hasLocalMutations: false\r\n });\r\n };\r\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var doc = this.requireDocument(maybeDoc);\r\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\r\n var newData = this.transformObject(doc.data, transformResults);\r\n return new Document(this.key, doc.version, newData, {\r\n hasLocalMutations: true\r\n });\r\n };\r\n TransformMutation.prototype.isEqual = function (other) {\r\n return (other instanceof TransformMutation &&\r\n this.key.isEqual(other.key) &&\r\n arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n /**\r\n * Asserts that the given MaybeDocument is actually a Document and verifies\r\n * that it matches the key for this mutation. Since we only support\r\n * transformations with precondition exists this method is guaranteed to be\r\n * safe.\r\n */\r\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\r\n assert(maybeDoc instanceof Document, 'Unknown MaybeDocument type ' + maybeDoc);\r\n var doc = maybeDoc;\r\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\r\n return doc;\r\n };\r\n /**\r\n * Creates a list of \"transform results\" (a transform result is a field value\r\n * representing the result of applying a transform) for use when applying a\r\n * TransformMutation locally.\r\n *\r\n * @param localWriteTime The local time of the transform mutation (used to\r\n * generate ServerTimestampValues).\r\n * @param baseDoc The document prior to applying this mutation batch.\r\n * @return The transform results list.\r\n */\r\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\r\n var transformResults = [];\r\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\r\n var fieldTransform = _a[_i];\r\n var transform = fieldTransform.transform;\r\n if (transform instanceof ServerTimestampTransform) {\r\n var previousValue = null;\r\n if (baseDoc instanceof Document) {\r\n previousValue = baseDoc.field(fieldTransform.field) || null;\r\n }\r\n transformResults.push(new ServerTimestampValue(localWriteTime, previousValue));\r\n }\r\n else {\r\n return fail('Encountered unknown transform: ' + transform);\r\n }\r\n }\r\n return transformResults;\r\n };\r\n TransformMutation.prototype.transformObject = function (data, transformResults) {\r\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\r\n for (var i = 0; i < this.fieldTransforms.length; i++) {\r\n var fieldTransform = this.fieldTransforms[i];\r\n var transform = fieldTransform.transform;\r\n var fieldPath = fieldTransform.field;\r\n if (transform instanceof ServerTimestampTransform) {\r\n data = data.set(fieldPath, transformResults[i]);\r\n }\r\n else {\r\n return fail('Encountered unknown transform: ' + transform);\r\n }\r\n }\r\n return data;\r\n };\r\n return TransformMutation;\r\n}(Mutation));\r\n/** A mutation that deletes the document at the given key. */\r\nvar DeleteMutation = /** @class */ (function (_super) {\r\n __extends(DeleteMutation, _super);\r\n function DeleteMutation(key, precondition) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.precondition = precondition;\r\n _this.type = MutationType.Delete;\r\n return _this;\r\n }\r\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\r\n // Unlike applyToLocalView, if we're applying a mutation to a remote\r\n // document the server has accepted the mutation so the precondition must\r\n // have held.\r\n return new NoDocument(this.key, SnapshotVersion.MIN);\r\n };\r\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n if (maybeDoc) {\r\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\r\n }\r\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\r\n };\r\n DeleteMutation.prototype.isEqual = function (other) {\r\n return (other instanceof DeleteMutation &&\r\n this.key.isEqual(other.key) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n return DeleteMutation;\r\n}(Mutation));\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar ExistenceFilter = /** @class */ (function () {\r\n // TODO(b/33078163): just use simplest form of existence filter for now\r\n function ExistenceFilter(count) {\r\n this.count = count;\r\n }\r\n ExistenceFilter.prototype.isEqual = function (other) {\r\n return other && other.count === this.count;\r\n };\r\n return ExistenceFilter;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Error Codes describing the different ways GRPC can fail. These are copied\r\n * directly from GRPC's sources here:\r\n *\r\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\r\n *\r\n * Important! The names of these identifiers matter because the string forms\r\n * are used for reverse lookups from the webchannel stream. Do NOT change the\r\n * names of these identifiers.\r\n */\r\nvar RpcCode;\r\n(function (RpcCode) {\r\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\r\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\r\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\r\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\r\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\r\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\r\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\r\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\r\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\r\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\r\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\r\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\r\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\r\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\r\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\r\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\r\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\r\n})(RpcCode || (RpcCode = {}));\r\nfunction isPermanentError(code) {\r\n switch (code) {\r\n case Code.OK:\r\n return fail('Treated status OK as error');\r\n case Code.CANCELLED:\r\n case Code.UNKNOWN:\r\n case Code.DEADLINE_EXCEEDED:\r\n case Code.RESOURCE_EXHAUSTED:\r\n case Code.INTERNAL:\r\n case Code.UNAVAILABLE:\r\n // Unauthenticated means something went wrong with our token and we need\r\n // to retry with new credentials which will happen automatically.\r\n // TODO(b/37325376): Give up after second unauthenticated error.\r\n case Code.UNAUTHENTICATED:\r\n return false;\r\n case Code.INVALID_ARGUMENT:\r\n case Code.NOT_FOUND:\r\n case Code.ALREADY_EXISTS:\r\n case Code.PERMISSION_DENIED:\r\n case Code.FAILED_PRECONDITION:\r\n // Aborted might be retried in some scenarios, but that is dependant on\r\n // the context and should handled individually by the calling code.\r\n // See https://cloud.google.com/apis/design/errors.\r\n case Code.ABORTED:\r\n case Code.OUT_OF_RANGE:\r\n case Code.UNIMPLEMENTED:\r\n case Code.DATA_LOSS:\r\n return true;\r\n default:\r\n return fail('Unknown status code: ' + code);\r\n }\r\n}\r\n/**\r\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\r\n *\r\n * @returns The Code equivalent to the given status string or undefined if\r\n * there is no match.\r\n */\r\nfunction mapCodeFromRpcStatus(status) {\r\n // tslint:disable-next-line:no-any lookup by string\r\n var code = RpcCode[status];\r\n if (code === undefined) {\r\n return undefined;\r\n }\r\n return mapCodeFromRpcCode(code);\r\n}\r\n/**\r\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\r\n * are not the same as HTTP status codes.\r\n *\r\n * @returns The Code equivalent to the given GRPC status code. Fails if there\r\n * is no match.\r\n */\r\nfunction mapCodeFromRpcCode(code) {\r\n if (code === undefined) {\r\n // This shouldn't normally happen, but in certain error cases (like trying\r\n // to send invalid proto messages) we may get an error with no GRPC code.\r\n error('GRPC error has no .code');\r\n return Code.UNKNOWN;\r\n }\r\n switch (code) {\r\n case RpcCode.OK:\r\n return Code.OK;\r\n case RpcCode.CANCELLED:\r\n return Code.CANCELLED;\r\n case RpcCode.UNKNOWN:\r\n return Code.UNKNOWN;\r\n case RpcCode.DEADLINE_EXCEEDED:\r\n return Code.DEADLINE_EXCEEDED;\r\n case RpcCode.RESOURCE_EXHAUSTED:\r\n return Code.RESOURCE_EXHAUSTED;\r\n case RpcCode.INTERNAL:\r\n return Code.INTERNAL;\r\n case RpcCode.UNAVAILABLE:\r\n return Code.UNAVAILABLE;\r\n case RpcCode.UNAUTHENTICATED:\r\n return Code.UNAUTHENTICATED;\r\n case RpcCode.INVALID_ARGUMENT:\r\n return Code.INVALID_ARGUMENT;\r\n case RpcCode.NOT_FOUND:\r\n return Code.NOT_FOUND;\r\n case RpcCode.ALREADY_EXISTS:\r\n return Code.ALREADY_EXISTS;\r\n case RpcCode.PERMISSION_DENIED:\r\n return Code.PERMISSION_DENIED;\r\n case RpcCode.FAILED_PRECONDITION:\r\n return Code.FAILED_PRECONDITION;\r\n case RpcCode.ABORTED:\r\n return Code.ABORTED;\r\n case RpcCode.OUT_OF_RANGE:\r\n return Code.OUT_OF_RANGE;\r\n case RpcCode.UNIMPLEMENTED:\r\n return Code.UNIMPLEMENTED;\r\n case RpcCode.DATA_LOSS:\r\n return Code.DATA_LOSS;\r\n default:\r\n return fail('Unknown status code: ' + code);\r\n }\r\n}\r\n/**\r\n * Maps an RPC code from a Code. This is the reverse operation from\r\n * mapCodeFromRpcCode and should really only be used in tests.\r\n */\r\nfunction mapRpcCodeFromCode(code) {\r\n if (code === undefined) {\r\n return RpcCode.OK;\r\n }\r\n switch (code) {\r\n case Code.OK:\r\n return RpcCode.OK;\r\n case Code.CANCELLED:\r\n return RpcCode.CANCELLED;\r\n case Code.UNKNOWN:\r\n return RpcCode.UNKNOWN;\r\n case Code.DEADLINE_EXCEEDED:\r\n return RpcCode.DEADLINE_EXCEEDED;\r\n case Code.RESOURCE_EXHAUSTED:\r\n return RpcCode.RESOURCE_EXHAUSTED;\r\n case Code.INTERNAL:\r\n return RpcCode.INTERNAL;\r\n case Code.UNAVAILABLE:\r\n return RpcCode.UNAVAILABLE;\r\n case Code.UNAUTHENTICATED:\r\n return RpcCode.UNAUTHENTICATED;\r\n case Code.INVALID_ARGUMENT:\r\n return RpcCode.INVALID_ARGUMENT;\r\n case Code.NOT_FOUND:\r\n return RpcCode.NOT_FOUND;\r\n case Code.ALREADY_EXISTS:\r\n return RpcCode.ALREADY_EXISTS;\r\n case Code.PERMISSION_DENIED:\r\n return RpcCode.PERMISSION_DENIED;\r\n case Code.FAILED_PRECONDITION:\r\n return RpcCode.FAILED_PRECONDITION;\r\n case Code.ABORTED:\r\n return RpcCode.ABORTED;\r\n case Code.OUT_OF_RANGE:\r\n return RpcCode.OUT_OF_RANGE;\r\n case Code.UNIMPLEMENTED:\r\n return RpcCode.UNIMPLEMENTED;\r\n case Code.DATA_LOSS:\r\n return RpcCode.DATA_LOSS;\r\n default:\r\n return fail('Unknown status code: ' + code);\r\n }\r\n}\r\n/**\r\n * Converts an HTTP Status Code to the equivalent error code.\r\n *\r\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\r\n * @returns The equivalent Code. Unknown status codes are mapped to\r\n * Code.UNKNOWN.\r\n */\r\nfunction mapCodeFromHttpStatus(status) {\r\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\r\n // status codes but the mapping is not bijective. In each case of ambiguity\r\n // this function chooses a primary error.\r\n //\r\n // [1]\r\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n switch (status) {\r\n case 200: // OK\r\n return Code.OK;\r\n case 400: // Bad Request\r\n return Code.INVALID_ARGUMENT;\r\n // Other possibilities based on the forward mapping\r\n // return Code.FAILED_PRECONDITION;\r\n // return Code.OUT_OF_RANGE;\r\n case 401: // Unauthorized\r\n return Code.UNAUTHENTICATED;\r\n case 403: // Forbidden\r\n return Code.PERMISSION_DENIED;\r\n case 404: // Not Found\r\n return Code.NOT_FOUND;\r\n case 409: // Conflict\r\n return Code.ABORTED;\r\n // Other possibilities:\r\n // return Code.ALREADY_EXISTS;\r\n case 416: // Range Not Satisfiable\r\n return Code.OUT_OF_RANGE;\r\n case 429: // Too Many Requests\r\n return Code.RESOURCE_EXHAUSTED;\r\n case 499: // Client Closed Request\r\n return Code.CANCELLED;\r\n case 500: // Internal Server Error\r\n return Code.UNKNOWN;\r\n // Other possibilities:\r\n // return Code.INTERNAL;\r\n // return Code.DATA_LOSS;\r\n case 501: // Unimplemented\r\n return Code.UNIMPLEMENTED;\r\n case 503: // Service Unavailable\r\n return Code.UNAVAILABLE;\r\n case 504: // Gateway Timeout\r\n return Code.DEADLINE_EXCEEDED;\r\n default:\r\n if (status >= 200 && status < 300)\r\n return Code.OK;\r\n if (status >= 400 && status < 500)\r\n return Code.FAILED_PRECONDITION;\r\n if (status >= 500 && status < 600)\r\n return Code.INTERNAL;\r\n return Code.UNKNOWN;\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * SortedSet is an immutable (copy-on-write) collection that holds elements\r\n * in order specified by the provided comparator.\r\n *\r\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\r\n * be equal!\r\n */\r\nvar SortedSet = /** @class */ (function () {\r\n function SortedSet(comparator) {\r\n this.comparator = comparator;\r\n this.data = new SortedMap(this.comparator);\r\n }\r\n /**\r\n * Creates a SortedSet from the keys of the map.\r\n * This is currently implemented as an O(n) copy.\r\n */\r\n SortedSet.fromMapKeys = function (map) {\r\n var keys = new SortedSet(map.comparator);\r\n map.forEach(function (key) {\r\n keys = keys.add(key);\r\n });\r\n return keys;\r\n };\r\n SortedSet.prototype.has = function (elem) {\r\n return this.data.get(elem) !== null;\r\n };\r\n SortedSet.prototype.first = function () {\r\n return this.data.minKey();\r\n };\r\n SortedSet.prototype.last = function () {\r\n return this.data.maxKey();\r\n };\r\n Object.defineProperty(SortedSet.prototype, \"size\", {\r\n get: function () {\r\n return this.data.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n SortedSet.prototype.indexOf = function (elem) {\r\n return this.data.indexOf(elem);\r\n };\r\n /** Iterates elements in order defined by \"comparator\" */\r\n SortedSet.prototype.forEach = function (cb) {\r\n this.data.inorderTraversal(function (k, v) {\r\n cb(k);\r\n return false;\r\n });\r\n };\r\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\r\n SortedSet.prototype.forEachInRange = function (range, cb) {\r\n var iter = this.data.getIteratorFrom(range[0]);\r\n while (iter.hasNext()) {\r\n var elem = iter.getNext();\r\n if (this.comparator(elem.key, range[1]) >= 0)\r\n return;\r\n cb(elem.key);\r\n }\r\n };\r\n /**\r\n * Iterates over `elem`s such that: start <= elem until false is returned.\r\n */\r\n SortedSet.prototype.forEachWhile = function (cb, start) {\r\n var iter;\r\n if (start !== undefined) {\r\n iter = this.data.getIteratorFrom(start);\r\n }\r\n else {\r\n iter = this.data.getIterator();\r\n }\r\n while (iter.hasNext()) {\r\n var elem = iter.getNext();\r\n var result = cb(elem.key);\r\n if (!result)\r\n return;\r\n }\r\n };\r\n /** Finds the least element greater than or equal to `elem`. */\r\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\r\n var iter = this.data.getIteratorFrom(elem);\r\n return iter.hasNext() ? iter.getNext().key : null;\r\n };\r\n /** Inserts or updates an element */\r\n SortedSet.prototype.add = function (elem) {\r\n return this.copy(this.data.remove(elem).insert(elem, true));\r\n };\r\n /** Deletes an element */\r\n SortedSet.prototype.delete = function (elem) {\r\n if (!this.has(elem))\r\n return this;\r\n return this.copy(this.data.remove(elem));\r\n };\r\n SortedSet.prototype.isEmpty = function () {\r\n return this.data.isEmpty();\r\n };\r\n SortedSet.prototype.unionWith = function (other) {\r\n var result = this;\r\n other.forEach(function (elem) {\r\n result = result.add(elem);\r\n });\r\n return result;\r\n };\r\n SortedSet.prototype.isEqual = function (other) {\r\n if (!(other instanceof SortedSet))\r\n return false;\r\n if (this.size !== other.size)\r\n return false;\r\n var thisIt = this.data.getIterator();\r\n var otherIt = other.data.getIterator();\r\n while (thisIt.hasNext()) {\r\n var thisElem = thisIt.getNext().key;\r\n var otherElem = otherIt.getNext().key;\r\n if (this.comparator(thisElem, otherElem) !== 0)\r\n return false;\r\n }\r\n return true;\r\n };\r\n SortedSet.prototype.toString = function () {\r\n var result = [];\r\n this.forEach(function (elem) { return result.push(elem); });\r\n return 'SortedSet(' + result.toString() + ')';\r\n };\r\n SortedSet.prototype.copy = function (data) {\r\n var result = new SortedSet(this.comparator);\r\n result.data = data;\r\n return result;\r\n };\r\n return SortedSet;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\r\nfunction maybeDocumentMap() {\r\n return EMPTY_MAYBE_DOCUMENT_MAP;\r\n}\r\nvar EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\r\nfunction documentMap() {\r\n return EMPTY_DOCUMENT_MAP;\r\n}\r\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator);\r\nfunction documentVersionMap() {\r\n return EMPTY_DOCUMENT_VERSION_MAP;\r\n}\r\nvar EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\r\nfunction documentKeySet() {\r\n return EMPTY_DOCUMENT_KEY_SET;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * An event from the RemoteStore. It is split into targetChanges (changes to the\r\n * state or the set of documents in our watched targets) and documentUpdates\r\n * (changes to the actual documents).\r\n */\r\nvar RemoteEvent = /** @class */ (function () {\r\n function RemoteEvent(\r\n /**\r\n * The snapshot version this event brings us up to, or MIN if not set.\r\n */\r\n snapshotVersion, \r\n /**\r\n * A map from target to changes to the target. See TargetChange.\r\n */\r\n targetChanges, \r\n /**\r\n * A set of which documents have changed or been deleted, along with the\r\n * doc's new values (if not deleted).\r\n */\r\n documentUpdates) {\r\n this.snapshotVersion = snapshotVersion;\r\n this.targetChanges = targetChanges;\r\n this.documentUpdates = documentUpdates;\r\n }\r\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\r\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\r\n };\r\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\r\n /*\r\n * An existence filter mismatch will reset the query and we need to reset\r\n * the mapping to contain no documents and an empty resume token.\r\n *\r\n * Note:\r\n * * The reset mapping is empty, specifically forcing the consumer of the\r\n * change to forget all keys for this targetID;\r\n * * The resume snapshot for this target must be reset\r\n * * The target must be unacked because unwatching and rewatching\r\n * introduces a race for changes.\r\n */\r\n this.targetChanges[targetId] = {\r\n mapping: new ResetMapping(),\r\n snapshotVersion: SnapshotVersion.MIN,\r\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\r\n resumeToken: emptyByteString()\r\n };\r\n };\r\n return RemoteEvent;\r\n}());\r\n/**\r\n * Represents an update to the current status of a target, either explicitly\r\n * having no new state, or the new value to set. Note \"current\" has special\r\n * meaning for in the RPC protocol that implies that a target is both up-to-date\r\n * and consistent with the rest of the watch stream.\r\n */\r\nvar CurrentStatusUpdate;\r\n(function (CurrentStatusUpdate) {\r\n /** The current status is not affected and should not be modified. */\r\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\r\n /** The target must be marked as no longer \"current\". */\r\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\r\n /** The target must be marked as \"current\". */\r\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\r\n})(CurrentStatusUpdate || (CurrentStatusUpdate = {}));\r\nvar EMPTY_KEY_SET = documentKeySet();\r\nvar ResetMapping = /** @class */ (function () {\r\n function ResetMapping() {\r\n this.docs = EMPTY_KEY_SET;\r\n }\r\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\r\n get: function () {\r\n return this.docs;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n ResetMapping.prototype.add = function (key) {\r\n this.docs = this.docs.add(key);\r\n };\r\n ResetMapping.prototype.delete = function (key) {\r\n this.docs = this.docs.delete(key);\r\n };\r\n ResetMapping.prototype.isEqual = function (other) {\r\n return other !== null && this.docs.isEqual(other.docs);\r\n };\r\n return ResetMapping;\r\n}());\r\nvar UpdateMapping = /** @class */ (function () {\r\n function UpdateMapping() {\r\n this.addedDocuments = EMPTY_KEY_SET;\r\n this.removedDocuments = EMPTY_KEY_SET;\r\n }\r\n UpdateMapping.prototype.applyToKeySet = function (keys) {\r\n var result = keys;\r\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\r\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\r\n return result;\r\n };\r\n UpdateMapping.prototype.add = function (key) {\r\n this.addedDocuments = this.addedDocuments.add(key);\r\n this.removedDocuments = this.removedDocuments.delete(key);\r\n };\r\n UpdateMapping.prototype.delete = function (key) {\r\n this.addedDocuments = this.addedDocuments.delete(key);\r\n this.removedDocuments = this.removedDocuments.add(key);\r\n };\r\n UpdateMapping.prototype.isEqual = function (other) {\r\n return (other !== null &&\r\n this.addedDocuments.isEqual(other.addedDocuments) &&\r\n this.removedDocuments.isEqual(other.removedDocuments));\r\n };\r\n return UpdateMapping;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Represents a changed document and a list of target ids to which this change\r\n * applies.\r\n *\r\n * If document has been deleted NoDocument will be provided.\r\n */\r\nvar DocumentWatchChange = /** @class */ (function () {\r\n function DocumentWatchChange(\r\n /** The new document applies to all of these targets. */\r\n updatedTargetIds, \r\n /** The new document is removed from all of these targets. */\r\n removedTargetIds, \r\n /** The key of the document for this change. */\r\n key, \r\n /**\r\n * The new document or NoDocument if it was deleted. Is null if the\r\n * document went out of view without the server sending a new document.\r\n */\r\n newDoc) {\r\n this.updatedTargetIds = updatedTargetIds;\r\n this.removedTargetIds = removedTargetIds;\r\n this.key = key;\r\n this.newDoc = newDoc;\r\n }\r\n return DocumentWatchChange;\r\n}());\r\nvar ExistenceFilterChange = /** @class */ (function () {\r\n function ExistenceFilterChange(targetId, existenceFilter) {\r\n this.targetId = targetId;\r\n this.existenceFilter = existenceFilter;\r\n }\r\n return ExistenceFilterChange;\r\n}());\r\nvar WatchTargetChangeState;\r\n(function (WatchTargetChangeState) {\r\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\r\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\r\nvar WatchTargetChange = /** @class */ (function () {\r\n function WatchTargetChange(\r\n /** What kind of change occurred to the watch target. */\r\n state, \r\n /** The target IDs that were added/removed/set. */\r\n targetIds, \r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data that\r\n * matches the query. The resume token essentially identifies a point in\r\n * time from which the server should resume sending results.\r\n */\r\n resumeToken, \r\n /** An RPC error indicating why the watch failed. */\r\n cause) {\r\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\r\n if (cause === void 0) { cause = null; }\r\n this.state = state;\r\n this.targetIds = targetIds;\r\n this.resumeToken = resumeToken;\r\n this.cause = cause;\r\n }\r\n return WatchTargetChange;\r\n}());\r\n/**\r\n * A helper class to accumulate watch changes into a RemoteEvent and other\r\n * target information.\r\n */\r\nvar WatchChangeAggregator = /** @class */ (function () {\r\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\r\n this.snapshotVersion = snapshotVersion;\r\n this.listenTargets = listenTargets;\r\n /** The existence filter - if any - for the given target IDs. */\r\n this.existenceFilters = {};\r\n /** Keeps track of the current target mappings */\r\n this.targetChanges = {};\r\n /** Keeps track of document to update */\r\n this.documentUpdates = maybeDocumentMap();\r\n /** Whether this aggregator was frozen and can no longer be modified */\r\n this.frozen = false;\r\n this.pendingTargetResponses = shallowCopy(pendingTargetResponses);\r\n }\r\n /** Aggregates a watch change into the current state */\r\n WatchChangeAggregator.prototype.add = function (watchChange) {\r\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\r\n if (watchChange instanceof DocumentWatchChange) {\r\n this.addDocumentChange(watchChange);\r\n }\r\n else if (watchChange instanceof WatchTargetChange) {\r\n this.addTargetChange(watchChange);\r\n }\r\n else if (watchChange instanceof ExistenceFilterChange) {\r\n this.addExistenceFilterChange(watchChange);\r\n }\r\n else {\r\n fail('Unknown watch change: ' + watchChange);\r\n }\r\n };\r\n /** Aggregates all provided watch changes to the current state in order */\r\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\r\n var _this = this;\r\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\r\n watchChanges.forEach(function (change) { return _this.add(change); });\r\n };\r\n /**\r\n * Converts the current state into a remote event with the snapshot version\r\n * provided via the constructor.\r\n */\r\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\r\n var _this = this;\r\n var targetChanges = this.targetChanges;\r\n // Remove all the non-active targets from the remote event.\r\n forEachNumber(this.targetChanges, function (targetId) {\r\n if (!_this.isActiveTarget(targetId)) {\r\n delete targetChanges[targetId];\r\n }\r\n });\r\n // Mark this aggregator as frozen so no further modifications are made\r\n this.frozen = true;\r\n return new RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\r\n };\r\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\r\n var change = this.targetChanges[targetId];\r\n if (!change) {\r\n // Create an UpdateMapping by default, since resets are always explicit.\r\n change = {\r\n currentStatusUpdate: CurrentStatusUpdate.None,\r\n snapshotVersion: this.snapshotVersion,\r\n mapping: new UpdateMapping(),\r\n resumeToken: emptyByteString()\r\n };\r\n this.targetChanges[targetId] = change;\r\n }\r\n return change;\r\n };\r\n /**\r\n * We need to wait for watch to ack targets before we process those events,\r\n * so to know if a target is active, there must be no pending acks we're\r\n * waiting for and it must be in the current list of targets that the client\r\n * cares about.\r\n *\r\n * This method is visible for testing.\r\n */\r\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\r\n return (!contains(this.pendingTargetResponses, targetId) &&\r\n contains(this.listenTargets, targetId));\r\n };\r\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\r\n var relevant = false;\r\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\r\n var targetId = _a[_i];\r\n if (this.isActiveTarget(targetId)) {\r\n var change = this.ensureTargetChange(targetId);\r\n change.mapping.add(docChange.key);\r\n relevant = true;\r\n }\r\n }\r\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\r\n var targetId = _c[_b];\r\n if (this.isActiveTarget(targetId)) {\r\n var change = this.ensureTargetChange(targetId);\r\n change.mapping.delete(docChange.key);\r\n relevant = true;\r\n }\r\n }\r\n // Only update the document if there is a new document to replace to an\r\n // active target that is being listened to, this might be just a target\r\n // update instead.\r\n if (docChange.newDoc && relevant) {\r\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\r\n }\r\n };\r\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\r\n var _this = this;\r\n targetChange.targetIds.forEach(function (targetId) {\r\n var change = _this.ensureTargetChange(targetId);\r\n switch (targetChange.state) {\r\n case WatchTargetChangeState.NoChange:\r\n if (_this.isActiveTarget(targetId)) {\r\n // Creating the change above satisfies the semantics of no-change.\r\n applyResumeToken(change, targetChange.resumeToken);\r\n }\r\n break;\r\n case WatchTargetChangeState.Added:\r\n // We need to decrement the number of pending acks needed from watch\r\n // for this targetId.\r\n _this.recordTargetResponse(targetId);\r\n if (!contains(_this.pendingTargetResponses, targetId)) {\r\n // We have a freshly added target, so we need to reset any state\r\n // that we had previously This can happen e.g. when remove and add\r\n // back a target for existence filter mismatches.\r\n change.mapping = new UpdateMapping();\r\n change.currentStatusUpdate = CurrentStatusUpdate.None;\r\n delete _this.existenceFilters[targetId];\r\n }\r\n applyResumeToken(change, targetChange.resumeToken);\r\n break;\r\n case WatchTargetChangeState.Removed:\r\n // We need to keep track of removed targets to we can\r\n // post-filter and remove any target changes.\r\n // We need to decrement the number of pending acks needed from watch\r\n // for this targetId.\r\n _this.recordTargetResponse(targetId);\r\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\r\n break;\r\n case WatchTargetChangeState.Current:\r\n if (_this.isActiveTarget(targetId)) {\r\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\r\n applyResumeToken(change, targetChange.resumeToken);\r\n }\r\n break;\r\n case WatchTargetChangeState.Reset:\r\n if (_this.isActiveTarget(targetId)) {\r\n // Overwrite any existing target mapping with a reset\r\n // mapping. Every subsequent update will modify the reset\r\n // mapping, not an update mapping.\r\n change.mapping = new ResetMapping();\r\n applyResumeToken(change, targetChange.resumeToken);\r\n }\r\n break;\r\n default:\r\n fail('Unknown target watch change state: ' + targetChange.state);\r\n }\r\n });\r\n };\r\n /**\r\n * Record that we get a watch target add/remove by decrementing the number of\r\n * pending target responses that we have.\r\n */\r\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\r\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\r\n if (newCount === 0) {\r\n delete this.pendingTargetResponses[targetId];\r\n }\r\n else {\r\n this.pendingTargetResponses[targetId] = newCount;\r\n }\r\n };\r\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\r\n if (this.isActiveTarget(change.targetId)) {\r\n this.existenceFilters[change.targetId] = change.existenceFilter;\r\n }\r\n };\r\n return WatchChangeAggregator;\r\n}());\r\n/**\r\n * Applies the resume token to the TargetChange, but only when it has a new\r\n * value. null and empty resumeTokens are discarded.\r\n */\r\nfunction applyResumeToken(change, resumeToken) {\r\n if (resumeToken.length > 0) {\r\n change.resumeToken = resumeToken;\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar DIRECTIONS = (function () {\r\n var dirs = {};\r\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\r\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\r\n return dirs;\r\n})();\r\nvar OPERATORS = (function () {\r\n var ops = {};\r\n ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';\r\n ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\r\n ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\r\n ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\r\n ops[RelationOp.EQUAL.name] = 'EQUAL';\r\n return ops;\r\n})();\r\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\r\nvar ISO_REG_EXP = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\r\nfunction assertPresent(value, description) {\r\n assert(!isNullOrUndefined(value), description + ' is missing');\r\n}\r\nfunction parseInt64(value) {\r\n // TODO(bjornick): Handle int64 greater than 53 bits.\r\n if (typeof value === 'number') {\r\n return value;\r\n }\r\n else if (typeof value === 'string') {\r\n return Number(value);\r\n }\r\n else {\r\n return fail(\"can't parse \" + value);\r\n }\r\n}\r\n/**\r\n * Generates JsonObject values for the Datastore API suitable for sending to\r\n * either GRPC stub methods or via the JSON/HTTP REST API.\r\n * TODO(klimt): We can remove the databaseId argument if we keep the full\r\n * resource name in documents.\r\n */\r\nvar JsonProtoSerializer = /** @class */ (function () {\r\n function JsonProtoSerializer(databaseId, options) {\r\n this.databaseId = databaseId;\r\n this.options = options;\r\n }\r\n JsonProtoSerializer.prototype.emptyByteString = function () {\r\n if (this.options.useProto3Json) {\r\n return '';\r\n }\r\n else {\r\n return new Uint8Array(0);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\r\n // byteStrings can be either string or UInt8Array, but the typings say\r\n // it's always a string. Cast as string to avoid type check failing\r\n return byteString;\r\n };\r\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\r\n var code = status.code === undefined\r\n ? Code.UNKNOWN\r\n : mapCodeFromRpcCode(status.code);\r\n return new FirestoreError(code, status.message || '');\r\n };\r\n /**\r\n * Returns a value for a number (or undefined) that's appropriate to put into\r\n * a google.protobuf.Int32Value proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"number\" because that's what\r\n * our generated proto interfaces say Int32Value must be. But GRPC actually\r\n * expects a { value: } struct.\r\n */\r\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\r\n if (!isNullOrUndefined(val)) {\r\n // tslint:disable-next-line:no-any We need to match generated Proto types.\r\n return { value: val };\r\n }\r\n else {\r\n return undefined;\r\n }\r\n };\r\n /**\r\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as accepting \"number\" because that's what\r\n * our generated proto interfaces say Int32Value must be, but it actually\r\n * accepts { value: number } to match our serialization in toInt32Value().\r\n */\r\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\r\n var result;\r\n if (typeof val === 'object') {\r\n // tslint:disable-next-line:no-any We need to match generated Proto types.\r\n result = val.value;\r\n }\r\n else {\r\n // We accept raw numbers (without the {value: ... } wrapper) for\r\n // compatibility with legacy persisted data.\r\n result = val;\r\n }\r\n return isNullOrUndefined(result) ? null : result;\r\n };\r\n /**\r\n * Returns a value for a Date that's appropriate to put into a proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"string\" because that's what\r\n * our generated proto interfaces say dates must be. But it's easier and safer\r\n * to actually return a Timestamp proto.\r\n */\r\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\r\n return {\r\n seconds: timestamp.seconds,\r\n nanos: timestamp.nanoseconds\r\n // tslint:disable-next-line:no-any\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\r\n // The json interface (for the browser) will return an iso timestamp string,\r\n // while the proto js library (for node) will return a\r\n // google.protobuf.Timestamp instance.\r\n if (typeof date === 'string') {\r\n // TODO(b/37282237): Use strings for Proto3 timestamps\r\n // assert(this.options.useProto3Json,\r\n // 'The timestamp string format requires Proto3.');\r\n return this.fromIso8601String(date);\r\n }\r\n else {\r\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\r\n // TODO(b/37282237): Use strings for Proto3 timestamps\r\n // assert(!this.options.useProto3Json,\r\n // 'The timestamp instance format requires Proto JS.');\r\n var seconds = parseInt64(date.seconds || '0');\r\n var nanos = date.nanos || 0;\r\n return new Timestamp(seconds, nanos);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromIso8601String = function (utc) {\r\n // The date string can have higher precision (nanos) than the Date class\r\n // (millis), so we do some custom parsing here.\r\n // Parse the nanos right out of the string.\r\n var nanos = 0;\r\n var fraction = ISO_REG_EXP.exec(utc);\r\n assert(!!fraction, 'invalid timestamp: ' + utc);\r\n if (fraction[1]) {\r\n // Pad the fraction out to 9 digits (nanos).\r\n var nanoStr = fraction[1];\r\n nanoStr = (nanoStr + '000000000').substr(0, 9);\r\n nanos = Number(nanoStr);\r\n }\r\n // Parse the date to get the seconds.\r\n var date = new Date(utc);\r\n var seconds = Math.floor(date.getTime() / 1000);\r\n return new Timestamp(seconds, nanos);\r\n };\r\n /**\r\n * Returns a value for bytes that's appropriate to put in a proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"string\" because that's what\r\n * our generated proto interfaces say bytes must be. But it should return\r\n * an Uint8Array in Node.\r\n */\r\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\r\n if (this.options.useProto3Json) {\r\n return bytes.toBase64();\r\n }\r\n else {\r\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\r\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\r\n }\r\n };\r\n /**\r\n * Parse the blob from the protos into the internal Blob class. Note that the\r\n * typings assume all blobs are strings, but they are actually Uint8Arrays\r\n * on Node.\r\n */\r\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\r\n if (typeof blob === 'string') {\r\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\r\n return Blob.fromBase64String(blob);\r\n }\r\n else {\r\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\r\n return Blob.fromUint8Array(blob);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toVersion = function (version) {\r\n return this.toTimestamp(version.toTimestamp());\r\n };\r\n JsonProtoSerializer.prototype.fromVersion = function (version) {\r\n assert(!!version, \"Trying to deserialize version that isn't set\");\r\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\r\n };\r\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\r\n return this.fullyQualifiedPrefixPath(databaseId)\r\n .child('documents')\r\n .child(path)\r\n .canonicalString();\r\n };\r\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\r\n var resource = ResourcePath.fromString(name);\r\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\r\n return resource;\r\n };\r\n JsonProtoSerializer.prototype.toName = function (key) {\r\n return this.toResourceName(this.databaseId, key.path);\r\n };\r\n JsonProtoSerializer.prototype.fromName = function (name) {\r\n var resource = this.fromResourceName(name);\r\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\r\n resource.get(1) +\r\n ' vs ' +\r\n this.databaseId.projectId);\r\n assert((!resource.get(3) && !this.databaseId.database) ||\r\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\r\n resource.get(3) +\r\n ' vs ' +\r\n this.databaseId.database);\r\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\r\n };\r\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\r\n if (path.length === 0) {\r\n // If the path is empty, the backend requires we leave off the /documents\r\n // at the end.\r\n return this.encodedDatabaseId;\r\n }\r\n return this.toResourceName(this.databaseId, path);\r\n };\r\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\r\n var resourceName = this.fromResourceName(name);\r\n if (resourceName.length === 4) {\r\n return ResourcePath.EMPTY_PATH;\r\n }\r\n return this.extractLocalPathFromResourceName(resourceName);\r\n };\r\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\r\n get: function () {\r\n var path = new ResourcePath([\r\n 'projects',\r\n this.databaseId.projectId,\r\n 'databases',\r\n this.databaseId.database\r\n ]);\r\n return path.canonicalString();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\r\n return new ResourcePath([\r\n 'projects',\r\n databaseId.projectId,\r\n 'databases',\r\n databaseId.database\r\n ]);\r\n };\r\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\r\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\r\n return resourceName.popFirst(5);\r\n };\r\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\r\n // Resource names have at least 4 components (project ID, database ID)\r\n return (path.length >= 4 &&\r\n path.get(0) === 'projects' &&\r\n path.get(2) === 'databases');\r\n };\r\n JsonProtoSerializer.prototype.toValue = function (val) {\r\n if (val instanceof NullValue) {\r\n return { nullValue: 'NULL_VALUE' };\r\n }\r\n else if (val instanceof BooleanValue) {\r\n return { booleanValue: val.value() };\r\n }\r\n else if (val instanceof IntegerValue) {\r\n return { integerValue: '' + val.value() };\r\n }\r\n else if (val instanceof DoubleValue) {\r\n var doubleValue = val.value();\r\n if (this.options.useProto3Json) {\r\n // Proto 3 let's us encode NaN and Infinity as string values as\r\n // expected by the backend. This is currently not checked by our unit\r\n // tests because they rely on protobuf.js.\r\n if (isNaN(doubleValue)) {\r\n return { doubleValue: 'NaN' };\r\n }\r\n else if (doubleValue === Infinity) {\r\n return { doubleValue: 'Infinity' };\r\n }\r\n else if (doubleValue === -Infinity) {\r\n return { doubleValue: '-Infinity' };\r\n }\r\n }\r\n return { doubleValue: val.value() };\r\n }\r\n else if (val instanceof StringValue) {\r\n return { stringValue: val.value() };\r\n }\r\n else if (val instanceof ObjectValue) {\r\n return { mapValue: this.toMapValue(val) };\r\n }\r\n else if (val instanceof ArrayValue) {\r\n return { arrayValue: this.toArrayValue(val) };\r\n }\r\n else if (val instanceof TimestampValue) {\r\n return {\r\n timestampValue: this.toTimestamp(val.internalValue)\r\n };\r\n }\r\n else if (val instanceof GeoPointValue) {\r\n return {\r\n geoPointValue: {\r\n latitude: val.value().latitude,\r\n longitude: val.value().longitude\r\n }\r\n };\r\n }\r\n else if (val instanceof BlobValue) {\r\n return {\r\n bytesValue: this.toBytes(val.value())\r\n };\r\n }\r\n else if (val instanceof RefValue) {\r\n return {\r\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\r\n };\r\n }\r\n else {\r\n return fail('Unknown FieldValue ' + JSON.stringify(val));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromValue = function (obj) {\r\n var _this = this;\r\n // tslint:disable-next-line:no-any\r\n var type = obj['value_type'];\r\n if (hasTag(obj, type, 'nullValue')) {\r\n return NullValue.INSTANCE;\r\n }\r\n else if (hasTag(obj, type, 'booleanValue')) {\r\n return BooleanValue.of(obj.booleanValue);\r\n }\r\n else if (hasTag(obj, type, 'integerValue')) {\r\n return new IntegerValue(parseInt64(obj.integerValue));\r\n }\r\n else if (hasTag(obj, type, 'doubleValue')) {\r\n if (this.options.useProto3Json) {\r\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\r\n if (obj.doubleValue === 'NaN') {\r\n return DoubleValue.NAN;\r\n }\r\n else if (obj.doubleValue === 'Infinity') {\r\n return DoubleValue.POSITIVE_INFINITY;\r\n }\r\n else if (obj.doubleValue === '-Infinity') {\r\n return DoubleValue.NEGATIVE_INFINITY;\r\n }\r\n }\r\n return new DoubleValue(obj.doubleValue);\r\n }\r\n else if (hasTag(obj, type, 'stringValue')) {\r\n return new StringValue(obj.stringValue);\r\n }\r\n else if (hasTag(obj, type, 'mapValue')) {\r\n return this.fromFields(obj.mapValue.fields || {});\r\n }\r\n else if (hasTag(obj, type, 'arrayValue')) {\r\n // \"values\" is not present if the array is empty\r\n assertPresent(obj.arrayValue, 'arrayValue');\r\n var values = obj.arrayValue.values || [];\r\n return new ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\r\n }\r\n else if (hasTag(obj, type, 'timestampValue')) {\r\n assertPresent(obj.timestampValue, 'timestampValue');\r\n return new TimestampValue(this.fromTimestamp(obj.timestampValue));\r\n }\r\n else if (hasTag(obj, type, 'geoPointValue')) {\r\n assertPresent(obj.geoPointValue, 'geoPointValue');\r\n var latitude = obj.geoPointValue.latitude || 0;\r\n var longitude = obj.geoPointValue.longitude || 0;\r\n return new GeoPointValue(new GeoPoint(latitude, longitude));\r\n }\r\n else if (hasTag(obj, type, 'bytesValue')) {\r\n assertPresent(obj.bytesValue, 'bytesValue');\r\n var blob = this.fromBlob(obj.bytesValue);\r\n return new BlobValue(blob);\r\n }\r\n else if (hasTag(obj, type, 'referenceValue')) {\r\n assertPresent(obj.referenceValue, 'referenceValue');\r\n var resourceName = this.fromResourceName(obj.referenceValue);\r\n var dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\r\n var key = new DocumentKey(this.extractLocalPathFromResourceName(resourceName));\r\n return new RefValue(dbId, key);\r\n }\r\n else {\r\n return fail('Unknown Value proto ' + JSON.stringify(obj));\r\n }\r\n };\r\n /** Creates an api.Document from key and fields (but no create/update time) */\r\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\r\n return {\r\n name: this.toName(key),\r\n fields: this.toFields(fields)\r\n };\r\n };\r\n JsonProtoSerializer.prototype.toDocument = function (document) {\r\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\r\n return {\r\n name: this.toName(document.key),\r\n fields: this.toFields(document.data),\r\n updateTime: this.toTimestamp(document.version.toTimestamp())\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromDocument = function (document) {\r\n return new Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\r\n };\r\n JsonProtoSerializer.prototype.toFields = function (fields) {\r\n var _this = this;\r\n var result = {};\r\n fields.forEach(function (key, value) {\r\n result[key] = _this.toValue(value);\r\n });\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.fromFields = function (object) {\r\n var _this = this;\r\n // Proto map gets mapped to Object, so cast it.\r\n var map = object;\r\n var result = ObjectValue.EMPTY;\r\n forEach(map, function (key, value) {\r\n result = result.set(new FieldPath([key]), _this.fromValue(value));\r\n });\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.toMapValue = function (map) {\r\n return {\r\n fields: this.toFields(map)\r\n };\r\n };\r\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\r\n var _this = this;\r\n var result = [];\r\n array.forEach(function (value) {\r\n result.push(_this.toValue(value));\r\n });\r\n return { values: result };\r\n };\r\n JsonProtoSerializer.prototype.fromFound = function (doc) {\r\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\r\n assertPresent(doc.found.name, 'doc.found.name');\r\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\r\n var key = this.fromName(doc.found.name);\r\n var version = this.fromVersion(doc.found.updateTime);\r\n var fields = this.fromFields(doc.found.fields || {});\r\n return new Document(key, version, fields, { hasLocalMutations: false });\r\n };\r\n JsonProtoSerializer.prototype.fromMissing = function (result) {\r\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\r\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\r\n var key = this.fromName(result.missing);\r\n var version = this.fromVersion(result.readTime);\r\n return new NoDocument(key, version);\r\n };\r\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\r\n // tslint:disable-next-line:no-any\r\n var type = result['result'];\r\n if (hasTag(result, type, 'found')) {\r\n return this.fromFound(result);\r\n }\r\n else if (hasTag(result, type, 'missing')) {\r\n return this.fromMissing(result);\r\n }\r\n return fail('invalid batch get response: ' + JSON.stringify(result));\r\n };\r\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\r\n switch (state) {\r\n case WatchTargetChangeState.Added:\r\n return 'ADD';\r\n case WatchTargetChangeState.Current:\r\n return 'CURRENT';\r\n case WatchTargetChangeState.NoChange:\r\n return 'NO_CHANGE';\r\n case WatchTargetChangeState.Removed:\r\n return 'REMOVE';\r\n case WatchTargetChangeState.Reset:\r\n return 'RESET';\r\n default:\r\n return fail('Unknown WatchTargetChangeState: ' + state);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\r\n if (watchChange instanceof ExistenceFilterChange) {\r\n return {\r\n filter: {\r\n count: watchChange.existenceFilter.count,\r\n targetId: watchChange.targetId\r\n }\r\n };\r\n }\r\n if (watchChange instanceof DocumentWatchChange) {\r\n if (watchChange.newDoc instanceof Document) {\r\n var doc = watchChange.newDoc;\r\n return {\r\n documentChange: {\r\n document: {\r\n name: this.toName(doc.key),\r\n fields: this.toFields(doc.data),\r\n updateTime: this.toVersion(doc.version)\r\n },\r\n targetIds: watchChange.updatedTargetIds,\r\n removedTargetIds: watchChange.removedTargetIds\r\n }\r\n };\r\n }\r\n else if (watchChange.newDoc instanceof NoDocument) {\r\n var doc = watchChange.newDoc;\r\n return {\r\n documentDelete: {\r\n document: this.toName(doc.key),\r\n readTime: this.toVersion(doc.version),\r\n removedTargetIds: watchChange.removedTargetIds\r\n }\r\n };\r\n }\r\n else if (watchChange.newDoc === null) {\r\n return {\r\n documentRemove: {\r\n document: this.toName(watchChange.key),\r\n removedTargetIds: watchChange.removedTargetIds\r\n }\r\n };\r\n }\r\n }\r\n if (watchChange instanceof WatchTargetChange) {\r\n var cause = undefined;\r\n if (watchChange.cause) {\r\n cause = {\r\n code: mapRpcCodeFromCode(watchChange.cause.code),\r\n message: watchChange.cause.message\r\n };\r\n }\r\n return {\r\n targetChange: {\r\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\r\n targetIds: watchChange.targetIds,\r\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\r\n cause: cause\r\n }\r\n };\r\n }\r\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\r\n };\r\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\r\n // tslint:disable-next-line:no-any\r\n var type = change['response_type'];\r\n var watchChange;\r\n if (hasTag(change, type, 'targetChange')) {\r\n assertPresent(change.targetChange, 'targetChange');\r\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\r\n // if unset\r\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\r\n var targetIds = change.targetChange.targetIds || [];\r\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\r\n var causeProto = change.targetChange.cause;\r\n var cause = causeProto && this.fromRpcStatus(causeProto);\r\n watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null);\r\n }\r\n else if (hasTag(change, type, 'documentChange')) {\r\n assertPresent(change.documentChange, 'documentChange');\r\n assertPresent(change.documentChange.document, 'documentChange.name');\r\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\r\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\r\n var entityChange = change.documentChange;\r\n var key = this.fromName(entityChange.document.name);\r\n var version = this.fromVersion(entityChange.document.updateTime);\r\n var fields = this.fromFields(entityChange.document.fields || {});\r\n var doc = new Document(key, version, fields, {\r\n hasLocalMutations: false\r\n });\r\n var updatedTargetIds = entityChange.targetIds || [];\r\n var removedTargetIds = entityChange.removedTargetIds || [];\r\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\r\n }\r\n else if (hasTag(change, type, 'documentDelete')) {\r\n assertPresent(change.documentDelete, 'documentDelete');\r\n assertPresent(change.documentDelete.document, 'documentDelete.document');\r\n var docDelete = change.documentDelete;\r\n var key = this.fromName(docDelete.document);\r\n var version = docDelete.readTime\r\n ? this.fromVersion(docDelete.readTime)\r\n : SnapshotVersion.forDeletedDoc();\r\n var doc = new NoDocument(key, version);\r\n var removedTargetIds = docDelete.removedTargetIds || [];\r\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\r\n }\r\n else if (hasTag(change, type, 'documentRemove')) {\r\n assertPresent(change.documentRemove, 'documentRemove');\r\n assertPresent(change.documentRemove.document, 'documentRemove');\r\n var docRemove = change.documentRemove;\r\n var key = this.fromName(docRemove.document);\r\n var removedTargetIds = docRemove.removedTargetIds || [];\r\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\r\n }\r\n else if (hasTag(change, type, 'filter')) {\r\n // TODO(dimond): implement existence filter parsing with strategy.\r\n assertPresent(change.filter, 'filter');\r\n assertPresent(change.filter.targetId, 'filter.targetId');\r\n var filter = change.filter;\r\n var count = filter.count || 0;\r\n var existenceFilter = new ExistenceFilter(count);\r\n var targetId = filter.targetId;\r\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\r\n }\r\n else {\r\n return fail('Unknown change type ' + JSON.stringify(change));\r\n }\r\n return watchChange;\r\n };\r\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\r\n if (state === 'NO_CHANGE') {\r\n return WatchTargetChangeState.NoChange;\r\n }\r\n else if (state === 'ADD') {\r\n return WatchTargetChangeState.Added;\r\n }\r\n else if (state === 'REMOVE') {\r\n return WatchTargetChangeState.Removed;\r\n }\r\n else if (state === 'CURRENT') {\r\n return WatchTargetChangeState.Current;\r\n }\r\n else if (state === 'RESET') {\r\n return WatchTargetChangeState.Reset;\r\n }\r\n else {\r\n return fail('Got unexpected TargetChange.state: ' + state);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\r\n // We have only reached a consistent snapshot for the entire stream if there\r\n // is a read_time set and it applies to all targets (i.e. the list of\r\n // targets is empty). The backend is guaranteed to send such responses.\r\n // tslint:disable-next-line:no-any\r\n var type = change['response_type'];\r\n if (!hasTag(change, type, 'targetChange')) {\r\n return SnapshotVersion.MIN;\r\n }\r\n var targetChange = change.targetChange;\r\n if (targetChange.targetIds && targetChange.targetIds.length) {\r\n return SnapshotVersion.MIN;\r\n }\r\n if (!targetChange.readTime) {\r\n return SnapshotVersion.MIN;\r\n }\r\n return this.fromVersion(targetChange.readTime);\r\n };\r\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\r\n var _this = this;\r\n var result;\r\n if (mutation instanceof SetMutation) {\r\n result = {\r\n update: this.toMutationDocument(mutation.key, mutation.value)\r\n };\r\n }\r\n else if (mutation instanceof DeleteMutation) {\r\n result = { delete: this.toName(mutation.key) };\r\n }\r\n else if (mutation instanceof PatchMutation) {\r\n result = {\r\n update: this.toMutationDocument(mutation.key, mutation.data),\r\n updateMask: this.toDocumentMask(mutation.fieldMask)\r\n };\r\n }\r\n else if (mutation instanceof TransformMutation) {\r\n result = {\r\n transform: {\r\n document: this.toName(mutation.key),\r\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\r\n return _this.toFieldTransform(transform);\r\n })\r\n }\r\n };\r\n }\r\n else {\r\n return fail('Unknown mutation type ' + mutation.type);\r\n }\r\n if (!mutation.precondition.isNone) {\r\n result.currentDocument = this.toPrecondition(mutation.precondition);\r\n }\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\r\n var _this = this;\r\n var precondition = proto.currentDocument\r\n ? this.fromPrecondition(proto.currentDocument)\r\n : Precondition.NONE;\r\n if (proto.update) {\r\n assertPresent(proto.update.name, 'name');\r\n var key = this.fromName(proto.update.name);\r\n var value = this.fromFields(proto.update.fields || {});\r\n if (proto.updateMask) {\r\n var fieldMask = this.fromDocumentMask(proto.updateMask);\r\n return new PatchMutation(key, value, fieldMask, precondition);\r\n }\r\n else {\r\n return new SetMutation(key, value, precondition);\r\n }\r\n }\r\n else if (proto.delete) {\r\n var key = this.fromName(proto.delete);\r\n return new DeleteMutation(key, precondition);\r\n }\r\n else if (proto.transform) {\r\n var key = this.fromName(proto.transform.document);\r\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\r\n return _this.fromFieldTransform(transform);\r\n });\r\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\r\n return new TransformMutation(key, fieldTransforms);\r\n }\r\n else {\r\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\r\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\r\n if (precondition.updateTime !== undefined) {\r\n return {\r\n updateTime: this.toVersion(precondition.updateTime)\r\n };\r\n }\r\n else if (precondition.exists !== undefined) {\r\n return { exists: precondition.exists };\r\n }\r\n else {\r\n return fail('Unknown precondition');\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\r\n if (precondition.updateTime !== undefined) {\r\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\r\n }\r\n else if (precondition.exists !== undefined) {\r\n return Precondition.exists(precondition.exists);\r\n }\r\n else {\r\n return Precondition.NONE;\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\r\n var _this = this;\r\n // NOTE: Deletes don't have an updateTime.\r\n var version = proto.updateTime\r\n ? this.fromVersion(proto.updateTime)\r\n : null;\r\n var transformResults = null;\r\n if (proto.transformResults && proto.transformResults.length > 0) {\r\n transformResults = proto.transformResults.map(function (result) {\r\n return _this.fromValue(result);\r\n });\r\n }\r\n return new MutationResult(version, transformResults);\r\n };\r\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\r\n var _this = this;\r\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\r\n };\r\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\r\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\r\n return {\r\n fieldPath: fieldTransform.field.canonicalString(),\r\n setToServerValue: 'REQUEST_TIME'\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\r\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\r\n var fieldPath = FieldPath.fromServerFormat(proto.fieldPath);\r\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\r\n };\r\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\r\n return { documents: [this.toQueryPath(query.path)] };\r\n };\r\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\r\n var count = documentsTarget.documents.length;\r\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\r\n var name = documentsTarget.documents[0];\r\n return Query.atPath(this.fromQueryPath(name));\r\n };\r\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\r\n // Dissect the path into parent, collectionId, and optional key filter.\r\n var result = { structuredQuery: {} };\r\n if (query.path.isEmpty()) {\r\n result.parent = this.toQueryPath(ResourcePath.EMPTY_PATH);\r\n }\r\n else {\r\n var path = query.path;\r\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\r\n result.parent = this.toQueryPath(path.popLast());\r\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\r\n }\r\n var where = this.toFilter(query.filters);\r\n if (where) {\r\n result.structuredQuery.where = where;\r\n }\r\n var orderBy = this.toOrder(query.orderBy);\r\n if (orderBy) {\r\n result.structuredQuery.orderBy = orderBy;\r\n }\r\n var limit = this.toInt32Value(query.limit);\r\n if (limit !== undefined) {\r\n result.structuredQuery.limit = limit;\r\n }\r\n if (query.startAt) {\r\n result.structuredQuery.startAt = this.toCursor(query.startAt);\r\n }\r\n if (query.endAt) {\r\n result.structuredQuery.endAt = this.toCursor(query.endAt);\r\n }\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\r\n var path = this.fromQueryPath(target.parent);\r\n var query = target.structuredQuery;\r\n var fromCount = query.from ? query.from.length : 0;\r\n if (fromCount > 0) {\r\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\r\n var from = query.from[0];\r\n path = path.child(from.collectionId);\r\n }\r\n var filterBy = [];\r\n if (query.where) {\r\n filterBy = this.fromFilter(query.where);\r\n }\r\n var orderBy = [];\r\n if (query.orderBy) {\r\n orderBy = this.fromOrder(query.orderBy);\r\n }\r\n var limit = null;\r\n if (query.limit) {\r\n limit = this.fromInt32Value(query.limit);\r\n }\r\n var startAt = null;\r\n if (query.startAt) {\r\n startAt = this.fromCursor(query.startAt);\r\n }\r\n var endAt = null;\r\n if (query.endAt) {\r\n endAt = this.fromCursor(query.endAt);\r\n }\r\n return new Query(path, orderBy, filterBy, limit, startAt, endAt);\r\n };\r\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\r\n var value = this.toLabel(queryData.purpose);\r\n if (value == null) {\r\n return null;\r\n }\r\n else {\r\n return {\r\n 'goog-listen-tags': value\r\n };\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\r\n switch (purpose) {\r\n case QueryPurpose.Listen:\r\n return null;\r\n case QueryPurpose.ExistenceFilterMismatch:\r\n return 'existence-filter-mismatch';\r\n case QueryPurpose.LimboResolution:\r\n return 'limbo-document';\r\n default:\r\n return fail('Unrecognized query purpose: ' + purpose);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\r\n var result;\r\n var query = queryData.query;\r\n if (query.isDocumentQuery()) {\r\n result = { documents: this.toDocumentsTarget(query) };\r\n }\r\n else {\r\n result = { query: this.toQueryTarget(query) };\r\n }\r\n result.targetId = queryData.targetId;\r\n if (queryData.resumeToken.length > 0) {\r\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\r\n }\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.toFilter = function (filters) {\r\n var _this = this;\r\n if (filters.length === 0)\r\n return;\r\n var protos = filters.map(function (filter) {\r\n return filter instanceof RelationFilter\r\n ? _this.toRelationFilter(filter)\r\n : _this.toUnaryFilter(filter);\r\n });\r\n if (protos.length === 1) {\r\n return protos[0];\r\n }\r\n return { compositeFilter: { op: 'AND', filters: protos } };\r\n };\r\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\r\n var _this = this;\r\n if (!filter) {\r\n return [];\r\n }\r\n else if (filter.unaryFilter !== undefined) {\r\n return [this.fromUnaryFilter(filter)];\r\n }\r\n else if (filter.fieldFilter !== undefined) {\r\n return [this.fromRelationFilter(filter)];\r\n }\r\n else if (filter.compositeFilter !== undefined) {\r\n return filter.compositeFilter\r\n .filters.map(function (f) { return _this.fromFilter(f); })\r\n .reduce(function (accum, current) { return accum.concat(current); });\r\n }\r\n else {\r\n return fail('Unknown filter: ' + JSON.stringify(filter));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\r\n var _this = this;\r\n if (orderBys.length === 0)\r\n return;\r\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\r\n };\r\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\r\n var _this = this;\r\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\r\n };\r\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\r\n var _this = this;\r\n return {\r\n before: cursor.before,\r\n values: cursor.position.map(function (component) { return _this.toValue(component); })\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\r\n var _this = this;\r\n var before = !!cursor.before;\r\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\r\n return new Bound(position, before);\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toDirection = function (dir) {\r\n return DIRECTIONS[dir.name];\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\r\n switch (dir) {\r\n case 'ASCENDING':\r\n return Direction.ASCENDING;\r\n case 'DESCENDING':\r\n return Direction.DESCENDING;\r\n default:\r\n return undefined;\r\n }\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\r\n return OPERATORS[op.name];\r\n };\r\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\r\n switch (op) {\r\n case 'EQUAL':\r\n return RelationOp.EQUAL;\r\n case 'GREATER_THAN':\r\n return RelationOp.GREATER_THAN;\r\n case 'GREATER_THAN_OR_EQUAL':\r\n return RelationOp.GREATER_THAN_OR_EQUAL;\r\n case 'LESS_THAN':\r\n return RelationOp.LESS_THAN;\r\n case 'LESS_THAN_OR_EQUAL':\r\n return RelationOp.LESS_THAN_OR_EQUAL;\r\n case 'OPERATOR_UNSPECIFIED':\r\n return fail('Unspecified relation');\r\n default:\r\n return fail('Unknown relation');\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\r\n return { fieldPath: path.canonicalString() };\r\n };\r\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\r\n return FieldPath.fromServerFormat(fieldReference.fieldPath);\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\r\n return {\r\n field: this.toFieldPathReference(orderBy.field),\r\n direction: this.toDirection(orderBy.dir)\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\r\n return new OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\r\n if (filter instanceof RelationFilter) {\r\n return {\r\n fieldFilter: {\r\n field: this.toFieldPathReference(filter.field),\r\n op: this.toOperatorName(filter.op),\r\n value: this.toValue(filter.value)\r\n }\r\n };\r\n }\r\n else {\r\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\r\n return new RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\r\n if (filter instanceof NanFilter) {\r\n return {\r\n unaryFilter: {\r\n field: this.toFieldPathReference(filter.field),\r\n op: 'IS_NAN'\r\n }\r\n };\r\n }\r\n else if (filter instanceof NullFilter) {\r\n return {\r\n unaryFilter: {\r\n field: this.toFieldPathReference(filter.field),\r\n op: 'IS_NULL'\r\n }\r\n };\r\n }\r\n else {\r\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\r\n switch (filter.unaryFilter.op) {\r\n case 'IS_NAN':\r\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\r\n return new NanFilter(nanField);\r\n case 'IS_NULL':\r\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\r\n return new NullFilter(nullField);\r\n case 'OPERATOR_UNSPECIFIED':\r\n return fail('Unspecified filter');\r\n default:\r\n return fail('Unknown filter');\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\r\n return {\r\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\r\n var paths = proto.fieldPaths || [];\r\n var fields = paths.map(function (path) { return FieldPath.fromServerFormat(path); });\r\n return new FieldMask(fields);\r\n };\r\n return JsonProtoSerializer;\r\n}());\r\n/**\r\n * Checks for a specific oneof tag in a protocol buffer message.\r\n *\r\n * This intentionally accommodates two distinct cases:\r\n *\r\n * 1) Messages containing a type tag: these are the format produced by GRPC in\r\n * return values. These may contain default-value mappings for all tags in the\r\n * oneof but the type tag specifies which one was actually set.\r\n *\r\n * 2) Messages that don't contain a type tag: these are the format required by\r\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\r\n * choke claiming that the tags aren't fields in the Message.\r\n *\r\n * Allowing both formats here makes the serializer able to consume the outputs\r\n * it produces: for all messages it supports, fromX(toX(value)) == value.\r\n *\r\n * Note that case 2 suffers from ambiguity: if multiple tags are present\r\n * without a type tag then the callers are structured in such a way that the\r\n * first invocation will win. Since we only parse in this mode when parsing\r\n * the output of a serialize method this works, but it's not a general\r\n * solution.\r\n *\r\n * Unfortunately there is no general solution here because proto3 makes it\r\n * impossible to distinguish unset from explicitly set fields: both have the\r\n * default value for the type. Without the type tag but multiple value tags\r\n * it's possible to have default values for each tag in the oneof and not be\r\n * able to know which was actually in effect.\r\n */\r\nfunction hasTag(obj, type, tag) {\r\n return type === tag || (!type && tag in obj);\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Provides a simple helper class that implements the Stream interface to\r\n * bridge to other implementations that are streams but do not implement the\r\n * interface. The stream callbacks are invoked with the callOn... methods.\r\n */\r\nvar StreamBridge = /** @class */ (function () {\r\n function StreamBridge(args) {\r\n this.sendFn = args.sendFn;\r\n this.closeFn = args.closeFn;\r\n }\r\n StreamBridge.prototype.onOpen = function (callback) {\r\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\r\n this.wrappedOnOpen = callback;\r\n };\r\n StreamBridge.prototype.onClose = function (callback) {\r\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\r\n this.wrappedOnClose = callback;\r\n };\r\n StreamBridge.prototype.onMessage = function (callback) {\r\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\r\n this.wrappedOnMessage = callback;\r\n };\r\n StreamBridge.prototype.close = function () {\r\n this.closeFn();\r\n };\r\n StreamBridge.prototype.send = function (msg) {\r\n this.sendFn(msg);\r\n };\r\n StreamBridge.prototype.callOnOpen = function () {\r\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\r\n this.wrappedOnOpen();\r\n };\r\n StreamBridge.prototype.callOnClose = function (err) {\r\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\r\n this.wrappedOnClose(err);\r\n };\r\n StreamBridge.prototype.callOnMessage = function (msg) {\r\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\r\n this.wrappedOnMessage(msg);\r\n };\r\n return StreamBridge;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG = 'Connection';\r\nvar RPC_STREAM_SERVICE = 'google.firestore.v1beta1.Firestore';\r\nvar RPC_URL_VERSION = 'v1beta1';\r\n/** Maps RPC names to the corresponding REST endpoint name. */\r\nvar RPC_NAME_REST_MAPPING = {\r\n BatchGetDocuments: 'batchGet',\r\n Commit: 'commit'\r\n};\r\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\r\n// we are doing out-of-band releases. Once we release as part of Firebase, we\r\n// should use the Firebase version instead.\r\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\r\nvar XHR_TIMEOUT_SECS = 15;\r\nvar WebChannelConnection = /** @class */ (function () {\r\n function WebChannelConnection(info) {\r\n this.databaseId = info.databaseId;\r\n this.pool = new XhrIoPool();\r\n var proto = info.ssl ? 'https' : 'http';\r\n this.baseUrl = proto + '://' + info.host;\r\n }\r\n /**\r\n * Modifies the headers for a request, adding any authorization token if\r\n * present and any additional headers for the request.\r\n */\r\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\r\n if (token) {\r\n for (var header in token.authHeaders) {\r\n if (token.authHeaders.hasOwnProperty(header)) {\r\n headers[header] = token.authHeaders[header];\r\n }\r\n }\r\n }\r\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\r\n };\r\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\r\n var _this = this;\r\n var url = this.makeUrl(rpcName);\r\n return new Promise(function (resolve, reject) {\r\n // tslint:disable-next-line:no-any XhrIoPool doesn't have TS typings.\r\n _this.pool.getObject(function (xhr) {\r\n xhr.listenOnce(EventType.COMPLETE, function () {\r\n try {\r\n switch (xhr.getLastErrorCode()) {\r\n case ErrorCode.NO_ERROR:\r\n var json = xhr.getResponseJson();\r\n debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\r\n resolve(json);\r\n break;\r\n case ErrorCode.TIMEOUT:\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\r\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\r\n break;\r\n case ErrorCode.HTTP_ERROR:\r\n var status_1 = xhr.getStatus();\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\r\n if (status_1 > 0) {\r\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\r\n }\r\n else {\r\n // If we received an HTTP_ERROR but there's no status code,\r\n // it's most probably a connection issue\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\r\n }\r\n break;\r\n default:\r\n fail('RPC \"' +\r\n rpcName +\r\n '\" failed with unanticipated ' +\r\n 'webchannel error ' +\r\n xhr.getLastErrorCode() +\r\n ': ' +\r\n xhr.getLastError() +\r\n ', giving up.');\r\n }\r\n }\r\n finally {\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\r\n _this.pool.releaseObject(xhr);\r\n }\r\n });\r\n var requestString = JSON.stringify(request);\r\n debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\r\n // Content-Type: text/plain will avoid preflight requests which might\r\n // mess with CORS and redirects by proxies. If we add custom headers\r\n // we will need to change this code to potentially use the\r\n // $httpOverwrite parameter supported by ESF to avoid\r\n // triggering preflight requests.\r\n var headers = { 'Content-Type': 'text/plain' };\r\n _this.modifyHeadersForRequest(headers, token);\r\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\r\n });\r\n });\r\n };\r\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\r\n // The REST API automatically aggregates all of the streamed results, so we\r\n // can just use the normal invoke() method.\r\n return this.invokeRPC(rpcName, request, token);\r\n };\r\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\r\n var urlParts = [\r\n this.baseUrl,\r\n '/',\r\n RPC_STREAM_SERVICE,\r\n '/',\r\n rpcName,\r\n '/channel'\r\n ];\r\n var webchannelTransport = createWebChannelTransport();\r\n var request = {\r\n // Background channel test avoids the initial two test calls and decreases\r\n // initial cold start time.\r\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\r\n // we should monitor closely for any reports.\r\n backgroundChannelTest: true,\r\n // Required for backend stickiness, routing behavior is based on this\r\n // parameter.\r\n httpSessionIdParam: 'gsessionid',\r\n initMessageHeaders: {},\r\n // Send our custom headers as a '$httpHeaders=' url param to avoid CORS\r\n // preflight round-trip. This is formally defined here:\r\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L40\r\n httpHeadersOverwriteParam: '$httpHeaders',\r\n messageUrlParams: {\r\n // This param is used to improve routing and project isolation by the\r\n // backend and must be included in every request.\r\n database: \"projects/\" + this.databaseId.projectId + \"/databases/\" + this.databaseId.database\r\n },\r\n sendRawJson: true,\r\n supportsCrossDomainXhr: true\r\n };\r\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\r\n var url = urlParts.join('');\r\n debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\r\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\r\n var channel = webchannelTransport.createWebChannel(url, request);\r\n // WebChannel supports sending the first message with the handshake - saving\r\n // a network round trip. However, it will have to call send in the same\r\n // JS event loop as open. In order to enforce this, we delay actually\r\n // opening the WebChannel until send is called. Whether we have called\r\n // open is tracked with this variable.\r\n var opened = false;\r\n // A flag to determine whether the stream was closed (by us or through an\r\n // error/close event) to avoid delivering multiple close events or sending\r\n // on a closed stream\r\n var closed = false;\r\n var streamBridge = new StreamBridge({\r\n sendFn: function (msg) {\r\n if (!closed) {\r\n if (!opened) {\r\n debug(LOG_TAG, 'Opening WebChannel transport.');\r\n channel.open();\r\n opened = true;\r\n }\r\n debug(LOG_TAG, 'WebChannel sending:', msg);\r\n channel.send(msg);\r\n }\r\n else {\r\n debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\r\n }\r\n },\r\n closeFn: function () { return channel.close(); }\r\n });\r\n // Closure events are guarded and exceptions are swallowed, so catch any\r\n // exception and rethrow using a setTimeout so they become visible again.\r\n // Note that eventually this function could go away if we are confident\r\n // enough the code is exception free.\r\n var unguardedEventListen = function (type, fn) {\r\n // TODO(dimond): closure typing seems broken because WebChannel does\r\n // not implement goog.events.Listenable\r\n channel.listen(type, function (param) {\r\n try {\r\n fn(param);\r\n }\r\n catch (e) {\r\n setTimeout(function () {\r\n throw e;\r\n }, 0);\r\n }\r\n });\r\n };\r\n unguardedEventListen(WebChannel.EventType.OPEN, function () {\r\n if (!closed) {\r\n debug(LOG_TAG, 'WebChannel transport opened.');\r\n }\r\n });\r\n unguardedEventListen(WebChannel.EventType.CLOSE, function () {\r\n if (!closed) {\r\n closed = true;\r\n debug(LOG_TAG, 'WebChannel transport closed');\r\n streamBridge.callOnClose();\r\n }\r\n });\r\n unguardedEventListen(WebChannel.EventType.ERROR, function (err) {\r\n if (!closed) {\r\n closed = true;\r\n debug(LOG_TAG, 'WebChannel transport errored:', err);\r\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\r\n }\r\n });\r\n unguardedEventListen(WebChannel.EventType.MESSAGE, function (msg) {\r\n if (!closed) {\r\n var msgData = msg.data[0];\r\n assert(!!msgData, 'Got a webchannel message without data.');\r\n // TODO(b/35143891): There is a bug in One Platform that caused errors\r\n // (and only errors) to be wrapped in an extra array. To be forward\r\n // compatible with the bug we need to check either condition. The latter\r\n // can be removed once the fix has been rolled out.\r\n var error$$1 = \r\n // tslint:disable-next-line:no-any msgData.error is not typed.\r\n msgData.error || (msgData[0] && msgData[0].error);\r\n if (error$$1) {\r\n debug(LOG_TAG, 'WebChannel received error:', error$$1);\r\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\r\n var status_2 = error$$1.status;\r\n var code = mapCodeFromRpcStatus(status_2);\r\n var message = error$$1.message;\r\n if (code === undefined) {\r\n code = Code.INTERNAL;\r\n message =\r\n 'Unknown error status: ' +\r\n status_2 +\r\n ' with message ' +\r\n error$$1.message;\r\n }\r\n // Mark closed so no further events are propagated\r\n closed = true;\r\n streamBridge.callOnClose(new FirestoreError(code, message));\r\n channel.close();\r\n }\r\n else {\r\n debug(LOG_TAG, 'WebChannel received:', msgData);\r\n streamBridge.callOnMessage(msgData);\r\n }\r\n }\r\n });\r\n setTimeout(function () {\r\n // Technically we could/should wait for the WebChannel opened event,\r\n // but because we want to send the first message with the WebChannel\r\n // handshake we pretend the channel opened here (asynchronously), and\r\n // then delay the actual open until the first message is sent.\r\n streamBridge.callOnOpen();\r\n }, 0);\r\n return streamBridge;\r\n };\r\n // visible for testing\r\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\r\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\r\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\r\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\r\n url.push('/projects/');\r\n url.push(this.databaseId.projectId);\r\n url.push('/databases/');\r\n url.push(this.databaseId.database);\r\n url.push('/documents');\r\n url.push(':');\r\n url.push(urlRpcName);\r\n return url.join('');\r\n };\r\n return WebChannelConnection;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar BrowserPlatform = /** @class */ (function () {\r\n function BrowserPlatform() {\r\n this.emptyByteString = '';\r\n this.base64Available = typeof atob !== 'undefined';\r\n }\r\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\r\n return Promise.resolve(new WebChannelConnection(databaseInfo));\r\n };\r\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\r\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\r\n };\r\n BrowserPlatform.prototype.formatJSON = function (value) {\r\n return JSON.stringify(value);\r\n };\r\n BrowserPlatform.prototype.atob = function (encoded) {\r\n return atob(encoded);\r\n };\r\n BrowserPlatform.prototype.btoa = function (raw) {\r\n return btoa(raw);\r\n };\r\n return BrowserPlatform;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * This code needs to run before Firestore is used. This can be achieved in\r\n * several ways:\r\n * 1) Through the JSCompiler compiling this code and then (automatically)\r\n * executing it before exporting the Firestore symbols.\r\n * 2) Through importing this module first in a Firestore main module\r\n */\r\nPlatformSupport.setPlatform(new BrowserPlatform());\n\n/**\r\n * Copyright 2017 Google Inc.\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// The objects that are a part of this API are exposed to third-parties as\r\n// compiled javascript so we want to flag our private members with a leading\r\n// underscore to discourage their use.\r\n// tslint:disable:strip-private-property-underscore\r\n/**\r\n * A FieldPath refers to a field in a document. The path may consist of a single\r\n * field name (referring to a top-level field in the document), or a list of\r\n * field names (referring to a nested field in the document).\r\n */\r\nvar FieldPath$1 = /** @class */ (function () {\r\n /**\r\n * Creates a FieldPath from the provided field names. If more than one field\r\n * name is provided, the path will point to a nested field in a document.\r\n *\r\n * @param fieldNames A list of field names.\r\n */\r\n function FieldPath$$1() {\r\n var fieldNames = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n fieldNames[_i] = arguments[_i];\r\n }\r\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\r\n for (var i = 0; i < fieldNames.length; ++i) {\r\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\r\n if (fieldNames[i].length === 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\r\n 'Field names must not be empty.');\r\n }\r\n }\r\n this._internalPath = new FieldPath(fieldNames);\r\n }\r\n FieldPath$$1.documentId = function () {\r\n return FieldPath$$1._DOCUMENT_ID;\r\n };\r\n FieldPath$$1.prototype.isEqual = function (other) {\r\n if (!(other instanceof FieldPath$$1)) {\r\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\r\n }\r\n return this._internalPath.isEqual(other._internalPath);\r\n };\r\n /**\r\n * Internal Note: The backend doesn't technically support querying by\r\n * document ID. Instead it queries by the entire document name (full path\r\n * included), but in the cases we currently support documentId(), the net\r\n * effect is the same.\r\n */\r\n FieldPath$$1._DOCUMENT_ID = new FieldPath$$1(FieldPath.keyField().canonicalString());\r\n return FieldPath$$1;\r\n}());\r\n/**\r\n * Matches any characters in a field path string that are reserved.\r\n */\r\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\r\n/**\r\n * Parses a field path string into a FieldPath, treating dots as separators.\r\n */\r\nfunction fromDotSeparatedString(path) {\r\n var found = path.search(RESERVED);\r\n if (found >= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\r\n \"'~', '*', '/', '[', or ']'\");\r\n }\r\n try {\r\n return new (FieldPath$1.bind.apply(FieldPath$1, [void 0].concat(path.split('.'))))();\r\n }\r\n catch (e) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\r\n \"begin with '.', end with '.', or contain '..'\");\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Describes the online state of the Firestore client. Note that this does not\r\n * indicate whether or not the remote store is trying to connect or not. This is\r\n * primarily used by the View / EventManager code to change their behavior while\r\n * offline (e.g. get() calls shouldn't wait for data from the server and\r\n * snapshot events should set metadata.isFromCache=true).\r\n */\r\nvar OnlineState;\r\n(function (OnlineState) {\r\n /**\r\n * The Firestore client is in an unknown online state. This means the client\r\n * is either not actively trying to establish a connection or it is currently\r\n * trying to establish a connection, but it has not succeeded or failed yet.\r\n * Higher-level components should not operate in offline mode.\r\n */\r\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\r\n /**\r\n * The client is connected and the connections are healthy. This state is\r\n * reached after a successful connection and there has been at least one\r\n * successful message received from the backends.\r\n */\r\n OnlineState[OnlineState[\"Online\"] = 1] = \"Online\";\r\n /**\r\n * The client is either trying to establish a connection but failing, or it\r\n * has been explicitly marked offline via a call to disableNetwork().\r\n * Higher-level components should operate in offline mode.\r\n */\r\n OnlineState[OnlineState[\"Offline\"] = 2] = \"Offline\";\r\n})(OnlineState || (OnlineState = {}));\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar ChangeType;\r\n(function (ChangeType) {\r\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\r\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\r\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\r\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\r\n})(ChangeType || (ChangeType = {}));\r\nvar SyncState;\r\n(function (SyncState) {\r\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\r\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\r\n})(SyncState || (SyncState = {}));\r\n/**\r\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\r\n * duplicate events for the same doc.\r\n */\r\nvar DocumentChangeSet = /** @class */ (function () {\r\n function DocumentChangeSet() {\r\n this.changeMap = new SortedMap(DocumentKey.comparator);\r\n }\r\n DocumentChangeSet.prototype.track = function (change) {\r\n var key = change.doc.key;\r\n var oldChange = this.changeMap.get(key);\r\n if (!oldChange) {\r\n this.changeMap = this.changeMap.insert(key, change);\r\n return;\r\n }\r\n // Merge the new change with the existing change.\r\n if (change.type !== ChangeType.Added &&\r\n oldChange.type === ChangeType.Metadata) {\r\n this.changeMap = this.changeMap.insert(key, change);\r\n }\r\n else if (change.type === ChangeType.Metadata &&\r\n oldChange.type !== ChangeType.Removed) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: oldChange.type,\r\n doc: change.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Modified &&\r\n oldChange.type === ChangeType.Modified) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Modified,\r\n doc: change.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Modified &&\r\n oldChange.type === ChangeType.Added) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Added,\r\n doc: change.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Removed &&\r\n oldChange.type === ChangeType.Added) {\r\n this.changeMap = this.changeMap.remove(key);\r\n }\r\n else if (change.type === ChangeType.Removed &&\r\n oldChange.type === ChangeType.Modified) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Removed,\r\n doc: oldChange.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Added &&\r\n oldChange.type === ChangeType.Removed) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Modified,\r\n doc: change.doc\r\n });\r\n }\r\n else {\r\n // This includes these cases, which don't make sense:\r\n // Added->Added\r\n // Removed->Removed\r\n // Modified->Added\r\n // Removed->Modified\r\n // Metadata->Added\r\n // Removed->Metadata\r\n fail('unsupported combination of changes: ' +\r\n JSON.stringify(change) +\r\n ' after ' +\r\n JSON.stringify(oldChange));\r\n }\r\n };\r\n DocumentChangeSet.prototype.getChanges = function () {\r\n var changes = [];\r\n this.changeMap.inorderTraversal(function (key, change) {\r\n changes.push(change);\r\n });\r\n return changes;\r\n };\r\n return DocumentChangeSet;\r\n}());\r\nvar ViewSnapshot = /** @class */ (function () {\r\n function ViewSnapshot(query, docs, oldDocs, docChanges, fromCache, hasPendingWrites, syncStateChanged) {\r\n this.query = query;\r\n this.docs = docs;\r\n this.oldDocs = oldDocs;\r\n this.docChanges = docChanges;\r\n this.fromCache = fromCache;\r\n this.hasPendingWrites = hasPendingWrites;\r\n this.syncStateChanged = syncStateChanged;\r\n }\r\n ViewSnapshot.prototype.isEqual = function (other) {\r\n if (this.fromCache !== other.fromCache ||\r\n this.hasPendingWrites !== other.hasPendingWrites ||\r\n this.syncStateChanged !== other.syncStateChanged ||\r\n !this.query.isEqual(other.query) ||\r\n !this.docs.isEqual(other.docs) ||\r\n !this.oldDocs.isEqual(other.oldDocs)) {\r\n return false;\r\n }\r\n var changes = this.docChanges;\r\n var otherChanges = other.docChanges;\r\n if (changes.length !== otherChanges.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < changes.length; i++) {\r\n if (changes[i].type !== otherChanges[i].type ||\r\n !changes[i].doc.isEqual(otherChanges[i].doc)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n return ViewSnapshot;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * DocumentSet is an immutable (copy-on-write) collection that holds documents\r\n * in order specified by the provided comparator. We always add a document key\r\n * comparator on top of what is provided to guarantee document equality based on\r\n * the key.\r\n */\r\nvar DocumentSet = /** @class */ (function () {\r\n /** The default ordering is by key if the comparator is omitted */\r\n function DocumentSet(comp) {\r\n // We are adding document key comparator to the end as it's the only\r\n // guaranteed unique property of a document.\r\n if (comp) {\r\n this.comparator = function (d1, d2) {\r\n return comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n }\r\n else {\r\n this.comparator = function (d1, d2) {\r\n return DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n }\r\n this.keyedMap = documentMap();\r\n this.sortedSet = new SortedMap(this.comparator);\r\n }\r\n /**\r\n * Returns an empty copy of the existing DocumentSet, using the same\r\n * comparator.\r\n */\r\n DocumentSet.emptySet = function (oldSet) {\r\n return new DocumentSet(oldSet.comparator);\r\n };\r\n DocumentSet.prototype.has = function (key) {\r\n return this.keyedMap.get(key) != null;\r\n };\r\n DocumentSet.prototype.get = function (key) {\r\n return this.keyedMap.get(key);\r\n };\r\n DocumentSet.prototype.first = function () {\r\n return this.sortedSet.minKey();\r\n };\r\n DocumentSet.prototype.last = function () {\r\n return this.sortedSet.maxKey();\r\n };\r\n DocumentSet.prototype.isEmpty = function () {\r\n return this.sortedSet.isEmpty();\r\n };\r\n /**\r\n * Returns the index of the provided key in the document set, or -1 if the\r\n * document key is not present in the set;\r\n */\r\n DocumentSet.prototype.indexOf = function (key) {\r\n var doc = this.keyedMap.get(key);\r\n return doc ? this.sortedSet.indexOf(doc) : -1;\r\n };\r\n Object.defineProperty(DocumentSet.prototype, \"size\", {\r\n get: function () {\r\n return this.sortedSet.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** Iterates documents in order defined by \"comparator\" */\r\n DocumentSet.prototype.forEach = function (cb) {\r\n this.sortedSet.inorderTraversal(function (k, v) {\r\n cb(k);\r\n return false;\r\n });\r\n };\r\n /** Inserts or updates a document with the same key */\r\n DocumentSet.prototype.add = function (doc) {\r\n // First remove the element if we have it.\r\n var set = this.delete(doc.key);\r\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\r\n };\r\n /** Deletes a document with a given key */\r\n DocumentSet.prototype.delete = function (key) {\r\n var doc = this.get(key);\r\n if (!doc) {\r\n return this;\r\n }\r\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\r\n };\r\n DocumentSet.prototype.isEqual = function (other) {\r\n if (!(other instanceof DocumentSet))\r\n return false;\r\n if (this.size !== other.size)\r\n return false;\r\n var thisIt = this.sortedSet.getIterator();\r\n var otherIt = other.sortedSet.getIterator();\r\n while (thisIt.hasNext()) {\r\n var thisDoc = thisIt.getNext().key;\r\n var otherDoc = otherIt.getNext().key;\r\n if (!thisDoc.isEqual(otherDoc))\r\n return false;\r\n }\r\n return true;\r\n };\r\n DocumentSet.prototype.toString = function () {\r\n var docStrings = [];\r\n this.forEach(function (doc) {\r\n docStrings.push(doc.toString());\r\n });\r\n if (docStrings.length === 0) {\r\n return 'DocumentSet ()';\r\n }\r\n else {\r\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\r\n }\r\n };\r\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\r\n var newSet = new DocumentSet();\r\n newSet.comparator = this.comparator;\r\n newSet.keyedMap = keyedMap;\r\n newSet.sortedSet = sortedSet;\r\n return newSet;\r\n };\r\n return DocumentSet;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A map implementation that uses objects as keys. Objects must implement the\r\n * Equatable interface and must be immutable. Entries in the map are stored\r\n * together with the key being produced from the mapKeyFn. This map\r\n * automatically handles collisions of keys.\r\n */\r\nvar ObjectMap = /** @class */ (function () {\r\n function ObjectMap(mapKeyFn) {\r\n this.mapKeyFn = mapKeyFn;\r\n /**\r\n * The inner map for a key -> value pair. Due to the possibility of\r\n * collisions we keep a list of entries that we do a linear search through\r\n * to find an actual match. Note that collisions should be rare, so we still\r\n * expect near constant time lookups in practice.\r\n */\r\n this.inner = {};\r\n }\r\n /** Get a value for this key, or undefined if it does not exist. */\r\n ObjectMap.prototype.get = function (key) {\r\n var id = this.mapKeyFn(key);\r\n var matches = this.inner[id];\r\n if (matches === undefined) {\r\n return undefined;\r\n }\r\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\r\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\r\n if (otherKey.isEqual(key)) {\r\n return value;\r\n }\r\n }\r\n return undefined;\r\n };\r\n ObjectMap.prototype.has = function (key) {\r\n return this.get(key) !== undefined;\r\n };\r\n /** Put this key and value in the map. */\r\n ObjectMap.prototype.set = function (key, value) {\r\n var id = this.mapKeyFn(key);\r\n var matches = this.inner[id];\r\n if (matches === undefined) {\r\n this.inner[id] = [[key, value]];\r\n return;\r\n }\r\n for (var i = 0; i < matches.length; i++) {\r\n if (matches[i][0].isEqual(key)) {\r\n matches[i] = [key, value];\r\n return;\r\n }\r\n }\r\n matches.push([key, value]);\r\n };\r\n /**\r\n * Remove this key from the map. Returns a boolean if anything was deleted.\r\n */\r\n ObjectMap.prototype.delete = function (key) {\r\n var id = this.mapKeyFn(key);\r\n var matches = this.inner[id];\r\n if (matches === undefined) {\r\n return false;\r\n }\r\n for (var i = 0; i < matches.length; i++) {\r\n if (matches[i][0].isEqual(key)) {\r\n if (matches.length === 1) {\r\n delete this.inner[id];\r\n }\r\n else {\r\n matches.splice(i, 1);\r\n }\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n ObjectMap.prototype.forEach = function (fn) {\r\n forEach(this.inner, function (_, entries) {\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var _a = entries_1[_i], k = _a[0], v = _a[1];\r\n fn(k, v);\r\n }\r\n });\r\n };\r\n ObjectMap.prototype.isEmpty = function () {\r\n return isEmpty(this.inner);\r\n };\r\n return ObjectMap;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Holds the listeners and the last received ViewSnapshot for a query being\r\n * tracked by EventManager.\r\n */\r\nvar QueryListenersInfo = /** @class */ (function () {\r\n function QueryListenersInfo() {\r\n this.listeners = [];\r\n }\r\n return QueryListenersInfo;\r\n}());\r\n/**\r\n * EventManager is responsible for mapping queries to query event emitters.\r\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\r\n * backend.\r\n */\r\nvar EventManager = /** @class */ (function () {\r\n function EventManager(syncEngine) {\r\n this.syncEngine = syncEngine;\r\n this.queries = new ObjectMap(function (q) {\r\n return q.canonicalId();\r\n });\r\n this.onlineState = OnlineState.Unknown;\r\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\r\n }\r\n EventManager.prototype.listen = function (listener) {\r\n var query = listener.query;\r\n var firstListen = false;\r\n var queryInfo = this.queries.get(query);\r\n if (!queryInfo) {\r\n firstListen = true;\r\n queryInfo = new QueryListenersInfo();\r\n this.queries.set(query, queryInfo);\r\n }\r\n queryInfo.listeners.push(listener);\r\n listener.applyOnlineStateChange(this.onlineState);\r\n if (queryInfo.viewSnap)\r\n listener.onViewSnapshot(queryInfo.viewSnap);\r\n if (firstListen) {\r\n return this.syncEngine.listen(query).then(function (targetId) {\r\n queryInfo.targetId = targetId;\r\n return targetId;\r\n });\r\n }\r\n else {\r\n return Promise.resolve(queryInfo.targetId);\r\n }\r\n };\r\n EventManager.prototype.unlisten = function (listener) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var query, lastListen, queryInfo, i;\r\n return __generator(this, function (_a) {\r\n query = listener.query;\r\n lastListen = false;\r\n queryInfo = this.queries.get(query);\r\n if (queryInfo) {\r\n i = queryInfo.listeners.indexOf(listener);\r\n if (i >= 0) {\r\n queryInfo.listeners.splice(i, 1);\r\n lastListen = queryInfo.listeners.length === 0;\r\n }\r\n }\r\n if (lastListen) {\r\n this.queries.delete(query);\r\n return [2 /*return*/, this.syncEngine.unlisten(query)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n EventManager.prototype.onChange = function (viewSnaps) {\r\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\r\n var viewSnap = viewSnaps_1[_i];\r\n var query = viewSnap.query;\r\n var queryInfo = this.queries.get(query);\r\n if (queryInfo) {\r\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\r\n var listener = _b[_a];\r\n listener.onViewSnapshot(viewSnap);\r\n }\r\n queryInfo.viewSnap = viewSnap;\r\n }\r\n }\r\n };\r\n EventManager.prototype.onError = function (query, error) {\r\n var queryInfo = this.queries.get(query);\r\n if (queryInfo) {\r\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\r\n var listener = _a[_i];\r\n listener.onError(error);\r\n }\r\n }\r\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\r\n // after an error.\r\n this.queries.delete(query);\r\n };\r\n EventManager.prototype.applyOnlineStateChange = function (onlineState) {\r\n this.onlineState = onlineState;\r\n this.queries.forEach(function (_, queryInfo) {\r\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\r\n var listener = _a[_i];\r\n listener.applyOnlineStateChange(onlineState);\r\n }\r\n });\r\n };\r\n return EventManager;\r\n}());\r\n/**\r\n * QueryListener takes a series of internal view snapshots and determines\r\n * when to raise the event.\r\n *\r\n * It uses an Observer to dispatch events.\r\n */\r\nvar QueryListener = /** @class */ (function () {\r\n function QueryListener(query, queryObserver, options) {\r\n this.query = query;\r\n this.queryObserver = queryObserver;\r\n /**\r\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\r\n * observer. This flag is set to true once we've actually raised an event.\r\n */\r\n this.raisedInitialEvent = false;\r\n this.onlineState = OnlineState.Unknown;\r\n this.options = options || {};\r\n }\r\n QueryListener.prototype.onViewSnapshot = function (snap) {\r\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\r\n if (!this.options.includeDocumentMetadataChanges) {\r\n // Remove the metadata only changes.\r\n var docChanges = [];\r\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\r\n var docChange = _a[_i];\r\n if (docChange.type !== ChangeType.Metadata) {\r\n docChanges.push(docChange);\r\n }\r\n }\r\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.fromCache, snap.hasPendingWrites, snap.syncStateChanged);\r\n }\r\n if (!this.raisedInitialEvent) {\r\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\r\n this.raiseInitialEvent(snap);\r\n }\r\n }\r\n else if (this.shouldRaiseEvent(snap)) {\r\n this.queryObserver.next(snap);\r\n }\r\n this.snap = snap;\r\n };\r\n QueryListener.prototype.onError = function (error) {\r\n this.queryObserver.error(error);\r\n };\r\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\r\n this.onlineState = onlineState;\r\n if (this.snap &&\r\n !this.raisedInitialEvent &&\r\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\r\n this.raiseInitialEvent(this.snap);\r\n }\r\n };\r\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\r\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\r\n // Always raise the first event when we're synced\r\n if (!snap.fromCache) {\r\n return true;\r\n }\r\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\r\n // or Online if we wait long enough).\r\n var maybeOnline = onlineState !== OnlineState.Offline;\r\n // Don't raise the event if we're online, aren't synced yet (checked\r\n // above) and are waiting for a sync.\r\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\r\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\r\n return false;\r\n }\r\n // Raise data from cache if we have any documents or we are offline\r\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\r\n };\r\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\r\n // We don't need to handle includeDocumentMetadataChanges here because\r\n // the Metadata only changes have already been stripped out if needed.\r\n // At this point the only changes we will see are the ones we should\r\n // propagate.\r\n if (snap.docChanges.length > 0) {\r\n return true;\r\n }\r\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\r\n if (snap.syncStateChanged || hasPendingWritesChanged) {\r\n return this.options.includeQueryMetadataChanges === true;\r\n }\r\n // Generally we should have hit one of the cases above, but it's possible\r\n // to get here if there were only metadata docChanges and they got\r\n // stripped out.\r\n return false;\r\n };\r\n QueryListener.prototype.raiseInitialEvent = function (snap) {\r\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\r\n snap = new ViewSnapshot(snap.query, snap.docs, DocumentSet.emptySet(snap.docs), QueryListener.getInitialViewChanges(snap), snap.fromCache, snap.hasPendingWrites, true);\r\n this.raisedInitialEvent = true;\r\n this.queryObserver.next(snap);\r\n };\r\n /** Returns changes as if all documents in the snap were added. */\r\n QueryListener.getInitialViewChanges = function (snap) {\r\n var result = [];\r\n snap.docs.forEach(function (doc) {\r\n result.push({ type: ChangeType.Added, doc: doc });\r\n });\r\n return result;\r\n };\r\n return QueryListener;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * PersistencePromise<> is essentially a re-implementation of Promise<> except\r\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\r\n * are executed synchronously when a PersistencePromise resolves rather than\r\n * asynchronously (Promise<> implementations use setImmediate() or similar).\r\n *\r\n * This is necessary to interoperate with IndexedDB which will automatically\r\n * commit transactions if control is returned to the event loop without\r\n * synchronously initiating another operation on the transaction.\r\n *\r\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\r\n * Promises.\r\n */\r\nvar PersistencePromise = /** @class */ (function () {\r\n function PersistencePromise(callback) {\r\n var _this = this;\r\n // NOTE: next/catchCallback will always point to our own wrapper functions,\r\n // not the user's raw next() or catch() callbacks.\r\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\r\n this.nextCallback = null;\r\n // tslint:disable-next-line:no-any Accept any result type for the error handler.\r\n this.catchCallback = null;\r\n // When the operation resolves, we'll set result or error and mark isDone.\r\n this.result = undefined;\r\n this.error = undefined;\r\n this.isDone = false;\r\n // Set to true when .then() or .catch() are called and prevents additional\r\n // chaining.\r\n this.callbackAttached = false;\r\n callback(function (value) {\r\n _this.isDone = true;\r\n _this.result = value;\r\n if (_this.nextCallback) {\r\n // value should be defined unless T is Void, but we can't express\r\n // that in the type system.\r\n _this.nextCallback(value);\r\n }\r\n }, function (error) {\r\n _this.isDone = true;\r\n _this.error = error;\r\n if (_this.catchCallback) {\r\n _this.catchCallback(error);\r\n }\r\n });\r\n }\r\n PersistencePromise.prototype.catch = function (fn) {\r\n return this.next(undefined, fn);\r\n };\r\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\r\n var _this = this;\r\n if (this.callbackAttached) {\r\n fail('Called next() or catch() twice for PersistencePromise');\r\n }\r\n this.callbackAttached = true;\r\n if (this.isDone) {\r\n if (!this.error) {\r\n return this.wrapSuccess(nextFn, this.result);\r\n }\r\n else {\r\n return this.wrapFailure(catchFn, this.error);\r\n }\r\n }\r\n else {\r\n return new PersistencePromise(function (resolve, reject) {\r\n _this.nextCallback = function (value) {\r\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\r\n };\r\n _this.catchCallback = function (error) {\r\n _this.wrapFailure(catchFn, error).next(resolve, reject);\r\n };\r\n });\r\n }\r\n };\r\n PersistencePromise.prototype.toPromise = function () {\r\n var _this = this;\r\n return new Promise(function (resolve, reject) {\r\n _this.next(resolve, reject);\r\n });\r\n };\r\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\r\n try {\r\n var result = fn();\r\n if (result instanceof PersistencePromise) {\r\n return result;\r\n }\r\n else {\r\n return PersistencePromise.resolve(result);\r\n }\r\n }\r\n catch (e) {\r\n return PersistencePromise.reject(e);\r\n }\r\n };\r\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\r\n if (nextFn) {\r\n return this.wrapUserFunction(function () { return nextFn(value); });\r\n }\r\n else {\r\n // If there's no nextFn, then R must be the same as T but we\r\n // can't express that in the type system.\r\n // tslint:disable-next-line:no-any\r\n return PersistencePromise.resolve(value);\r\n }\r\n };\r\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\r\n if (catchFn) {\r\n return this.wrapUserFunction(function () { return catchFn(error); });\r\n }\r\n else {\r\n return PersistencePromise.reject(error);\r\n }\r\n };\r\n PersistencePromise.resolve = function (result) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n resolve(result);\r\n });\r\n };\r\n PersistencePromise.reject = function (error) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n reject(error);\r\n });\r\n };\r\n PersistencePromise.waitFor = function (\r\n // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\r\n all) {\r\n return all.reduce(function (promise, nextPromise, idx) {\r\n return promise.next(function () {\r\n return nextPromise;\r\n });\r\n }, PersistencePromise.resolve());\r\n };\r\n PersistencePromise.map = function (all) {\r\n var results = [];\r\n var first = true;\r\n // initial is ignored, so we can cheat on the type.\r\n // tslint:disable-next-line:no-any\r\n var initial = PersistencePromise.resolve(null);\r\n return all\r\n .reduce(function (promise, nextPromise) {\r\n return promise.next(function (result) {\r\n if (!first) {\r\n results.push(result);\r\n }\r\n first = false;\r\n return nextPromise;\r\n });\r\n }, initial)\r\n .next(function (result) {\r\n results.push(result);\r\n return results;\r\n });\r\n };\r\n return PersistencePromise;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A garbage collector implementation that eagerly collects documents as soon as\r\n * they're no longer referenced in any of its registered GarbageSources.\r\n *\r\n * This implementation keeps track of a set of keys that are potentially garbage\r\n * without keeping an exact reference count. During collectGarbage, the\r\n * collector verifies that all potential garbage keys actually have no\r\n * references by consulting its list of garbage sources.\r\n */\r\nvar EagerGarbageCollector = /** @class */ (function () {\r\n function EagerGarbageCollector() {\r\n this.isEager = true;\r\n /**\r\n * The garbage collectible sources to double-check during garbage collection.\r\n */\r\n this.sources = [];\r\n /**\r\n * A set of potentially garbage keys.\r\n * PORTING NOTE: This would be a mutable set if Javascript had one.\r\n */\r\n this.potentialGarbage = documentKeySet();\r\n }\r\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\r\n this.sources.push(garbageSource);\r\n garbageSource.setGarbageCollector(this);\r\n };\r\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\r\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\r\n garbageSource.setGarbageCollector(null);\r\n };\r\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\r\n this.potentialGarbage = this.potentialGarbage.add(key);\r\n };\r\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\r\n var _this = this;\r\n var promises = [];\r\n var garbageKeys = documentKeySet();\r\n this.potentialGarbage.forEach(function (key) {\r\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\r\n promises.push(hasRefsPromise.next(function (hasRefs) {\r\n // If there are no references, get the key.\r\n if (!hasRefs) {\r\n garbageKeys = garbageKeys.add(key);\r\n }\r\n return PersistencePromise.resolve();\r\n }));\r\n });\r\n // Clear locally retained potential keys and returned confirmed garbage.\r\n this.potentialGarbage = documentKeySet();\r\n return PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\r\n };\r\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\r\n var initial = PersistencePromise.resolve(false);\r\n return this.sources\r\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\r\n .reduce(function (promise, nextPromise) {\r\n return promise.next(function (result) {\r\n if (result) {\r\n return PersistencePromise.resolve(true);\r\n }\r\n else {\r\n return nextPromise();\r\n }\r\n });\r\n }, initial);\r\n };\r\n return EagerGarbageCollector;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A set of changes to what documents are currently in view and out of view for\r\n * a given query. These changes are sent to the LocalStore by the View (via\r\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\r\n */\r\nvar LocalViewChanges = /** @class */ (function () {\r\n function LocalViewChanges(query, addedKeys, removedKeys) {\r\n this.query = query;\r\n this.addedKeys = addedKeys;\r\n this.removedKeys = removedKeys;\r\n }\r\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\r\n var addedKeys = documentKeySet();\r\n var removedKeys = documentKeySet();\r\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\r\n var docChange = _a[_i];\r\n switch (docChange.type) {\r\n case ChangeType.Added:\r\n addedKeys = addedKeys.add(docChange.doc.key);\r\n break;\r\n case ChangeType.Removed:\r\n removedKeys = removedKeys.add(docChange.doc.key);\r\n break;\r\n default:\r\n // do nothing\r\n }\r\n }\r\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\r\n };\r\n return LocalViewChanges;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A collection of references to a document from some kind of numbered entity\r\n * (either a target ID or batch ID). As references are added to or removed from\r\n * the set corresponding events are emitted to a registered garbage collector.\r\n *\r\n * Each reference is represented by a DocumentReference object. Each of them\r\n * contains enough information to uniquely identify the reference. They are all\r\n * stored primarily in a set sorted by key. A document is considered garbage if\r\n * there's no references in that set (this can be efficiently checked thanks to\r\n * sorting by key).\r\n *\r\n * ReferenceSet also keeps a secondary set that contains references sorted by\r\n * IDs. This one is used to efficiently implement removal of all references by\r\n * some target ID.\r\n */\r\nvar ReferenceSet = /** @class */ (function () {\r\n function ReferenceSet() {\r\n // A set of outstanding references to a document sorted by key.\r\n this.refsByKey = new SortedSet(DocReference.compareByKey);\r\n // A set of outstanding references to a document sorted by target id.\r\n this.refsByTarget = new SortedSet(DocReference.compareByTargetId);\r\n /** Keeps track of keys that have references */\r\n this.garbageCollector = null;\r\n }\r\n /** Returns true if the reference set contains no references. */\r\n ReferenceSet.prototype.isEmpty = function () {\r\n return this.refsByKey.isEmpty();\r\n };\r\n /** Adds a reference to the given document key for the given ID. */\r\n ReferenceSet.prototype.addReference = function (key, id) {\r\n var ref = new DocReference(key, id);\r\n this.refsByKey = this.refsByKey.add(ref);\r\n this.refsByTarget = this.refsByTarget.add(ref);\r\n };\r\n /** Add references to the given document keys for the given ID. */\r\n ReferenceSet.prototype.addReferences = function (keys, id) {\r\n var _this = this;\r\n keys.forEach(function (key) { return _this.addReference(key, id); });\r\n };\r\n /**\r\n * Removes a reference to the given document key for the given\r\n * ID.\r\n */\r\n ReferenceSet.prototype.removeReference = function (key, id) {\r\n this.removeRef(new DocReference(key, id));\r\n };\r\n ReferenceSet.prototype.removeReferences = function (keys, id) {\r\n var _this = this;\r\n keys.forEach(function (key) { return _this.removeReference(key, id); });\r\n };\r\n /**\r\n * Clears all references with a given ID. Calls removeRef() for each key\r\n * removed.\r\n */\r\n ReferenceSet.prototype.removeReferencesForId = function (id) {\r\n var _this = this;\r\n var emptyKey = DocumentKey.EMPTY;\r\n var startRef = new DocReference(emptyKey, id);\r\n var endRef = new DocReference(emptyKey, id + 1);\r\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\r\n _this.removeRef(ref);\r\n });\r\n };\r\n ReferenceSet.prototype.removeAllReferences = function () {\r\n var _this = this;\r\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\r\n };\r\n ReferenceSet.prototype.removeRef = function (ref) {\r\n this.refsByKey = this.refsByKey.delete(ref);\r\n this.refsByTarget = this.refsByTarget.delete(ref);\r\n if (this.garbageCollector !== null) {\r\n this.garbageCollector.addPotentialGarbageKey(ref.key);\r\n }\r\n };\r\n ReferenceSet.prototype.referencesForId = function (id) {\r\n var emptyKey = DocumentKey.EMPTY;\r\n var startRef = new DocReference(emptyKey, id);\r\n var endRef = new DocReference(emptyKey, id + 1);\r\n var keys = documentKeySet();\r\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\r\n keys = keys.add(ref.key);\r\n });\r\n return keys;\r\n };\r\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\r\n this.garbageCollector = garbageCollector;\r\n };\r\n ReferenceSet.prototype.containsKey = function (txn, key) {\r\n var ref = new DocReference(key, 0);\r\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\r\n return PersistencePromise.resolve(firstRef !== null && key.isEqual(firstRef.key));\r\n };\r\n return ReferenceSet;\r\n}());\r\nvar DocReference = /** @class */ (function () {\r\n function DocReference(key, targetOrBatchId) {\r\n this.key = key;\r\n this.targetOrBatchId = targetOrBatchId;\r\n }\r\n /** Compare by key then by ID */\r\n DocReference.compareByKey = function (left, right) {\r\n return (DocumentKey.comparator(left.key, right.key) ||\r\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\r\n };\r\n /** Compare by ID then by key */\r\n DocReference.compareByTargetId = function (left, right) {\r\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\r\n DocumentKey.comparator(left.key, right.key));\r\n };\r\n return DocReference;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar RESERVED_BITS = 1;\r\nvar GeneratorIds;\r\n(function (GeneratorIds) {\r\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\r\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\r\n})(GeneratorIds || (GeneratorIds = {}));\r\n/**\r\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\r\n * separate generators for different scopes. While these generators will operate\r\n * independently of each other, they are scoped, such that no two generators\r\n * will ever produce the same ID. This is useful, because sometimes the backend\r\n * may group IDs from separate parts of the client into the same ID space.\r\n */\r\nvar TargetIdGenerator = /** @class */ (function () {\r\n function TargetIdGenerator(generatorId, initAfter) {\r\n if (initAfter === void 0) { initAfter = 0; }\r\n this.generatorId = generatorId;\r\n // Replace the generator part of initAfter with this generator's ID.\r\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\r\n var afterGenerator = initAfter - afterWithoutGenerator;\r\n if (afterGenerator >= generatorId) {\r\n // For example, if:\r\n // this.generatorId = 0b0000\r\n // after = 0b1011\r\n // afterGenerator = 0b0001\r\n // Then:\r\n // previous = 0b1010\r\n // next = 0b1100\r\n this.previousId = afterWithoutGenerator | this.generatorId;\r\n }\r\n else {\r\n // For example, if:\r\n // this.generatorId = 0b0001\r\n // after = 0b1010\r\n // afterGenerator = 0b0000\r\n // Then:\r\n // previous = 0b1001\r\n // next = 0b1011\r\n this.previousId =\r\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\r\n }\r\n }\r\n TargetIdGenerator.prototype.next = function () {\r\n this.previousId += 1 << RESERVED_BITS;\r\n return this.previousId;\r\n };\r\n TargetIdGenerator.forLocalStore = function (initAfter) {\r\n if (initAfter === void 0) { initAfter = 0; }\r\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\r\n };\r\n TargetIdGenerator.forSyncEngine = function () {\r\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\r\n };\r\n return TargetIdGenerator;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar AddedLimboDocument = /** @class */ (function () {\r\n function AddedLimboDocument(key) {\r\n this.key = key;\r\n }\r\n return AddedLimboDocument;\r\n}());\r\nvar RemovedLimboDocument = /** @class */ (function () {\r\n function RemovedLimboDocument(key) {\r\n this.key = key;\r\n }\r\n return RemovedLimboDocument;\r\n}());\r\n/**\r\n * View is responsible for computing the final merged truth of what docs are in\r\n * a query. It gets notified of local and remote changes to docs, and applies\r\n * the query filters and limits to determine the most correct possible results.\r\n */\r\nvar View = /** @class */ (function () {\r\n function View(query, \r\n /** Documents included in the remote target */\r\n syncedDocuments) {\r\n this.query = query;\r\n this.syncedDocuments = syncedDocuments;\r\n this.syncState = null;\r\n /**\r\n * A flag whether the view is current with the backend. A view is considered\r\n * current after it has seen the current flag from the backend and did not\r\n * lose consistency within the watch stream (e.g. because of an existence\r\n * filter mismatch).\r\n */\r\n this.current = false;\r\n /** Documents in the view but not in the remote target */\r\n this.limboDocuments = documentKeySet();\r\n /** Document Keys that have local changes */\r\n this.mutatedKeys = documentKeySet();\r\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\r\n }\r\n /**\r\n * Iterates over a set of doc changes, applies the query limit, and computes\r\n * what the new results should be, what the changes were, and whether we may\r\n * need to go back to the local cache for more results. Does not make any\r\n * changes to the view.\r\n * @param docChanges The doc changes to apply to this view.\r\n * @param previousChanges If this is being called with a refill, then start\r\n * with this set of docs and changes instead of the current view.\r\n * @return a new set of docs, changes, and refill flag.\r\n */\r\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\r\n var _this = this;\r\n var changeSet = previousChanges\r\n ? previousChanges.changeSet\r\n : new DocumentChangeSet();\r\n var oldDocumentSet = previousChanges\r\n ? previousChanges.documentSet\r\n : this.documentSet;\r\n var newMutatedKeys = previousChanges\r\n ? previousChanges.mutatedKeys\r\n : this.mutatedKeys;\r\n var newDocumentSet = oldDocumentSet;\r\n var needsRefill = false;\r\n // Track the last doc in a (full) limit. This is necessary, because some\r\n // update (a delete, or an update moving a doc past the old limit) might\r\n // mean there is some other document in the local cache that either should\r\n // come (1) between the old last limit doc and the new last document, in the\r\n // case of updates, or (2) after the new last document, in the case of\r\n // deletes. So we keep this doc at the old limit to compare the updates to.\r\n //\r\n // Note that this should never get used in a refill (when previousChanges is\r\n // set), because there will only be adds -- no deletes or updates.\r\n var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\r\n ? oldDocumentSet.last()\r\n : null;\r\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\r\n var oldDoc = oldDocumentSet.get(key);\r\n var newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\r\n if (newDoc) {\r\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' +\r\n key +\r\n ' != ' +\r\n newDoc.key);\r\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\r\n }\r\n if (newDoc) {\r\n newDocumentSet = newDocumentSet.add(newDoc);\r\n if (newDoc.hasLocalMutations) {\r\n newMutatedKeys = newMutatedKeys.add(key);\r\n }\r\n else {\r\n newMutatedKeys = newMutatedKeys.delete(key);\r\n }\r\n }\r\n else {\r\n newDocumentSet = newDocumentSet.delete(key);\r\n newMutatedKeys = newMutatedKeys.delete(key);\r\n }\r\n // Calculate change\r\n if (oldDoc && newDoc) {\r\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\r\n if (!docsEqual ||\r\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\r\n // only report a change if document actually changed\r\n if (docsEqual) {\r\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\r\n }\r\n else {\r\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\r\n }\r\n if (lastDocInLimit &&\r\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\r\n // This doc moved from inside the limit to after the limit.\r\n // That means there may be some doc in the local cache that's\r\n // actually less than this one.\r\n needsRefill = true;\r\n }\r\n }\r\n }\r\n else if (!oldDoc && newDoc) {\r\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\r\n }\r\n else if (oldDoc && !newDoc) {\r\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\r\n if (lastDocInLimit) {\r\n // A doc was removed from a full limit query. We'll need to\r\n // requery from the local cache to see if we know about some other\r\n // doc that should be in the results.\r\n needsRefill = true;\r\n }\r\n }\r\n });\r\n if (this.query.hasLimit()) {\r\n // TODO(klimt): Make DocumentSet size be constant time.\r\n while (newDocumentSet.size > this.query.limit) {\r\n var oldDoc = newDocumentSet.last();\r\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\r\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\r\n }\r\n }\r\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\r\n return {\r\n documentSet: newDocumentSet,\r\n changeSet: changeSet,\r\n needsRefill: needsRefill,\r\n mutatedKeys: newMutatedKeys\r\n };\r\n };\r\n /**\r\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\r\n * and sync state from the given (optional) target change.\r\n * @param docChanges The set of changes to make to the view's docs.\r\n * @param targetChange A target change to apply for computing limbo docs and\r\n * sync state.\r\n * @return A new ViewChange with the given docs, changes, and sync state.\r\n */\r\n View.prototype.applyChanges = function (docChanges, targetChange) {\r\n var _this = this;\r\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\r\n var oldDocs = this.documentSet;\r\n this.documentSet = docChanges.documentSet;\r\n this.mutatedKeys = docChanges.mutatedKeys;\r\n // Sort changes based on type and query comparator\r\n var changes = docChanges.changeSet.getChanges();\r\n changes.sort(function (c1, c2) {\r\n return (compareChangeType(c1.type, c2.type) ||\r\n _this.query.docComparator(c1.doc, c2.doc));\r\n });\r\n this.applyTargetChange(targetChange);\r\n var limboChanges = this.updateLimboDocuments();\r\n var synced = this.limboDocuments.size === 0 && this.current;\r\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\r\n var syncStateChanged = newSyncState !== this.syncState;\r\n this.syncState = newSyncState;\r\n if (changes.length === 0 && !syncStateChanged) {\r\n // no changes\r\n return { limboChanges: limboChanges };\r\n }\r\n else {\r\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, newSyncState === SyncState.Local, !docChanges.mutatedKeys.isEmpty(), syncStateChanged);\r\n return {\r\n snapshot: snap,\r\n limboChanges: limboChanges\r\n };\r\n }\r\n };\r\n /**\r\n * Applies an OnlineState change to the view, potentially generating a\r\n * ViewChange if the view's syncState changes as a result.\r\n */\r\n View.prototype.applyOnlineStateChange = function (onlineState) {\r\n if (this.current && onlineState === OnlineState.Offline) {\r\n // If we're offline, set `current` to false and then call applyChanges()\r\n // to refresh our syncState and generate a ViewChange as appropriate. We\r\n // are guaranteed to get a new TargetChange that sets `current` back to\r\n // true once the client is back online.\r\n this.current = false;\r\n return this.applyChanges({\r\n documentSet: this.documentSet,\r\n changeSet: new DocumentChangeSet(),\r\n mutatedKeys: this.mutatedKeys,\r\n needsRefill: false\r\n });\r\n }\r\n else {\r\n // No effect, just return a no-op ViewChange.\r\n return { limboChanges: [] };\r\n }\r\n };\r\n /**\r\n * Returns whether the doc for the given key should be in limbo.\r\n */\r\n View.prototype.shouldBeInLimbo = function (key) {\r\n // If the remote end says it's part of this query, it's not in limbo.\r\n if (this.syncedDocuments.has(key)) {\r\n return false;\r\n }\r\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\r\n if (!this.documentSet.has(key)) {\r\n return false;\r\n }\r\n // If there are local changes to the doc, they might explain why the server\r\n // doesn't know that it's part of the query. So don't put it in limbo.\r\n // TODO(klimt): Ideally, we would only consider changes that might actually\r\n // affect this specific query.\r\n if (this.documentSet.get(key).hasLocalMutations) {\r\n return false;\r\n }\r\n // Everything else is in limbo.\r\n return true;\r\n };\r\n /**\r\n * Updates syncedDocuments, current, and limbo docs based on the given change.\r\n * Returns the list of changes to which docs are in limbo.\r\n */\r\n View.prototype.applyTargetChange = function (targetChange) {\r\n if (targetChange) {\r\n var targetMapping = targetChange.mapping;\r\n if (targetMapping instanceof ResetMapping) {\r\n this.syncedDocuments = targetMapping.documents;\r\n }\r\n else if (targetMapping instanceof UpdateMapping) {\r\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\r\n }\r\n switch (targetChange.currentStatusUpdate) {\r\n case CurrentStatusUpdate.MarkCurrent:\r\n this.current = true;\r\n break;\r\n case CurrentStatusUpdate.MarkNotCurrent:\r\n this.current = false;\r\n break;\r\n case CurrentStatusUpdate.None:\r\n break;\r\n default:\r\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\r\n }\r\n }\r\n };\r\n View.prototype.updateLimboDocuments = function () {\r\n var _this = this;\r\n // We can only determine limbo documents when we're in-sync with the server.\r\n if (!this.current) {\r\n return [];\r\n }\r\n // TODO(klimt): Do this incrementally so that it's not quadratic when\r\n // updating many documents.\r\n var oldLimboDocuments = this.limboDocuments;\r\n this.limboDocuments = documentKeySet();\r\n this.documentSet.forEach(function (doc) {\r\n if (_this.shouldBeInLimbo(doc.key)) {\r\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\r\n }\r\n });\r\n // Diff the new limbo docs with the old limbo docs.\r\n var changes = [];\r\n oldLimboDocuments.forEach(function (key) {\r\n if (!_this.limboDocuments.has(key)) {\r\n changes.push(new RemovedLimboDocument(key));\r\n }\r\n });\r\n this.limboDocuments.forEach(function (key) {\r\n if (!oldLimboDocuments.has(key)) {\r\n changes.push(new AddedLimboDocument(key));\r\n }\r\n });\r\n return changes;\r\n };\r\n return View;\r\n}());\r\nfunction compareChangeType(c1, c2) {\r\n var order = function (change) {\r\n switch (change) {\r\n case ChangeType.Added:\r\n return 1;\r\n case ChangeType.Modified:\r\n return 2;\r\n case ChangeType.Metadata:\r\n // A metadata change is converted to a modified change at the public\r\n // api layer. Since we sort by document key and then change type,\r\n // metadata and modified changes must be sorted equivalently.\r\n return 2;\r\n case ChangeType.Removed:\r\n return 0;\r\n default:\r\n return fail('Unknown ChangeType: ' + change);\r\n }\r\n };\r\n return order(c1) - order(c2);\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$1 = 'SyncEngine';\r\n/**\r\n * QueryView contains all of the data that SyncEngine needs to keep track of for\r\n * a particular query.\r\n */\r\nvar QueryView = /** @class */ (function () {\r\n function QueryView(\r\n /**\r\n * The query itself.\r\n */\r\n query, \r\n /**\r\n * The target number created by the client that is used in the watch\r\n * stream to identify this query.\r\n */\r\n targetId, \r\n /**\r\n * An identifier from the datastore backend that indicates the last state\r\n * of the results that was received. This can be used to indicate where\r\n * to continue receiving new doc changes for the query.\r\n */\r\n resumeToken, \r\n /**\r\n * The view is responsible for computing the final merged truth of what\r\n * docs are in the query. It gets notified of local and remote changes,\r\n * and applies the query filters and limits to determine the most correct\r\n * possible results.\r\n */\r\n view) {\r\n this.query = query;\r\n this.targetId = targetId;\r\n this.resumeToken = resumeToken;\r\n this.view = view;\r\n }\r\n return QueryView;\r\n}());\r\n/**\r\n * SyncEngine is the central controller in the client SDK architecture. It is\r\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\r\n * SyncEngine's responsibilities include:\r\n * 1. Coordinating client requests and remote events between the EventManager\r\n * and the local and remote data stores.\r\n * 2. Managing a View object for each query, providing the unified view between\r\n * the local and remote data stores.\r\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\r\n * queue that need sending to the backend.\r\n *\r\n * The SyncEngine’s methods should only ever be called by methods running in the\r\n * global async queue.\r\n */\r\nvar SyncEngine = /** @class */ (function () {\r\n function SyncEngine(localStore, remoteStore, currentUser) {\r\n this.localStore = localStore;\r\n this.remoteStore = remoteStore;\r\n this.currentUser = currentUser;\r\n this.viewHandler = null;\r\n this.errorHandler = null;\r\n this.queryViewsByQuery = new ObjectMap(function (q) {\r\n return q.canonicalId();\r\n });\r\n this.queryViewsByTarget = {};\r\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\r\n this.limboKeysByTarget = {};\r\n this.limboDocumentRefs = new ReferenceSet();\r\n this.limboCollector = new EagerGarbageCollector();\r\n /** Stores user completion handlers, indexed by User and BatchId. */\r\n this.mutationUserCallbacks = {};\r\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\r\n }\r\n /** Subscribes view and error handler. Can be called only once. */\r\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\r\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\r\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\r\n this.viewHandler = viewHandler;\r\n this.errorHandler = errorHandler;\r\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\r\n };\r\n /**\r\n * Initiates the new listen, resolves promise when listen enqueued to the\r\n * server. All the subsequent view snapshots or errors are sent to the\r\n * subscribed handlers. Returns the targetId of the query.\r\n */\r\n SyncEngine.prototype.listen = function (query) {\r\n var _this = this;\r\n this.assertSubscribed('listen()');\r\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\r\n return this.localStore.allocateQuery(query).then(function (queryData) {\r\n return _this.localStore\r\n .executeQuery(query)\r\n .then(function (docs) {\r\n return _this.localStore\r\n .remoteDocumentKeys(queryData.targetId)\r\n .then(function (remoteKeys) {\r\n var view = new View(query, remoteKeys);\r\n var viewDocChanges = view.computeDocChanges(docs);\r\n var viewChange = view.applyChanges(viewDocChanges);\r\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\r\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\r\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\r\n _this.queryViewsByQuery.set(query, data);\r\n _this.queryViewsByTarget[queryData.targetId] = data;\r\n _this.viewHandler([viewChange.snapshot]);\r\n _this.remoteStore.listen(queryData);\r\n });\r\n })\r\n .then(function () {\r\n return queryData.targetId;\r\n });\r\n });\r\n };\r\n /** Stops listening to the query. */\r\n SyncEngine.prototype.unlisten = function (query) {\r\n var _this = this;\r\n this.assertSubscribed('unlisten()');\r\n var queryView = this.queryViewsByQuery.get(query);\r\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\r\n return this.localStore.releaseQuery(query).then(function () {\r\n _this.remoteStore.unlisten(queryView.targetId);\r\n return _this.removeAndCleanupQuery(queryView).then(function () {\r\n return _this.localStore.collectGarbage();\r\n });\r\n });\r\n };\r\n /**\r\n * Initiates the write of local mutation batch which involves adding the\r\n * writes to the mutation queue, notifying the remote store about new\r\n * mutations and raising events for any changes this write caused.\r\n *\r\n * The promise returned by this call is resolved when the above steps\r\n * have completed, *not* when the write was acked by the backend. The\r\n * userCallback is resolved once the write was acked/rejected by the\r\n * backend (or failed locally for any other reason).\r\n */\r\n SyncEngine.prototype.write = function (batch, userCallback) {\r\n var _this = this;\r\n this.assertSubscribed('write()');\r\n return this.localStore\r\n .localWrite(batch)\r\n .then(function (result) {\r\n _this.addMutationCallback(result.batchId, userCallback);\r\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\r\n })\r\n .then(function () {\r\n return _this.remoteStore.fillWritePipeline();\r\n });\r\n };\r\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\r\n SyncEngine.prototype.wrapUpdateFunctionError = function (error$$1) {\r\n return error$$1;\r\n };\r\n /**\r\n * Takes an updateFunction in which a set of reads and writes can be performed\r\n * atomically. In the updateFunction, the client can read and write values\r\n * using the supplied transaction object. After the updateFunction, all\r\n * changes will be committed. If some other client has changed any of the data\r\n * referenced, then the updateFunction will be called again. If the\r\n * updateFunction still fails after the given number of retries, then the\r\n * transaction will be rejection.\r\n *\r\n * The transaction object passed to the updateFunction contains methods for\r\n * accessing documents and collections. Unlike other datastore access, data\r\n * accessed with the transaction will not reflect local changes that have not\r\n * been committed. For this reason, it is required that all reads are\r\n * performed before any writes. Transactions must be performed while online.\r\n *\r\n * The promise returned is resolved when the transaction is fully committed.\r\n */\r\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\r\n var _this = this;\r\n if (retries === void 0) { retries = 5; }\r\n assert(retries >= 0, 'Got negative number of retries for transaction.');\r\n var transaction = this.remoteStore.createTransaction();\r\n var wrappedUpdateFunction = function () {\r\n try {\r\n var userPromise = updateFunction(transaction);\r\n if (isNullOrUndefined(userPromise) ||\r\n !userPromise.catch ||\r\n !userPromise.then) {\r\n return Promise.reject(Error('Transaction callback must return a Promise'));\r\n }\r\n return userPromise.catch(function (e) {\r\n return Promise.reject(_this.wrapUpdateFunctionError(e));\r\n });\r\n }\r\n catch (e) {\r\n return Promise.reject(_this.wrapUpdateFunctionError(e));\r\n }\r\n };\r\n return wrappedUpdateFunction().then(function (result) {\r\n return transaction\r\n .commit()\r\n .then(function () {\r\n return result;\r\n })\r\n .catch(function (error$$1) {\r\n if (retries === 0) {\r\n return Promise.reject(error$$1);\r\n }\r\n // TODO(klimt): Put in a retry delay?\r\n return _this.runTransaction(updateFunction, retries - 1);\r\n });\r\n });\r\n };\r\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\r\n var _this = this;\r\n this.assertSubscribed('applyRemoteEvent()');\r\n // Make sure limbo documents are deleted if there were no results\r\n forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\r\n var limboKey = _this.limboKeysByTarget[targetId];\r\n if (limboKey &&\r\n targetChange.currentStatusUpdate ===\r\n CurrentStatusUpdate.MarkCurrent &&\r\n !remoteEvent.documentUpdates.get(limboKey)) {\r\n // When listening to a query the server responds with a snapshot\r\n // containing documents matching the query and a current marker\r\n // telling us we're now in sync. It's possible for these to arrive\r\n // as separate remote events or as a single remote event.\r\n // For a document query, there will be no documents sent in the\r\n // response if the document doesn't exist.\r\n //\r\n // If the snapshot arrives separately from the current marker,\r\n // we handle it normally and updateTrackedLimbos will resolve the\r\n // limbo status of the document, removing it from limboDocumentRefs.\r\n // This works because clients only initiate limbo resolution when\r\n // a target is current and because all current targets are\r\n // always at a consistent snapshot.\r\n //\r\n // However, if the document doesn't exist and the current marker\r\n // arrives, the document is not present in the snapshot and our\r\n // normal view handling would consider the document to remain in\r\n // limbo indefinitely because there are no updates to the document.\r\n // To avoid this, we specially handle this just this case here:\r\n // synthesizing a delete.\r\n //\r\n // TODO(dimond): Ideally we would have an explicit lookup query\r\n // instead resulting in an explicit delete message and we could\r\n // remove this special logic.\r\n remoteEvent.addDocumentUpdate(new NoDocument(limboKey, remoteEvent.snapshotVersion));\r\n }\r\n });\r\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\r\n });\r\n };\r\n /**\r\n * Applies an OnlineState change to the sync engine and notifies any views of\r\n * the change.\r\n */\r\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState) {\r\n var newViewSnapshots = [];\r\n this.queryViewsByQuery.forEach(function (query, queryView) {\r\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\r\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\r\n if (viewChange.snapshot) {\r\n newViewSnapshots.push(viewChange.snapshot);\r\n }\r\n });\r\n this.viewHandler(newViewSnapshots);\r\n };\r\n SyncEngine.prototype.rejectListen = function (targetId, err) {\r\n var _this = this;\r\n this.assertSubscribed('rejectListens()');\r\n var limboKey = this.limboKeysByTarget[targetId];\r\n if (limboKey) {\r\n // Since this query failed, we won't want to manually unlisten to it.\r\n // So go ahead and remove it from bookkeeping.\r\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\r\n delete this.limboKeysByTarget[targetId];\r\n // TODO(klimt): We really only should do the following on permission\r\n // denied errors, but we don't have the cause code here.\r\n // It's a limbo doc. Create a synthetic event saying it was deleted.\r\n // This is kind of a hack. Ideally, we would have a method in the local\r\n // store to purge a document. However, it would be tricky to keep all of\r\n // the local store's invariants with another method.\r\n var docMap = new SortedMap(DocumentKey.comparator);\r\n docMap = docMap.insert(limboKey, new NoDocument(limboKey, SnapshotVersion.forDeletedDoc()));\r\n var event_1 = new RemoteEvent(SnapshotVersion.MIN, {}, docMap);\r\n return this.applyRemoteEvent(event_1);\r\n }\r\n else {\r\n var queryView_1 = this.queryViewsByTarget[targetId];\r\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\r\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\r\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\r\n _this.errorHandler(queryView_1.query, err);\r\n });\r\n });\r\n }\r\n };\r\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\r\n var _this = this;\r\n this.assertSubscribed('applySuccessfulWrite()');\r\n // The local store may or may not be able to apply the write result and\r\n // raise events immediately (depending on whether the watcher is caught\r\n // up), so we raise user callbacks first so that they consistently happen\r\n // before listen events.\r\n this.processUserCallback(mutationBatchResult.batch.batchId, \r\n /*error=*/ null);\r\n return this.localStore\r\n .acknowledgeBatch(mutationBatchResult)\r\n .then(function (changes) {\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\r\n });\r\n };\r\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error$$1) {\r\n var _this = this;\r\n this.assertSubscribed('rejectFailedWrite()');\r\n // The local store may or may not be able to apply the write result and\r\n // raise events immediately (depending on whether the watcher is caught up),\r\n // so we raise user callbacks first so that they consistently happen before\r\n // listen events.\r\n this.processUserCallback(batchId, error$$1);\r\n return this.localStore.rejectBatch(batchId).then(function (changes) {\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\r\n });\r\n };\r\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\r\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\r\n if (!newCallbacks) {\r\n newCallbacks = new SortedMap(primitiveComparator);\r\n }\r\n newCallbacks = newCallbacks.insert(batchId, callback);\r\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\r\n };\r\n /**\r\n * Resolves or rejects the user callback for the given batch and then discards\r\n * it.\r\n */\r\n SyncEngine.prototype.processUserCallback = function (batchId, error$$1) {\r\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\r\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\r\n // okay for there to be no callback for this ID.\r\n if (newCallbacks) {\r\n var callback = newCallbacks.get(batchId);\r\n if (callback) {\r\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\r\n if (error$$1) {\r\n callback.reject(error$$1);\r\n }\r\n else {\r\n callback.resolve();\r\n }\r\n newCallbacks = newCallbacks.remove(batchId);\r\n }\r\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\r\n }\r\n };\r\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\r\n this.queryViewsByQuery.delete(queryView.query);\r\n delete this.queryViewsByTarget[queryView.targetId];\r\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\r\n return this.gcLimboDocuments();\r\n };\r\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\r\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\r\n var limboChange = limboChanges_1[_i];\r\n if (limboChange instanceof AddedLimboDocument) {\r\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\r\n this.trackLimboChange(limboChange);\r\n }\r\n else if (limboChange instanceof RemovedLimboDocument) {\r\n debug(LOG_TAG$1, 'Document no longer in limbo: ' + limboChange.key);\r\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\r\n }\r\n else {\r\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\r\n }\r\n }\r\n return this.gcLimboDocuments();\r\n };\r\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\r\n var key = limboChange.key;\r\n if (!this.limboTargetsByKey.get(key)) {\r\n debug(LOG_TAG$1, 'New document in limbo: ' + key);\r\n var limboTargetId = this.targetIdGenerator.next();\r\n var query = Query.atPath(key.path);\r\n this.limboKeysByTarget[limboTargetId] = key;\r\n this.remoteStore.listen(new QueryData(query, limboTargetId, QueryPurpose.Listen));\r\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\r\n }\r\n };\r\n SyncEngine.prototype.gcLimboDocuments = function () {\r\n var _this = this;\r\n // HACK: We can use a null transaction here, because we know that the\r\n // reference set is entirely within memory and doesn't need a store engine.\r\n return this.limboCollector\r\n .collectGarbage(null)\r\n .next(function (keys) {\r\n keys.forEach(function (key) {\r\n var limboTargetId = _this.limboTargetsByKey.get(key);\r\n if (limboTargetId === null) {\r\n // This target already got removed, because the query failed.\r\n return;\r\n }\r\n _this.remoteStore.unlisten(limboTargetId);\r\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\r\n delete _this.limboKeysByTarget[limboTargetId];\r\n });\r\n })\r\n .toPromise();\r\n };\r\n // Visible for testing\r\n SyncEngine.prototype.currentLimboDocs = function () {\r\n return this.limboTargetsByKey;\r\n };\r\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\r\n var _this = this;\r\n var newSnaps = [];\r\n var docChangesInAllViews = [];\r\n var queriesProcessed = [];\r\n this.queryViewsByQuery.forEach(function (_, queryView) {\r\n queriesProcessed.push(Promise.resolve()\r\n .then(function () {\r\n var viewDocChanges = queryView.view.computeDocChanges(changes);\r\n if (!viewDocChanges.needsRefill) {\r\n return viewDocChanges;\r\n }\r\n // The query has a limit and some docs were removed, so we need\r\n // to re-run the query against the local store to make sure we\r\n // didn't lose any good docs that had been past the limit.\r\n return _this.localStore.executeQuery(queryView.query).then(function (docs) {\r\n return queryView.view.computeDocChanges(docs, viewDocChanges);\r\n });\r\n })\r\n .then(function (viewDocChanges) {\r\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\r\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\r\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\r\n if (viewChange.snapshot) {\r\n newSnaps.push(viewChange.snapshot);\r\n var docChanges = LocalViewChanges.fromSnapshot(viewChange.snapshot);\r\n docChangesInAllViews.push(docChanges);\r\n }\r\n });\r\n }));\r\n });\r\n return Promise.all(queriesProcessed)\r\n .then(function () {\r\n _this.viewHandler(newSnaps);\r\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\r\n })\r\n .then(function () {\r\n return _this.localStore.collectGarbage();\r\n });\r\n };\r\n SyncEngine.prototype.assertSubscribed = function (fnName) {\r\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\r\n };\r\n SyncEngine.prototype.handleUserChange = function (user) {\r\n var _this = this;\r\n this.currentUser = user;\r\n return this.localStore\r\n .handleUserChange(user)\r\n .then(function (changes) {\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\r\n })\r\n .then(function () {\r\n return _this.remoteStore.handleUserChange(user);\r\n });\r\n };\r\n return SyncEngine;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar BATCHID_UNKNOWN = -1;\r\n/**\r\n * A batch of mutations that will be sent as one unit to the backend.\r\n */\r\nvar MutationBatch = /** @class */ (function () {\r\n function MutationBatch(batchId, localWriteTime, mutations) {\r\n this.batchId = batchId;\r\n this.localWriteTime = localWriteTime;\r\n this.mutations = mutations;\r\n }\r\n /**\r\n * Applies all the mutations in this MutationBatch to the specified document\r\n * to create a new remote document\r\n *\r\n * @param docKey The key of the document to apply mutations to.\r\n * @param maybeDoc The document to apply mutations to.\r\n * @param batchResult The result of applying the MutationBatch to the\r\n * backend.\r\n */\r\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\r\n if (maybeDoc) {\r\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\r\n }\r\n var mutationResults = batchResult.mutationResults;\r\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\r\n for (var i = 0; i < this.mutations.length; i++) {\r\n var mutation = this.mutations[i];\r\n if (mutation.key.isEqual(docKey)) {\r\n var mutationResult = mutationResults[i];\r\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\r\n }\r\n }\r\n return maybeDoc;\r\n };\r\n /**\r\n * Computes the local view of a document given all the mutations in this\r\n * batch.\r\n *\r\n * @param docKey The key of the document to apply mutations to.\r\n * @param maybeDoc The document to apply mutations to.\r\n */\r\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\r\n if (maybeDoc) {\r\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\r\n }\r\n var baseDoc = maybeDoc;\r\n for (var i = 0; i < this.mutations.length; i++) {\r\n var mutation = this.mutations[i];\r\n if (mutation.key.isEqual(docKey)) {\r\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\r\n }\r\n }\r\n return maybeDoc;\r\n };\r\n MutationBatch.prototype.keys = function () {\r\n var keySet = documentKeySet();\r\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\r\n var mutation = _a[_i];\r\n keySet = keySet.add(mutation.key);\r\n }\r\n return keySet;\r\n };\r\n MutationBatch.prototype.isEqual = function (other) {\r\n return (this.batchId === other.batchId &&\r\n arrayEquals(this.mutations, other.mutations));\r\n };\r\n /**\r\n * Returns true if this mutation batch has already been removed from the\r\n * mutation queue.\r\n *\r\n * Note that not all implementations of the MutationQueue necessarily use\r\n * tombstones as part of their implementation and generally speaking no code\r\n * outside the mutation queues should really care about this.\r\n */\r\n MutationBatch.prototype.isTombstone = function () {\r\n return this.mutations.length === 0;\r\n };\r\n /** Converts this batch into a tombstone */\r\n MutationBatch.prototype.toTombstone = function () {\r\n return new MutationBatch(this.batchId, this.localWriteTime, []);\r\n };\r\n return MutationBatch;\r\n}());\r\n/** The result of applying a mutation batch to the backend. */\r\nvar MutationBatchResult = /** @class */ (function () {\r\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \r\n /**\r\n * A pre-computed mapping from each mutated document to the resulting\r\n * version.\r\n */\r\n docVersions) {\r\n this.batch = batch;\r\n this.commitVersion = commitVersion;\r\n this.mutationResults = mutationResults;\r\n this.streamToken = streamToken;\r\n this.docVersions = docVersions;\r\n }\r\n /**\r\n * Creates a new MutationBatchResult for the given batch and results. There\r\n * must be one result for each mutation in the batch. This static factory\r\n * caches a document=>version mapping (docVersions).\r\n */\r\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\r\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\r\n batch.mutations.length +\r\n ' must equal results received ' +\r\n results.length);\r\n var versionMap = documentVersionMap();\r\n var mutations = batch.mutations;\r\n for (var i = 0; i < mutations.length; i++) {\r\n var version = results[i].version;\r\n if (version === null) {\r\n // deletes don't have a version, so we substitute the commitVersion\r\n // of the entire batch.\r\n version = commitVersion;\r\n }\r\n versionMap = versionMap.insert(mutations[i].key, version);\r\n }\r\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\r\n };\r\n return MutationBatchResult;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar escapeChar = '\\u0001';\r\nvar encodedSeparatorChar = '\\u0001';\r\nvar encodedNul = '\\u0010';\r\nvar encodedEscape = '\\u0011';\r\n/**\r\n * Encodes a resource path into a IndexedDb-compatible string form.\r\n */\r\nfunction encode(path) {\r\n var result = '';\r\n for (var i = 0; i < path.length; i++) {\r\n if (result.length > 0) {\r\n result = encodeSeparator(result);\r\n }\r\n result = encodeSegment(path.get(i), result);\r\n }\r\n return encodeSeparator(result);\r\n}\r\n/** Encodes a single segment of a resource path into the given result */\r\nfunction encodeSegment(segment, resultBuf) {\r\n var result = resultBuf;\r\n var length = segment.length;\r\n for (var i = 0; i < length; i++) {\r\n var c = segment.charAt(i);\r\n switch (c) {\r\n case '\\0':\r\n result += escapeChar + encodedNul;\r\n break;\r\n case escapeChar:\r\n result += escapeChar + encodedEscape;\r\n break;\r\n default:\r\n result += c;\r\n }\r\n }\r\n return result;\r\n}\r\n/** Encodes a path separator into the given result */\r\nfunction encodeSeparator(result) {\r\n return result + escapeChar + encodedSeparatorChar;\r\n}\r\n/**\r\n * Decodes the given IndexedDb-compatible string form of a resource path into\r\n * a ResourcePath instance. Note that this method is not suitable for use with\r\n * decoding resource names from the server; those are One Platform format\r\n * strings.\r\n */\r\nfunction decode(path) {\r\n // Event the empty path must encode as a path of at least length 2. A path\r\n // with exactly 2 must be the empty path.\r\n var length = path.length;\r\n assert(length >= 2, 'Invalid path ' + path);\r\n if (length === 2) {\r\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\r\n return ResourcePath.EMPTY_PATH;\r\n }\r\n // Escape characters cannot exist past the second-to-last position in the\r\n // source value.\r\n var lastReasonableEscapeIndex = length - 2;\r\n var segments = [];\r\n var segmentBuilder = '';\r\n for (var start = 0; start < length;) {\r\n // The last two characters of a valid encoded path must be a separator, so\r\n // there must be an end to this segment.\r\n var end = path.indexOf(escapeChar, start);\r\n if (end < 0 || end > lastReasonableEscapeIndex) {\r\n fail('Invalid encoded resource path: \"' + path + '\"');\r\n }\r\n var next = path.charAt(end + 1);\r\n switch (next) {\r\n case encodedSeparatorChar:\r\n var currentPiece = path.substring(start, end);\r\n var segment = void 0;\r\n if (segmentBuilder.length === 0) {\r\n // Avoid copying for the common case of a segment that excludes \\0\r\n // and \\001\r\n segment = currentPiece;\r\n }\r\n else {\r\n segmentBuilder += currentPiece;\r\n segment = segmentBuilder;\r\n segmentBuilder = '';\r\n }\r\n segments.push(segment);\r\n break;\r\n case encodedNul:\r\n segmentBuilder += path.substring(start, end);\r\n segmentBuilder += '\\0';\r\n break;\r\n case encodedEscape:\r\n // The escape character can be used in the output to encode itself.\r\n segmentBuilder += path.substring(start, end + 1);\r\n break;\r\n default:\r\n fail('Invalid encoded resource path: \"' + path + '\"');\r\n }\r\n start = end + 2;\r\n }\r\n return new ResourcePath(segments);\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Schema Version for the Web client:\r\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\r\n * Cache\r\n * 2. Added targetCount to targetGlobal row.\r\n */\r\nvar SCHEMA_VERSION = 2;\r\n/**\r\n * Performs database creation and schema upgrades.\r\n *\r\n * Note that in production, this method is only ever used to upgrade the schema\r\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\r\n * and local feature development.\r\n */\r\nfunction createOrUpgradeDb(db, txn, fromVersion, toVersion) {\r\n // This function currently supports migrating to schema version 1 (Mutation\r\n // Queue, Query and Remote Document Cache) and schema version 2 (Query\r\n // counting).\r\n assert(fromVersion < toVersion && fromVersion >= 0 && toVersion <= 2, 'Unexpected schema upgrade from v${fromVersion} to v{toVersion}.');\r\n if (fromVersion < 1 && toVersion >= 1) {\r\n createOwnerStore(db);\r\n createMutationQueue(db);\r\n createQueryCache(db);\r\n createRemoteDocumentCache(db);\r\n }\r\n var p = PersistencePromise.resolve();\r\n if (fromVersion < 2 && toVersion >= 2) {\r\n p = ensureTargetGlobalExists(txn).next(function (targetGlobal) {\r\n return saveTargetCount(txn, targetGlobal);\r\n });\r\n }\r\n return p;\r\n}\r\n/**\r\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\r\n */\r\nvar DbTimestamp = /** @class */ (function () {\r\n function DbTimestamp(seconds, nanoseconds) {\r\n this.seconds = seconds;\r\n this.nanoseconds = nanoseconds;\r\n }\r\n return DbTimestamp;\r\n}());\r\n/**\r\n * A singleton object to be stored in the 'owner' store in IndexedDb.\r\n *\r\n * A given database can be owned by a single tab at a given time. That tab\r\n * must validate that it is still the owner before every write operation and\r\n * should regularly write an updated timestamp to prevent other tabs from\r\n * \"stealing\" ownership of the db.\r\n */\r\nvar DbOwner = /** @class */ (function () {\r\n function DbOwner(ownerId, leaseTimestampMs) {\r\n this.ownerId = ownerId;\r\n this.leaseTimestampMs = leaseTimestampMs;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbOwner.store = 'owner';\r\n return DbOwner;\r\n}());\r\nfunction createOwnerStore(db) {\r\n db.createObjectStore(DbOwner.store);\r\n}\r\n/**\r\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\r\n *\r\n * Each user gets a single queue of MutationBatches to apply to the server.\r\n * DbMutationQueue tracks the metadata about the queue.\r\n */\r\nvar DbMutationQueue = /** @class */ (function () {\r\n function DbMutationQueue(\r\n /**\r\n * The normalized user ID to which this queue belongs.\r\n */\r\n userId, \r\n /**\r\n * An identifier for the highest numbered batch that has been acknowledged\r\n * by the server. All MutationBatches in this queue with batchIds less\r\n * than or equal to this value are considered to have been acknowledged by\r\n * the server.\r\n */\r\n lastAcknowledgedBatchId, \r\n /**\r\n * A stream token that was previously sent by the server.\r\n *\r\n * See StreamingWriteRequest in datastore.proto for more details about\r\n * usage.\r\n *\r\n * After sending this token, earlier tokens may not be used anymore so\r\n * only a single stream token is retained.\r\n */\r\n lastStreamToken) {\r\n this.userId = userId;\r\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\r\n this.lastStreamToken = lastStreamToken;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbMutationQueue.store = 'mutationQueues';\r\n /** Keys are automatically assigned via the userId property. */\r\n DbMutationQueue.keyPath = 'userId';\r\n return DbMutationQueue;\r\n}());\r\n/**\r\n * An object to be stored in the 'mutations' store in IndexedDb.\r\n *\r\n * Represents a batch of user-level mutations intended to be sent to the server\r\n * in a single write. Each user-level batch gets a separate DbMutationBatch\r\n * with a new batchId.\r\n */\r\nvar DbMutationBatch = /** @class */ (function () {\r\n function DbMutationBatch(\r\n /**\r\n * The normalized user ID to which this batch belongs.\r\n */\r\n userId, \r\n /**\r\n * An identifier for this batch, allocated by the mutation queue in a\r\n * monotonically increasing manner.\r\n */\r\n batchId, \r\n /**\r\n * The local write time of the batch, stored as milliseconds since the\r\n * epoch.\r\n */\r\n localWriteTimeMs, \r\n /**\r\n * A list of mutations to apply. All mutations will be applied atomically.\r\n *\r\n * Mutations are serialized via JsonProtoSerializer.toMutation().\r\n */\r\n mutations) {\r\n this.userId = userId;\r\n this.batchId = batchId;\r\n this.localWriteTimeMs = localWriteTimeMs;\r\n this.mutations = mutations;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbMutationBatch.store = 'mutations';\r\n /** Keys are automatically assigned via the userId, batchId properties. */\r\n DbMutationBatch.keyPath = ['userId', 'batchId'];\r\n return DbMutationBatch;\r\n}());\r\nfunction createMutationQueue(db) {\r\n db.createObjectStore(DbMutationQueue.store, {\r\n keyPath: DbMutationQueue.keyPath\r\n });\r\n db.createObjectStore(DbMutationBatch.store, {\r\n keyPath: DbMutationBatch.keyPath\r\n });\r\n db.createObjectStore(DbDocumentMutation.store);\r\n}\r\n/**\r\n * An object to be stored in the 'documentMutations' store in IndexedDb.\r\n *\r\n * A manually maintained index of all the mutation batches that affect a given\r\n * document key. The rows in this table are references based on the contents of\r\n * DbMutationBatch.mutations.\r\n */\r\nvar DbDocumentMutation = /** @class */ (function () {\r\n function DbDocumentMutation() {\r\n }\r\n /**\r\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\r\n * over all of a user's document mutations.\r\n */\r\n DbDocumentMutation.prefixForUser = function (userId) {\r\n return [userId];\r\n };\r\n /**\r\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\r\n * index to iterate over all at document mutations for a given path or lower.\r\n */\r\n DbDocumentMutation.prefixForPath = function (userId, path) {\r\n return [userId, encode(path)];\r\n };\r\n /**\r\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\r\n * and deleting into the DbDocumentMutations index.\r\n */\r\n DbDocumentMutation.key = function (userId, path, batchId) {\r\n return [userId, encode(path), batchId];\r\n };\r\n DbDocumentMutation.store = 'documentMutations';\r\n /**\r\n * Because we store all the useful information for this store in the key,\r\n * there is no useful information to store as the value. The raw (unencoded)\r\n * path cannot be stored because IndexedDb doesn't store prototype\r\n * information.\r\n */\r\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\r\n return DbDocumentMutation;\r\n}());\r\nfunction createRemoteDocumentCache(db) {\r\n db.createObjectStore(DbRemoteDocument.store);\r\n}\r\n/**\r\n * Represents the known absence of a document at a particular version.\r\n * Stored in IndexedDb as part of a DbRemoteDocument object.\r\n */\r\nvar DbNoDocument = /** @class */ (function () {\r\n function DbNoDocument(path, readTime) {\r\n this.path = path;\r\n this.readTime = readTime;\r\n }\r\n return DbNoDocument;\r\n}());\r\n/**\r\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\r\n * represents either a cached document (if it exists) or a cached \"no-document\"\r\n * (if it is known to not exist).\r\n *\r\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\r\n * be made more general if necessary.\r\n */\r\nvar DbRemoteDocument = /** @class */ (function () {\r\n function DbRemoteDocument(\r\n /**\r\n * Set to an instance of a DbNoDocument if it is known that no document\r\n * exists.\r\n */\r\n noDocument, \r\n /**\r\n * Set to an instance of a Document if there's a cached version of the\r\n * document.\r\n */\r\n document) {\r\n this.noDocument = noDocument;\r\n this.document = document;\r\n }\r\n DbRemoteDocument.store = 'remoteDocuments';\r\n return DbRemoteDocument;\r\n}());\r\n/**\r\n * An object to be stored in the 'targets' store in IndexedDb.\r\n *\r\n * This is based on and should be kept in sync with the proto used in the iOS\r\n * client.\r\n *\r\n * Each query the client listens to against the server is tracked on disk so\r\n * that the query can be efficiently resumed on restart.\r\n */\r\nvar DbTarget = /** @class */ (function () {\r\n function DbTarget(\r\n /**\r\n * An auto-generated sequential numeric identifier for the query.\r\n *\r\n * Queries are stored using their canonicalId as the key, but these\r\n * canonicalIds can be quite long so we additionally assign a unique\r\n * queryId which can be used by referenced data structures (e.g.\r\n * indexes) to minimize the on-disk cost.\r\n */\r\n targetId, \r\n /**\r\n * The canonical string representing this query. This is not unique.\r\n */\r\n canonicalId, \r\n /**\r\n * The last readTime received from the Watch Service for this query.\r\n *\r\n * This is the same value as TargetChange.read_time in the protos.\r\n */\r\n readTime, \r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data\r\n * that matches the query. The resume token essentially identifies a\r\n * point in time from which the server should resume sending results.\r\n *\r\n * This is related to the snapshotVersion in that the resumeToken\r\n * effectively also encodes that value, but the resumeToken is opaque\r\n * and sometimes encodes additional information.\r\n *\r\n * A consequence of this is that the resumeToken should be used when\r\n * asking the server to reason about where this client is in the watch\r\n * stream, but the client should use the snapshotVersion for its own\r\n * purposes.\r\n *\r\n * This is the same value as TargetChange.resume_token in the protos.\r\n */\r\n resumeToken, \r\n /**\r\n * A sequence number representing the last time this query was\r\n * listened to, used for garbage collection purposes.\r\n *\r\n * Conventionally this would be a timestamp value, but device-local\r\n * clocks are unreliable and they must be able to create new listens\r\n * even while disconnected. Instead this should be a monotonically\r\n * increasing number that's incremented on each listen call.\r\n *\r\n * This is different from the queryId since the queryId is an\r\n * immutable identifier assigned to the Query on first use while\r\n * lastListenSequenceNumber is updated every time the query is\r\n * listened to.\r\n */\r\n lastListenSequenceNumber, \r\n /**\r\n * The query for this target.\r\n *\r\n * Because canonical ids are not unique we must store the actual query. We\r\n * use the proto to have an object we can persist without having to\r\n * duplicate translation logic to and from a `Query` object.\r\n */\r\n query) {\r\n this.targetId = targetId;\r\n this.canonicalId = canonicalId;\r\n this.readTime = readTime;\r\n this.resumeToken = resumeToken;\r\n this.lastListenSequenceNumber = lastListenSequenceNumber;\r\n this.query = query;\r\n }\r\n DbTarget.store = 'targets';\r\n /** Keys are automatically assigned via the targetId property. */\r\n DbTarget.keyPath = 'targetId';\r\n /** The name of the queryTargets index. */\r\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\r\n /**\r\n * The index of all canonicalIds to the targets that they match. This is not\r\n * a unique mapping because canonicalId does not promise a unique name for all\r\n * possible queries, so we append the targetId to make the mapping unique.\r\n */\r\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\r\n return DbTarget;\r\n}());\r\n/**\r\n * An object representing an association between a target and a document.\r\n * Stored in the targetDocument object store to store the documents tracked by a\r\n * particular target.\r\n */\r\nvar DbTargetDocument = /** @class */ (function () {\r\n function DbTargetDocument(\r\n /**\r\n * The targetId identifying a target.\r\n */\r\n targetId, \r\n /**\r\n * The path to the document, as encoded in the key.\r\n */\r\n path) {\r\n this.targetId = targetId;\r\n this.path = path;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbTargetDocument.store = 'targetDocuments';\r\n /** Keys are automatically assigned via the targetId, path properties. */\r\n DbTargetDocument.keyPath = ['targetId', 'path'];\r\n /** The index name for the reverse index. */\r\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\r\n /** We also need to create the reverse index for these properties. */\r\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\r\n return DbTargetDocument;\r\n}());\r\n/**\r\n * A record of global state tracked across all Targets, tracked separately\r\n * to avoid the need for extra indexes.\r\n *\r\n * This should be kept in-sync with the proto used in the iOS client.\r\n */\r\nvar DbTargetGlobal = /** @class */ (function () {\r\n function DbTargetGlobal(\r\n /**\r\n * The highest numbered target id across all targets.\r\n *\r\n * See DbTarget.targetId.\r\n */\r\n highestTargetId, \r\n /**\r\n * The highest numbered lastListenSequenceNumber across all targets.\r\n *\r\n * See DbTarget.lastListenSequenceNumber.\r\n */\r\n highestListenSequenceNumber, \r\n /**\r\n * A global snapshot version representing the last consistent snapshot we\r\n * received from the backend. This is monotonically increasing and any\r\n * snapshots received from the backend prior to this version (e.g. for\r\n * targets resumed with a resumeToken) should be suppressed (buffered)\r\n * until the backend has caught up to this snapshot version again. This\r\n * prevents our cache from ever going backwards in time.\r\n */\r\n lastRemoteSnapshotVersion, \r\n /**\r\n * The number of targets persisted.\r\n */\r\n targetCount) {\r\n this.highestTargetId = highestTargetId;\r\n this.highestListenSequenceNumber = highestListenSequenceNumber;\r\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\r\n this.targetCount = targetCount;\r\n }\r\n /**\r\n * The key string used for the single object that exists in the\r\n * DbTargetGlobal store.\r\n */\r\n DbTargetGlobal.key = 'targetGlobalKey';\r\n DbTargetGlobal.store = 'targetGlobal';\r\n return DbTargetGlobal;\r\n}());\r\nfunction createQueryCache(db) {\r\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\r\n keyPath: DbTargetDocument.keyPath\r\n });\r\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\r\n var targetStore = db.createObjectStore(DbTarget.store, {\r\n keyPath: DbTarget.keyPath\r\n });\r\n // NOTE: This is unique only because the TargetId is the suffix.\r\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\r\n db.createObjectStore(DbTargetGlobal.store);\r\n}\r\n/**\r\n * Counts the number of targets persisted and adds that value to the target\r\n * global singleton.\r\n */\r\nfunction saveTargetCount(txn, metadata) {\r\n var globalStore = txn.store(DbTargetGlobal.store);\r\n var targetStore = txn.store(DbTarget.store);\r\n return targetStore.count().next(function (count) {\r\n metadata.targetCount = count;\r\n return globalStore.put(DbTargetGlobal.key, metadata);\r\n });\r\n}\r\n/**\r\n * Ensures that the target global singleton row exists by adding it if it's\r\n * missing.\r\n *\r\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\r\n */\r\nfunction ensureTargetGlobalExists(txn) {\r\n var globalStore = txn.store(DbTargetGlobal.store);\r\n return globalStore.get(DbTargetGlobal.key).next(function (metadata) {\r\n if (metadata != null) {\r\n return PersistencePromise.resolve(metadata);\r\n }\r\n else {\r\n metadata = new DbTargetGlobal(\r\n /*highestTargetId=*/ 0, \r\n /*lastListenSequenceNumber=*/ 0, SnapshotVersion.MIN.toTimestamp(), \r\n /*targetCount=*/ 0);\r\n return globalStore.put(DbTargetGlobal.key, metadata).next(function () { return metadata; });\r\n }\r\n });\r\n}\r\n/**\r\n * The list of all default IndexedDB stores used throughout the SDK. This is\r\n * used when creating transactions so that access across all stores is done\r\n * atomically.\r\n */\r\nvar ALL_STORES = [\r\n DbMutationQueue.store,\r\n DbMutationBatch.store,\r\n DbDocumentMutation.store,\r\n DbRemoteDocument.store,\r\n DbTarget.store,\r\n DbOwner.store,\r\n DbTargetGlobal.store,\r\n DbTargetDocument.store\r\n];\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$2 = 'SimpleDb';\r\n/**\r\n * Provides a wrapper around IndexedDb with a simplified interface that uses\r\n * Promise-like return values to chain operations. Real promises cannot be used\r\n * since .then() continuations are executed asynchronously (e.g. via\r\n * .setImmediate), which would cause IndexedDB to end the transaction.\r\n * See PersistencePromise for more details.\r\n */\r\nvar SimpleDb = /** @class */ (function () {\r\n function SimpleDb(db) {\r\n this.db = db;\r\n }\r\n /** Opens the specified database, creating or upgrading it if necessary. */\r\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\r\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\r\n debug(LOG_TAG$2, 'Opening database:', name);\r\n return new PersistencePromise(function (resolve, reject) {\r\n // TODO(mikelehen): Investigate browser compatibility.\r\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\r\n // suggests IE9 and older WebKit browsers handle upgrade\r\n // differently. They expect setVersion, as described here:\r\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\r\n var request = window.indexedDB.open(name, version);\r\n request.onsuccess = function (event) {\r\n var db = event.target.result;\r\n resolve(new SimpleDb(db));\r\n };\r\n request.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n request.onupgradeneeded = function (event) {\r\n debug(LOG_TAG$2, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\r\n var db = event.target.result;\r\n // We are provided a version upgrade transaction from the request, so\r\n // we wrap that in a SimpleDbTransaction to allow use of our friendlier\r\n // API for schema migration operations.\r\n var txn = new SimpleDbTransaction(request.transaction);\r\n runUpgrade(db, txn, event.oldVersion, SCHEMA_VERSION).next(function () {\r\n debug(LOG_TAG$2, 'Database upgrade to version ' + SCHEMA_VERSION + ' complete');\r\n });\r\n };\r\n }).toPromise();\r\n };\r\n /** Deletes the specified database. */\r\n SimpleDb.delete = function (name) {\r\n debug(LOG_TAG$2, 'Removing database:', name);\r\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\r\n };\r\n /** Returns true if IndexedDB is available in the current environment. */\r\n SimpleDb.isAvailable = function () {\r\n if (typeof window === 'undefined' || window.indexedDB == null) {\r\n return false;\r\n }\r\n // We extensively use indexed array values and compound keys,\r\n // which IE and Edge do not support. However, they still have indexedDB\r\n // defined on the window, so we need to check for them here and make sure\r\n // to return that persistence is not enabled for those browsers.\r\n // For tracking support of this feature, see here:\r\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\r\n // Check the UA string to find out the browser.\r\n var ua = window.navigator.userAgent;\r\n // IE 10\r\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\r\n // IE 11\r\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\r\n // Edge\r\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\r\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\r\n if (ua.indexOf('MSIE ') > 0 ||\r\n ua.indexOf('Trident/') > 0 ||\r\n ua.indexOf('Edge/') > 0) {\r\n return false;\r\n }\r\n else {\r\n return true;\r\n }\r\n };\r\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\r\n var transaction = SimpleDbTransaction.open(this.db, mode, objectStores);\r\n var transactionFnResult = transactionFn(transaction)\r\n .catch(function (error$$1) {\r\n // Abort the transaction if there was an\r\n // error.\r\n transaction.abort();\r\n return PersistencePromise.reject(error$$1);\r\n })\r\n .toPromise();\r\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\r\n // fire), but still return the original transactionFnResult back to the\r\n // caller.\r\n return transaction.completionPromise.then(function () { return transactionFnResult; });\r\n };\r\n SimpleDb.prototype.close = function () {\r\n this.db.close();\r\n };\r\n return SimpleDb;\r\n}());\r\n/**\r\n * A controller for iterating over a key range or index. It allows an iterate\r\n * callback to delete the currently-referenced object, or jump to a new key\r\n * within the key range or index.\r\n */\r\nvar IterationController = /** @class */ (function () {\r\n function IterationController(dbCursor) {\r\n this.dbCursor = dbCursor;\r\n this.shouldStop = false;\r\n this.nextKey = null;\r\n }\r\n Object.defineProperty(IterationController.prototype, \"isDone\", {\r\n get: function () {\r\n return this.shouldStop;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\r\n get: function () {\r\n return this.nextKey;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(IterationController.prototype, \"cursor\", {\r\n set: function (value) {\r\n this.dbCursor = value;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * This function can be called to stop iteration at any point.\r\n */\r\n IterationController.prototype.done = function () {\r\n this.shouldStop = true;\r\n };\r\n /**\r\n * This function can be called to skip to that next key, which could be\r\n * an index or a primary key.\r\n */\r\n IterationController.prototype.skip = function (key) {\r\n this.nextKey = key;\r\n };\r\n /**\r\n * Delete the current cursor value from the object store.\r\n *\r\n * NOTE: You CANNOT do this with a keysOnly query.\r\n */\r\n IterationController.prototype.delete = function () {\r\n return wrapRequest(this.dbCursor.delete());\r\n };\r\n return IterationController;\r\n}());\r\n/**\r\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\r\n * specific object store.\r\n */\r\nvar SimpleDbTransaction = /** @class */ (function () {\r\n function SimpleDbTransaction(transaction) {\r\n var _this = this;\r\n this.transaction = transaction;\r\n this.aborted = false;\r\n this.completionPromise = new Promise(function (resolve, reject) {\r\n // We consider aborting to be \"normal\" and just resolve the promise.\r\n // May need to revisit if/when we actually need to abort transactions.\r\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\r\n resolve();\r\n };\r\n _this.transaction.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n });\r\n }\r\n SimpleDbTransaction.open = function (db, mode, objectStoreNames) {\r\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\r\n };\r\n SimpleDbTransaction.prototype.abort = function () {\r\n if (!this.aborted) {\r\n debug(LOG_TAG$2, 'Aborting transaction.');\r\n this.aborted = true;\r\n this.transaction.abort();\r\n }\r\n };\r\n /**\r\n * Returns a SimpleDbStore for the specified store. All\r\n * operations performed on the SimpleDbStore happen within the context of this\r\n * transaction and it cannot be used anymore once the transaction is\r\n * completed.\r\n *\r\n * Note that we can't actually enforce that the KeyType and ValueType are\r\n * correct, but they allow type safety through the rest of the consuming code.\r\n */\r\n SimpleDbTransaction.prototype.store = function (storeName) {\r\n var store = this.transaction.objectStore(storeName);\r\n assert(!!store, 'Object store not part of transaction: ' + storeName);\r\n return new SimpleDbStore(store);\r\n };\r\n return SimpleDbTransaction;\r\n}());\r\n/**\r\n * A wrapper around an IDBObjectStore providing an API that:\r\n *\r\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\r\n * methods for acting against the object store.\r\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\r\n * method return a PersistencePromise instead.\r\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\r\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\r\n */\r\nvar SimpleDbStore = /** @class */ (function () {\r\n function SimpleDbStore(store) {\r\n this.store = store;\r\n }\r\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\r\n var request;\r\n if (value !== undefined) {\r\n debug(LOG_TAG$2, 'PUT', this.store.name, keyOrValue, value);\r\n request = this.store.put(value, keyOrValue);\r\n }\r\n else {\r\n debug(LOG_TAG$2, 'PUT', this.store.name, '', keyOrValue);\r\n request = this.store.put(keyOrValue);\r\n }\r\n return wrapRequest(request);\r\n };\r\n /**\r\n * Gets the object with the specified key from the specified store, or null\r\n * if no object exists with the specified key.\r\n *\r\n * @key The key of the object to get.\r\n * @return The object with the specified key or null if no object exists.\r\n */\r\n SimpleDbStore.prototype.get = function (key) {\r\n var _this = this;\r\n var request = this.store.get(key);\r\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\r\n return wrapRequest(request).next(function (result) {\r\n // Normalize nonexistence to null.\r\n if (result === undefined) {\r\n result = null;\r\n }\r\n debug(LOG_TAG$2, 'GET', _this.store.name, key, result);\r\n return result;\r\n });\r\n };\r\n SimpleDbStore.prototype.delete = function (key) {\r\n debug(LOG_TAG$2, 'DELETE', this.store.name, key);\r\n var request = this.store.delete(key);\r\n return wrapRequest(request);\r\n };\r\n /**\r\n * If we ever need more of the count variants, we can add overloads. For now,\r\n * all we need is to count everything in a store.\r\n *\r\n * Returns the number of rows in the store.\r\n */\r\n SimpleDbStore.prototype.count = function () {\r\n debug(LOG_TAG$2, 'COUNT', this.store.name);\r\n var request = this.store.count();\r\n return wrapRequest(request);\r\n };\r\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\r\n var cursor = this.cursor(this.options(indexOrRange, range));\r\n var results = [];\r\n return this.iterateCursor(cursor, function (key, value) {\r\n results.push(value);\r\n }).next(function () {\r\n return results;\r\n });\r\n };\r\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\r\n debug(LOG_TAG$2, 'DELETE ALL', this.store.name);\r\n var options = this.options(indexOrRange, range);\r\n options.keysOnly = false;\r\n var cursor = this.cursor(options);\r\n return this.iterateCursor(cursor, function (key, value, control) {\r\n // NOTE: Calling delete() on a cursor is documented as more efficient than\r\n // calling delete() on an object store with a single key\r\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\r\n // however, this requires us *not* to use a keysOnly cursor\r\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\r\n // may want to compare the performance of each method.\r\n return control.delete();\r\n });\r\n };\r\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\r\n var options;\r\n if (!callback) {\r\n options = {};\r\n callback = optionsOrCallback;\r\n }\r\n else {\r\n options = optionsOrCallback;\r\n }\r\n var cursor = this.cursor(options);\r\n return this.iterateCursor(cursor, callback);\r\n };\r\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\r\n var results = [];\r\n return new PersistencePromise(function (resolve, reject) {\r\n cursorRequest.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n cursorRequest.onsuccess = function (event) {\r\n var cursor = event.target.result;\r\n if (!cursor) {\r\n resolve();\r\n return;\r\n }\r\n var controller = new IterationController(cursor);\r\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\r\n if (userResult instanceof PersistencePromise) {\r\n results.push(userResult);\r\n }\r\n if (controller.isDone) {\r\n resolve();\r\n }\r\n else if (controller.skipToKey === null) {\r\n cursor.continue();\r\n }\r\n else {\r\n cursor.continue(controller.skipToKey);\r\n }\r\n };\r\n }).next(function () {\r\n return PersistencePromise.waitFor(results);\r\n });\r\n };\r\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\r\n var indexName = undefined;\r\n if (indexOrRange !== undefined) {\r\n if (typeof indexOrRange === 'string') {\r\n indexName = indexOrRange;\r\n }\r\n else {\r\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\r\n range = indexOrRange;\r\n }\r\n }\r\n return { index: indexName, range: range };\r\n };\r\n SimpleDbStore.prototype.cursor = function (options) {\r\n var direction = 'next';\r\n if (options.reverse) {\r\n direction = 'prev';\r\n }\r\n if (options.index) {\r\n var index = this.store.index(options.index);\r\n if (options.keysOnly) {\r\n return index.openKeyCursor(options.range, direction);\r\n }\r\n else {\r\n return index.openCursor(options.range, direction);\r\n }\r\n }\r\n else {\r\n return this.store.openCursor(options.range, direction);\r\n }\r\n };\r\n return SimpleDbStore;\r\n}());\r\n/**\r\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\r\n * handlers to resolve / reject the PersistencePromise as appropriate.\r\n */\r\nfunction wrapRequest(request) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n request.onsuccess = function (event) {\r\n var result = event.target.result;\r\n resolve(result);\r\n };\r\n request.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n });\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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/** A mutation queue for a specific user, backed by IndexedDB. */\r\nvar IndexedDbMutationQueue = /** @class */ (function () {\r\n function IndexedDbMutationQueue(\r\n /**\r\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\r\n * retrieve mutations.\r\n */\r\n userId, serializer) {\r\n this.userId = userId;\r\n this.serializer = serializer;\r\n this.garbageCollector = null;\r\n }\r\n /**\r\n * Creates a new mutation queue for the given user.\r\n * @param user The user for which to create a mutation queue.\r\n * @param serializer The serializer to use when persisting to IndexedDb.\r\n */\r\n IndexedDbMutationQueue.forUser = function (user, serializer) {\r\n // TODO(mcg): Figure out what constraints there are on userIDs\r\n // In particular, are there any reserved characters? are empty ids allowed?\r\n // For the moment store these together in the same mutations table assuming\r\n // that empty userIDs aren't allowed.\r\n assert(user.uid !== '', 'UserID must not be an empty string.');\r\n var userId = user.isAuthenticated() ? user.uid : '';\r\n return new IndexedDbMutationQueue(userId, serializer);\r\n };\r\n IndexedDbMutationQueue.prototype.start = function (transaction) {\r\n var _this = this;\r\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\r\n .next(function (nextBatchId) {\r\n _this.nextBatchId = nextBatchId;\r\n return mutationQueuesStore(transaction).get(_this.userId);\r\n })\r\n .next(function (metadata) {\r\n if (!metadata) {\r\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \r\n /*lastStreamToken=*/ '');\r\n }\r\n _this.metadata = metadata;\r\n // On restart, nextBatchId may end up lower than\r\n // lastAcknowledgedBatchId since it's computed from the queue\r\n // contents, and there may be no mutations in the queue. In this\r\n // case, we need to reset lastAcknowledgedBatchId (which is safe\r\n // since the queue must be empty).\r\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\r\n return _this.checkEmpty(transaction).next(function (empty) {\r\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\r\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\r\n return mutationQueuesStore(transaction).put(_this.metadata);\r\n });\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n };\r\n /**\r\n * Returns one larger than the largest batch ID that has been stored. If there\r\n * are no mutations returns 0. Note that batch IDs are global.\r\n */\r\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\r\n var maxBatchId = BATCHID_UNKNOWN;\r\n return mutationsStore(txn)\r\n .iterate({ reverse: true }, function (key, batch, control) {\r\n var userId = key[0], batchId = key[1];\r\n if (batchId > maxBatchId) {\r\n maxBatchId = batch.batchId;\r\n }\r\n if (userId === '') {\r\n // We can't compute a predecessor for the empty string, since it\r\n // is lexographically first. That also means that no other\r\n // userIds can come before this one, so we can just exit early.\r\n control.done();\r\n }\r\n else {\r\n var nextUser = immediatePredecessor(userId);\r\n control.skip([nextUser]);\r\n }\r\n })\r\n .next(function () { return maxBatchId + 1; });\r\n };\r\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\r\n var empty = true;\r\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\r\n return mutationsStore(transaction)\r\n .iterate({ range: range }, function (key, value, control) {\r\n empty = false;\r\n control.done();\r\n })\r\n .next(function () { return empty; });\r\n };\r\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\r\n return PersistencePromise.resolve(this.nextBatchId);\r\n };\r\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\r\n return PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\r\n };\r\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\r\n var batchId = batch.batchId;\r\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\r\n this.metadata.lastAcknowledgedBatchId = batchId;\r\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\r\n return mutationQueuesStore(transaction).put(this.metadata);\r\n };\r\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\r\n return PersistencePromise.resolve(this.metadata.lastStreamToken);\r\n };\r\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\r\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\r\n return mutationQueuesStore(transaction).put(this.metadata);\r\n };\r\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\r\n var _this = this;\r\n var batchId = this.nextBatchId;\r\n this.nextBatchId++;\r\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\r\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\r\n return mutationsStore(transaction)\r\n .put(dbBatch)\r\n .next(function () {\r\n var promises = [];\r\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\r\n var mutation = mutations_1[_i];\r\n var indexKey = DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\r\n promises.push(documentMutationsStore(transaction).put(indexKey, DbDocumentMutation.PLACEHOLDER));\r\n }\r\n return PersistencePromise.waitFor(promises);\r\n })\r\n .next(function () {\r\n return batch;\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\r\n var _this = this;\r\n return mutationsStore(transaction)\r\n .get(this.keyForBatchId(batchId))\r\n .next(function (dbBatch) {\r\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\r\n var _this = this;\r\n // All batches with batchId <= this.metadata.lastAcknowledgedBatchId have\r\n // been acknowledged so the first unacknowledged batch after batchID will\r\n // have a batchID larger than both of these values.\r\n var nextBatchId = Math.max(batchId, this.metadata.lastAcknowledgedBatchId) + 1;\r\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(nextBatchId));\r\n var foundBatch = null;\r\n return mutationsStore(transaction)\r\n .iterate({ range: range }, function (key, dbBatch, control) {\r\n if (dbBatch.userId === _this.userId) {\r\n assert(dbBatch.batchId >= nextBatchId, 'Should have found mutation after ' + nextBatchId);\r\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\r\n }\r\n control.done();\r\n })\r\n .next(function () { return foundBatch; });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\r\n var _this = this;\r\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\r\n return mutationsStore(transaction)\r\n .loadAll(range)\r\n .next(function (dbBatches) {\r\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\r\n var _this = this;\r\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\r\n return mutationsStore(transaction)\r\n .loadAll(range)\r\n .next(function (dbBatches) {\r\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\r\n var _this = this;\r\n // Scan the document-mutation index starting with a prefix starting with\r\n // the given documentKey.\r\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\r\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\r\n var results = [];\r\n return documentMutationsStore(transaction)\r\n .iterate({ range: indexStart }, function (indexKey, _, control) {\r\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\r\n // Only consider rows matching exactly the specific key of\r\n // interest. Note that because we order by path first, and we\r\n // order terminators before path separators, we'll encounter all\r\n // the index rows for documentKey contiguously. In particular, all\r\n // the rows for documentKey will occur before any rows for\r\n // documents nested in a subcollection beneath documentKey so we\r\n // can stop as soon as we hit any such row.\r\n var path = decode(encodedPath);\r\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\r\n control.done();\r\n return;\r\n }\r\n var mutationKey = _this.keyForBatchId(batchID);\r\n // Look up the mutation batch in the store.\r\n // PORTING NOTE: because iteration is callback driven in the web,\r\n // we just look up the key instead of keeping an open iterator\r\n // like iOS.\r\n return mutationsStore(transaction)\r\n .get(mutationKey)\r\n .next(function (dbBatch) {\r\n if (dbBatch === null) {\r\n fail('Dangling document-mutation reference found: ' +\r\n indexKey +\r\n ' which points to ' +\r\n mutationKey);\r\n }\r\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\r\n });\r\n })\r\n .next(function () { return results; });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\r\n var _this = this;\r\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\r\n var queryPath = query.path;\r\n var immediateChildrenLength = queryPath.length + 1;\r\n // TODO(mcg): Actually implement a single-collection query\r\n //\r\n // This is actually executing an ancestor query, traversing the whole\r\n // subtree below the collection which can be horrifically inefficient for\r\n // some structures. The right way to solve this is to implement the full\r\n // value index, but that's not in the cards in the near future so this is\r\n // the best we can do for the moment.\r\n //\r\n // Since we don't yet index the actual properties in the mutations, our\r\n // current approach is to just return all mutation batches that affect\r\n // documents in the collection being queried.\r\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, queryPath);\r\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\r\n // Collect up unique batchIDs encountered during a scan of the index. Use a\r\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\r\n // scan of the main table.\r\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\r\n return documentMutationsStore(transaction)\r\n .iterate({ range: indexStart }, function (indexKey, _, control) {\r\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\r\n var path = decode(encodedPath);\r\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\r\n control.done();\r\n return;\r\n }\r\n // Rows with document keys more than one segment longer than the\r\n // query path can't be matches. For example, a query on 'rooms'\r\n // can't match the document /rooms/abc/messages/xyx.\r\n // TODO(mcg): we'll need a different scanner when we implement\r\n // ancestor queries.\r\n if (path.length !== immediateChildrenLength) {\r\n return;\r\n }\r\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\r\n })\r\n .next(function () {\r\n var results = [];\r\n var promises = [];\r\n // TODO(rockwood): Implement this using iterate.\r\n uniqueBatchIDs.forEach(function (batchID) {\r\n var mutationKey = _this.keyForBatchId(batchID);\r\n promises.push(mutationsStore(transaction)\r\n .get(mutationKey)\r\n .next(function (mutation) {\r\n if (mutation === null) {\r\n fail('Dangling document-mutation reference found, ' +\r\n 'which points to ' +\r\n mutationKey);\r\n }\r\n results.push(_this.serializer.fromDbMutationBatch(mutation));\r\n }));\r\n });\r\n return PersistencePromise.waitFor(promises).next(function () { return results; });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\r\n var txn = mutationsStore(transaction);\r\n var indexTxn = documentMutationsStore(transaction);\r\n var promises = [];\r\n var _loop_1 = function (batch) {\r\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\r\n var numDeleted = 0;\r\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\r\n numDeleted++;\r\n return control.delete();\r\n });\r\n promises.push(removePromise.next(function () {\r\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\r\n batch.batchId);\r\n }));\r\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\r\n var mutation = _a[_i];\r\n var indexKey = DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\r\n promises.push(indexTxn.delete(indexKey));\r\n if (this_1.garbageCollector !== null) {\r\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\r\n }\r\n }\r\n };\r\n var this_1 = this;\r\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\r\n var batch = batches_1[_i];\r\n _loop_1(batch);\r\n }\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\r\n var _this = this;\r\n return this.checkEmpty(txn).next(function (empty) {\r\n if (!empty) {\r\n return PersistencePromise.resolve();\r\n }\r\n // Verify that there are no entries in the documentMutations index if\r\n // the queue is empty.\r\n var startRange = IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(_this.userId));\r\n var danglingMutationReferences = [];\r\n return documentMutationsStore(txn)\r\n .iterate({ range: startRange }, function (key, _, control) {\r\n var userID = key[0];\r\n if (userID !== _this.userId) {\r\n control.done();\r\n return;\r\n }\r\n else {\r\n var path = decode(key[1]);\r\n danglingMutationReferences.push(path);\r\n }\r\n })\r\n .next(function () {\r\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\r\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\r\n });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\r\n this.garbageCollector = gc;\r\n };\r\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\r\n var _this = this;\r\n var indexKey = DbDocumentMutation.prefixForPath(this.userId, key.path);\r\n var encodedPath = indexKey[1];\r\n var startRange = IDBKeyRange.lowerBound(indexKey);\r\n var containsKey = false;\r\n return documentMutationsStore(txn)\r\n .iterate({ range: startRange, keysOnly: true }, function (key, value, control) {\r\n var userID = key[0], keyPath = key[1], /*batchID*/ _ = key[2];\r\n if (userID === _this.userId && keyPath === encodedPath) {\r\n containsKey = true;\r\n }\r\n control.done();\r\n })\r\n .next(function () { return containsKey; });\r\n };\r\n /**\r\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\r\n * store.\r\n */\r\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\r\n return [this.userId, batchId];\r\n };\r\n return IndexedDbMutationQueue;\r\n}());\r\nfunction validateStreamToken(token) {\r\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\r\n return token;\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the mutations object store.\r\n */\r\nfunction mutationsStore(txn) {\r\n return getStore(txn, DbMutationBatch.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\r\n */\r\nfunction documentMutationsStore(txn) {\r\n return getStore(txn, DbDocumentMutation.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\r\n */\r\nfunction mutationQueuesStore(txn) {\r\n return getStore(txn, DbMutationQueue.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore from a transaction.\r\n */\r\nfunction getStore(txn, store) {\r\n if (txn instanceof SimpleDbTransaction) {\r\n return txn.store(store);\r\n }\r\n else {\r\n return fail('Invalid transaction object provided!');\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar IndexedDbQueryCache = /** @class */ (function () {\r\n function IndexedDbQueryCache(serializer) {\r\n this.serializer = serializer;\r\n /**\r\n * The last received snapshot version. We store this seperately from the\r\n * metadata to avoid the extra conversion to/from DbTimestamp.\r\n */\r\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\r\n /**\r\n * A cached copy of the metadata for the query cache.\r\n */\r\n this.metadata = null;\r\n /** The garbage collector to notify about potential garbage keys. */\r\n this.garbageCollector = null;\r\n }\r\n IndexedDbQueryCache.prototype.start = function (transaction) {\r\n var _this = this;\r\n return globalTargetStore(transaction)\r\n .get(DbTargetGlobal.key)\r\n .next(function (metadata) {\r\n assert(metadata !== null, 'Missing metadata row that should be added by schema migration.');\r\n _this.metadata = metadata;\r\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\r\n _this.lastRemoteSnapshotVersion = SnapshotVersion.fromTimestamp(new Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanoseconds));\r\n return PersistencePromise.resolve();\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\r\n return this.metadata.highestTargetId;\r\n };\r\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\r\n return this.lastRemoteSnapshotVersion;\r\n };\r\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\r\n this.lastRemoteSnapshotVersion = snapshotVersion;\r\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\r\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\r\n };\r\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\r\n var _this = this;\r\n return this.saveQueryData(transaction, queryData).next(function () {\r\n _this.metadata.targetCount += 1;\r\n _this.updateMetadataFromQueryData(queryData);\r\n return _this.saveMetadata(transaction);\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.updateQueryData = function (transaction, queryData) {\r\n var _this = this;\r\n return this.saveQueryData(transaction, queryData).next(function () {\r\n if (_this.updateMetadataFromQueryData(queryData)) {\r\n return _this.saveMetadata(transaction);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\r\n var _this = this;\r\n assert(this.metadata.targetCount > 0, 'Removing from an empty query cache');\r\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId)\r\n .next(function () { return targetsStore(transaction).delete(queryData.targetId); })\r\n .next(function () {\r\n _this.metadata.targetCount -= 1;\r\n return _this.saveMetadata(transaction);\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.saveMetadata = function (transaction) {\r\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\r\n };\r\n IndexedDbQueryCache.prototype.saveQueryData = function (transaction, queryData) {\r\n return targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\r\n };\r\n /**\r\n * Updates the in-memory version of the metadata to account for values in the\r\n * given QueryData. Saving is done separately. Returns true if there were any\r\n * changes to the metadata.\r\n */\r\n IndexedDbQueryCache.prototype.updateMetadataFromQueryData = function (queryData) {\r\n var needsUpdate = false;\r\n if (queryData.targetId > this.metadata.highestTargetId) {\r\n this.metadata.highestTargetId = queryData.targetId;\r\n needsUpdate = true;\r\n }\r\n // TODO(GC): add sequence number check\r\n return needsUpdate;\r\n };\r\n Object.defineProperty(IndexedDbQueryCache.prototype, \"count\", {\r\n get: function () {\r\n return this.metadata.targetCount;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\r\n var _this = this;\r\n // Iterating by the canonicalId may yield more than one result because\r\n // canonicalId values are not required to be unique per target. This query\r\n // depends on the queryTargets index to be efficent.\r\n var canonicalId = query.canonicalId();\r\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\r\n var result = null;\r\n return targetsStore(transaction)\r\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\r\n var found = _this.serializer.fromDbTarget(value);\r\n // After finding a potential match, check that the query is\r\n // actually equal to the requested query.\r\n if (query.isEqual(found.query)) {\r\n result = found;\r\n control.done();\r\n }\r\n })\r\n .next(function () { return result; });\r\n };\r\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\r\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\r\n // Indexeddb.\r\n var promises = [];\r\n var store = documentTargetStore(txn);\r\n keys.forEach(function (key) {\r\n var path = encode(key.path);\r\n promises.push(store.put(new DbTargetDocument(targetId, path)));\r\n });\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\r\n var _this = this;\r\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\r\n // IndexedDb.\r\n var promises = [];\r\n var store = documentTargetStore(txn);\r\n keys.forEach(function (key) {\r\n var path = encode(key.path);\r\n promises.push(store.delete([targetId, path]));\r\n if (_this.garbageCollector !== null) {\r\n _this.garbageCollector.addPotentialGarbageKey(key);\r\n }\r\n });\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\r\n var store = documentTargetStore(txn);\r\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\r\n return store.delete(range);\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\r\n var _this = this;\r\n var store = documentTargetStore(txn);\r\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\r\n // In order to generate garbage events properly, we need to read these\r\n // keys before deleting.\r\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\r\n var path = decode(key[1]);\r\n var docKey = new DocumentKey(path);\r\n // Paranoid assertion in case the the collector is set to null\r\n // during the iteration.\r\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\r\n _this.garbageCollector.addPotentialGarbageKey(docKey);\r\n });\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n };\r\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\r\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n var store = documentTargetStore(txn);\r\n var result = documentKeySet();\r\n return store\r\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\r\n var path = decode(key[1]);\r\n var docKey = new DocumentKey(path);\r\n result = result.add(docKey);\r\n })\r\n .next(function () { return result; });\r\n };\r\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\r\n this.garbageCollector = gc;\r\n };\r\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\r\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\r\n var path = encode(key.path);\r\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n var count = 0;\r\n return documentTargetStore(txn)\r\n .iterate({\r\n index: DbTargetDocument.documentTargetsIndex,\r\n keysOnly: true,\r\n range: range\r\n }, function (key, _, control) {\r\n count++;\r\n control.done();\r\n })\r\n .next(function () { return count > 0; });\r\n };\r\n return IndexedDbQueryCache;\r\n}());\r\n/**\r\n * Helper to get a typed SimpleDbStore for the queries object store.\r\n */\r\nfunction targetsStore(txn) {\r\n return getStore$1(txn, DbTarget.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the target globals object store.\r\n */\r\nfunction globalTargetStore(txn) {\r\n return getStore$1(txn, DbTargetGlobal.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the document target object store.\r\n */\r\nfunction documentTargetStore(txn) {\r\n return getStore$1(txn, DbTargetDocument.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore from a transaction.\r\n */\r\nfunction getStore$1(txn, store) {\r\n if (txn instanceof SimpleDbTransaction) {\r\n return txn.store(store);\r\n }\r\n else {\r\n return fail('Invalid transaction object provided!');\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar IndexedDbRemoteDocumentCache = /** @class */ (function () {\r\n function IndexedDbRemoteDocumentCache(serializer) {\r\n this.serializer = serializer;\r\n }\r\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\r\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\r\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\r\n var _this = this;\r\n return remoteDocumentsStore(transaction)\r\n .get(dbKey(documentKey))\r\n .next(function (dbRemoteDoc) {\r\n return dbRemoteDoc\r\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\r\n : null;\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\r\n var _this = this;\r\n var results = documentMap();\r\n // Documents are ordered by key, so we can use a prefix scan to narrow down\r\n // the documents we need to match the query against.\r\n var startKey = query.path.toArray();\r\n var range = IDBKeyRange.lowerBound(startKey);\r\n return remoteDocumentsStore(transaction)\r\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\r\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\r\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\r\n control.done();\r\n }\r\n else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\r\n results = results.insert(maybeDoc.key, maybeDoc);\r\n }\r\n })\r\n .next(function () { return results; });\r\n };\r\n return IndexedDbRemoteDocumentCache;\r\n}());\r\n/**\r\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\r\n */\r\nfunction remoteDocumentsStore(txn) {\r\n if (txn instanceof SimpleDbTransaction) {\r\n return txn.store(DbRemoteDocument.store);\r\n }\r\n else {\r\n return fail('Invalid transaction object provided!');\r\n }\r\n}\r\nfunction dbKey(docKey) {\r\n return docKey.path.toArray();\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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/** Serializer for values stored in the LocalStore. */\r\nvar LocalSerializer = /** @class */ (function () {\r\n function LocalSerializer(remoteSerializer) {\r\n this.remoteSerializer = remoteSerializer;\r\n }\r\n /** Decodes a remote document from storage locally to a Document. */\r\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\r\n if (remoteDoc.document) {\r\n return this.remoteSerializer.fromDocument(remoteDoc.document);\r\n }\r\n else if (remoteDoc.noDocument) {\r\n var key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\r\n var readTime = remoteDoc.noDocument.readTime;\r\n var timestamp = new Timestamp(readTime.seconds, readTime.nanoseconds);\r\n return new NoDocument(key, SnapshotVersion.fromTimestamp(timestamp));\r\n }\r\n else {\r\n return fail('Unexpected DbRemoteDocument');\r\n }\r\n };\r\n /** Encodes a document for storage locally. */\r\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\r\n if (maybeDoc instanceof Document) {\r\n var doc = this.remoteSerializer.toDocument(maybeDoc);\r\n return new DbRemoteDocument(null, doc);\r\n }\r\n else {\r\n var path = maybeDoc.key.path.toArray();\r\n var timestamp = maybeDoc.version.toTimestamp();\r\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanoseconds);\r\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\r\n }\r\n };\r\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\r\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\r\n var _this = this;\r\n var serializedMutations = batch.mutations.map(function (m) {\r\n return _this.remoteSerializer.toMutation(m);\r\n });\r\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toMillis(), serializedMutations);\r\n };\r\n /** Decodes a DbMutationBatch into a MutationBatch */\r\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\r\n var _this = this;\r\n var mutations = dbBatch.mutations.map(function (m) {\r\n return _this.remoteSerializer.fromMutation(m);\r\n });\r\n var timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\r\n return new MutationBatch(dbBatch.batchId, timestamp, mutations);\r\n };\r\n /** Decodes a DbTarget into QueryData */\r\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\r\n var readTime = new Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanoseconds);\r\n var version = SnapshotVersion.fromTimestamp(readTime);\r\n var query;\r\n if (isDocumentQuery(dbTarget.query)) {\r\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\r\n }\r\n else {\r\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\r\n }\r\n return new QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\r\n };\r\n /** Encodes QueryData into a DbTarget for storage locally. */\r\n LocalSerializer.prototype.toDbTarget = function (queryData) {\r\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\r\n QueryPurpose.Listen +\r\n ' may be stored, got ' +\r\n queryData.purpose);\r\n var timestamp = queryData.snapshotVersion.toTimestamp();\r\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanoseconds);\r\n var queryProto;\r\n if (queryData.query.isDocumentQuery()) {\r\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\r\n }\r\n else {\r\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\r\n }\r\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\r\n var resumeToken = queryData.resumeToken;\r\n // lastListenSequenceNumber is always 0 until we do real GC.\r\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\r\n };\r\n return LocalSerializer;\r\n}());\r\n/**\r\n * A helper function for figuring out what kind of query has been stored.\r\n */\r\nfunction isDocumentQuery(dbQuery) {\r\n return dbQuery.documents !== undefined;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$3 = 'IndexedDbPersistence';\r\n/** If the owner lease is older than 5 seconds, try to take ownership. */\r\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\r\n/** Refresh the owner lease every 4 seconds while owner. */\r\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\r\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\r\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\r\n/** Error when the owner lease cannot be acquired or is lost. */\r\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\r\n ' persistence enabled. Only one such tab is allowed at a time. The' +\r\n ' other tab must be closed or persistence must be disabled.';\r\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\r\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\r\n ' persistence has been disabled.';\r\n/**\r\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\r\n * across sessions.\r\n *\r\n * Currently the Firestore SDK only supports a single consumer of the database,\r\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\r\n * single consumer of the database via an \"owner lease\" stored in the database.\r\n *\r\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\r\n * it to a special \"owner\" object in the database (if no entry exists already or\r\n * the current entry is expired). This owner lease is then verified inside every\r\n * transaction to ensure the lease has not been lost.\r\n *\r\n * If a tab opts not to acquire the owner lease (because there's an existing\r\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\r\n * failed state and all subsequent operations will automatically fail.\r\n *\r\n * The current owner regularly refreshes the owner lease with new timestamps to\r\n * prevent newly-opened tabs from taking over ownership.\r\n *\r\n * Additionally there is an optimization so that when a tab is closed, the owner\r\n * lease is released immediately (this is especially important to make sure that\r\n * a refreshed tab is able to immediately re-acquire the owner lease).\r\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\r\n * an asynchronous API. So in addition to attempting to give up the lease,\r\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\r\n * which acts as an indicator that another tab should go ahead and take the\r\n * owner lease immediately regardless of the current lease timestamp.\r\n */\r\nvar IndexedDbPersistence = /** @class */ (function () {\r\n function IndexedDbPersistence(prefix, serializer) {\r\n this.ownerId = this.generateOwnerId();\r\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\r\n this.serializer = new LocalSerializer(serializer);\r\n this.localStoragePrefix = prefix;\r\n }\r\n IndexedDbPersistence.prototype.start = function () {\r\n var _this = this;\r\n if (!IndexedDbPersistence.isAvailable()) {\r\n this.persistenceError = new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\r\n return Promise.reject(this.persistenceError);\r\n }\r\n assert(!this.started, 'IndexedDbPersistence double-started!');\r\n this.started = true;\r\n return SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\r\n .then(function (db) {\r\n _this.simpleDb = db;\r\n })\r\n .then(function () { return _this.tryAcquireOwnerLease(); })\r\n .then(function () {\r\n _this.scheduleOwnerLeaseRefreshes();\r\n _this.attachWindowUnloadHook();\r\n });\r\n };\r\n IndexedDbPersistence.prototype.shutdown = function () {\r\n var _this = this;\r\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\r\n this.started = false;\r\n this.detachWindowUnloadHook();\r\n this.stopOwnerLeaseRefreshes();\r\n return this.releaseOwnerLease().then(function () {\r\n _this.simpleDb.close();\r\n });\r\n };\r\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\r\n return IndexedDbMutationQueue.forUser(user, this.serializer);\r\n };\r\n IndexedDbPersistence.prototype.getQueryCache = function () {\r\n return new IndexedDbQueryCache(this.serializer);\r\n };\r\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\r\n return new IndexedDbRemoteDocumentCache(this.serializer);\r\n };\r\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\r\n var _this = this;\r\n if (this.persistenceError) {\r\n return Promise.reject(this.persistenceError);\r\n }\r\n debug(LOG_TAG$3, 'Starting transaction:', action);\r\n // Do all transactions as readwrite against all object stores, since we\r\n // are the only reader/writer.\r\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\r\n // Verify that we still have the owner lease as part of every transaction.\r\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\r\n });\r\n };\r\n IndexedDbPersistence.isAvailable = function () {\r\n return SimpleDb.isAvailable();\r\n };\r\n /**\r\n * Generates a string used as a prefix when storing data in IndexedDB and\r\n * LocalStorage.\r\n */\r\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\r\n // Use two different prefix formats:\r\n //\r\n // * firestore / persistenceKey / projectID . databaseID / ...\r\n // * firestore / persistenceKey / projectID / ...\r\n //\r\n // projectIDs are DNS-compatible names and cannot contain dots\r\n // so there's no danger of collisions.\r\n var database = databaseInfo.databaseId.projectId;\r\n if (!databaseInfo.databaseId.isDefaultDatabase) {\r\n database += '.' + databaseInfo.databaseId.database;\r\n }\r\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\r\n };\r\n /**\r\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\r\n * promise.\r\n */\r\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\r\n var _this = this;\r\n // NOTE: Don't use this.runTransaction, since it requires us to already\r\n // have the lease.\r\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\r\n var store = txn.store(DbOwner.store);\r\n return store.get('owner').next(function (dbOwner) {\r\n if (!_this.validOwner(dbOwner)) {\r\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\r\n debug(LOG_TAG$3, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\r\n return store.put('owner', newDbOwner);\r\n }\r\n else {\r\n debug(LOG_TAG$3, 'Valid owner already. Failing. Current owner:', dbOwner);\r\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\r\n return PersistencePromise.reject(_this.persistenceError);\r\n }\r\n });\r\n });\r\n };\r\n /** Checks the owner lease and deletes it if we are the current owner. */\r\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\r\n var _this = this;\r\n // NOTE: Don't use this.runTransaction, since it requires us to already\r\n // have the lease.\r\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\r\n var store = txn.store(DbOwner.store);\r\n return store.get('owner').next(function (dbOwner) {\r\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\r\n debug(LOG_TAG$3, 'Releasing owner lease.');\r\n return store.delete('owner');\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Checks the owner lease and returns a rejected promise if we are not the\r\n * current owner. This should be included in every transaction to guard\r\n * against losing the owner lease.\r\n */\r\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\r\n var _this = this;\r\n var store = txn.store(DbOwner.store);\r\n return store.get('owner').next(function (dbOwner) {\r\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\r\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\r\n return PersistencePromise.reject(_this.persistenceError);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n };\r\n /**\r\n * Returns true if the provided owner exists, has a recent timestamp, and\r\n * isn't zombied.\r\n *\r\n * NOTE: To determine if the owner is zombied, this method reads from\r\n * LocalStorage which could be mildly expensive.\r\n */\r\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\r\n var now = Date.now();\r\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\r\n var maxAcceptable = now;\r\n if (dbOwner === null) {\r\n return false; // no owner.\r\n }\r\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\r\n return false; // owner lease has expired.\r\n }\r\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\r\n error('Persistence owner-lease is in the future. Discarding.', dbOwner);\r\n return false;\r\n }\r\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\r\n return false; // owner's tab closed.\r\n }\r\n else {\r\n return true;\r\n }\r\n };\r\n /**\r\n * Schedules a recurring timer to update the owner lease timestamp to prevent\r\n * other tabs from taking the lease.\r\n */\r\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\r\n var _this = this;\r\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\r\n // would increase the chances of us not refreshing on time if the queue is\r\n // backed up for some reason.\r\n this.ownerLeaseRefreshHandle = setInterval(function () {\r\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\r\n // NOTE: We don't need to validate the current owner contents, since\r\n // runTransaction does that automatically.\r\n var store = txn.store(DbOwner.store);\r\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\r\n });\r\n txResult.catch(function (reason) {\r\n // Probably means we lost the lease. Report the error and stop trying to\r\n // refresh the lease.\r\n error(reason);\r\n _this.stopOwnerLeaseRefreshes();\r\n });\r\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\r\n };\r\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\r\n if (this.ownerLeaseRefreshHandle) {\r\n clearInterval(this.ownerLeaseRefreshHandle);\r\n this.ownerLeaseRefreshHandle = null;\r\n }\r\n };\r\n /**\r\n * Attaches a window.unload handler that will synchronously write our\r\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\r\n * by tabs trying to acquire the lease to determine that the lease should be\r\n * acquired immediately even if the timestamp is recent. This is particularly\r\n * important for the refresh case (so the tab correctly re-acquires the owner\r\n * lease). LocalStorage is used for this rather than IndexedDb because it is\r\n * a synchronous API and so can be used reliably from an unload handler.\r\n */\r\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\r\n var _this = this;\r\n this.windowUnloadHandler = function () {\r\n // Record that we're zombied.\r\n _this.setZombiedOwnerId(_this.ownerId);\r\n // Attempt graceful shutdown (including releasing our owner lease), but\r\n // there's no guarantee it will complete.\r\n _this.shutdown();\r\n };\r\n window.addEventListener('unload', this.windowUnloadHandler);\r\n };\r\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\r\n if (this.windowUnloadHandler) {\r\n window.removeEventListener('unload', this.windowUnloadHandler);\r\n this.windowUnloadHandler = null;\r\n }\r\n };\r\n /**\r\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\r\n * zombied due to their tab closing) from LocalStorage, or null if no such\r\n * record exists.\r\n */\r\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\r\n try {\r\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\r\n debug(LOG_TAG$3, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\r\n return zombiedOwnerId;\r\n }\r\n catch (e) {\r\n // Gracefully handle if LocalStorage isn't available / working.\r\n error('Failed to get zombie owner id.', e);\r\n return null;\r\n }\r\n };\r\n /**\r\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\r\n * or, if passed null, deletes any recorded zombied owner.\r\n */\r\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\r\n try {\r\n if (zombieOwnerId === null) {\r\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\r\n }\r\n else {\r\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\r\n }\r\n }\r\n catch (e) {\r\n // Gracefully handle if LocalStorage isn't available / working.\r\n error('Failed to set zombie owner id.', e);\r\n }\r\n };\r\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\r\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\r\n };\r\n IndexedDbPersistence.prototype.generateOwnerId = function () {\r\n // For convenience, just use an AutoId.\r\n return AutoId.newId();\r\n };\r\n /**\r\n * The name of the main (and currently only) IndexedDB database. this name is\r\n * appended to the prefix provided to the IndexedDbPersistence constructor.\r\n */\r\n IndexedDbPersistence.MAIN_DATABASE = 'main';\r\n return IndexedDbPersistence;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A readonly view of the local state of all documents we're tracking (i.e. we\r\n * have a cached version in remoteDocumentCache or local mutations for the\r\n * document). The view is computed by applying the mutations in the\r\n * MutationQueue to the RemoteDocumentCache.\r\n */\r\nvar LocalDocumentsView = /** @class */ (function () {\r\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\r\n this.remoteDocumentCache = remoteDocumentCache;\r\n this.mutationQueue = mutationQueue;\r\n }\r\n /**\r\n * Get the local view of the document identified by `key`.\r\n *\r\n * @return Local view of the document or null if we don't have any cached\r\n * state for it.\r\n */\r\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\r\n var _this = this;\r\n return this.remoteDocumentCache\r\n .getEntry(transaction, key)\r\n .next(function (remoteDoc) {\r\n return _this.computeLocalDocument(transaction, key, remoteDoc);\r\n });\r\n };\r\n /**\r\n * Gets the local view of the documents identified by `keys`.\r\n *\r\n * If we don't have cached state for a document in `keys`, a NoDocument will\r\n * be stored for that key in the resulting set.\r\n */\r\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\r\n var _this = this;\r\n var promises = [];\r\n var results = maybeDocumentMap();\r\n keys.forEach(function (key) {\r\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\r\n // TODO(http://b/32275378): Don't conflate missing / deleted.\r\n if (!maybeDoc) {\r\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\r\n }\r\n results = results.insert(key, maybeDoc);\r\n }));\r\n });\r\n return PersistencePromise.waitFor(promises).next(function () { return results; });\r\n };\r\n /** Performs a query against the local view of all documents. */\r\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\r\n if (DocumentKey.isDocumentKey(query.path)) {\r\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\r\n }\r\n else {\r\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\r\n }\r\n };\r\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\r\n // Just do a simple document lookup.\r\n return this.getDocument(transaction, new DocumentKey(docPath)).next(function (maybeDoc) {\r\n var result = documentMap();\r\n if (maybeDoc instanceof Document) {\r\n result = result.insert(maybeDoc.key, maybeDoc);\r\n }\r\n return result;\r\n });\r\n };\r\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\r\n var _this = this;\r\n // Query the remote documents and overlay mutations.\r\n // TODO(mikelehen): There may be significant overlap between the mutations\r\n // affecting these remote documents and the\r\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\r\n var results;\r\n return this.remoteDocumentCache\r\n .getDocumentsMatchingQuery(transaction, query)\r\n .next(function (queryResults) {\r\n return _this.computeLocalDocuments(transaction, queryResults);\r\n })\r\n .next(function (promisedResults) {\r\n results = promisedResults;\r\n // Now use the mutation queue to discover any other documents that may\r\n // match the query after applying mutations.\r\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\r\n })\r\n .next(function (matchingMutationBatches) {\r\n var matchingKeys = documentKeySet();\r\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\r\n var batch = matchingMutationBatches_1[_i];\r\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\r\n var mutation = _b[_a];\r\n // TODO(mikelehen): PERF: Check if this mutation actually\r\n // affects the query to reduce work.\r\n if (!results.get(mutation.key)) {\r\n matchingKeys = matchingKeys.add(mutation.key);\r\n }\r\n }\r\n }\r\n // Now add in the results for the matchingKeys.\r\n var promises = [];\r\n matchingKeys.forEach(function (key) {\r\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\r\n if (doc instanceof Document) {\r\n results = results.insert(doc.key, doc);\r\n }\r\n }));\r\n });\r\n return PersistencePromise.waitFor(promises);\r\n })\r\n .next(function () {\r\n // Finally, filter out any documents that don't actually match\r\n // the query.\r\n results.forEach(function (key, doc) {\r\n if (!query.matches(doc)) {\r\n results = results.remove(key);\r\n }\r\n });\r\n return results;\r\n });\r\n };\r\n /**\r\n * Takes a remote document and applies local mutations to generate the local\r\n * view of the document.\r\n * @param transaction The transaction in which to perform any persistence\r\n * operations.\r\n * @param documentKey The key of the document (necessary when remoteDocument\r\n * is null).\r\n * @param document The base remote document to apply mutations to or null.\r\n */\r\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\r\n return this.mutationQueue\r\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\r\n .next(function (batches) {\r\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\r\n var batch = batches_1[_i];\r\n document = batch.applyToLocalView(documentKey, document);\r\n }\r\n return document;\r\n });\r\n };\r\n /**\r\n * Takes a set of remote documents and applies local mutations to generate the\r\n * local view of the documents.\r\n * @param transaction The transaction in which to perform any persistence\r\n * operations.\r\n * @param documents The base remote documents to apply mutations to.\r\n * @return The local view of the documents.\r\n */\r\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\r\n var _this = this;\r\n var promises = [];\r\n documents.forEach(function (key, doc) {\r\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\r\n if (mutatedDoc instanceof Document) {\r\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\r\n }\r\n else if (mutatedDoc instanceof NoDocument) {\r\n documents = documents.remove(mutatedDoc.key);\r\n }\r\n else {\r\n fail('Unknown MaybeDocument: ' + mutatedDoc);\r\n }\r\n }));\r\n });\r\n return PersistencePromise.waitFor(promises).next(function () { return documents; });\r\n };\r\n return LocalDocumentsView;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * An in-memory buffer of entries to be written to a RemoteDocumentCache.\r\n * It can be used to batch up a set of changes to be written to the cache, but\r\n * additionally supports reading entries back with the `getEntry()` method,\r\n * falling back to the underlying RemoteDocumentCache if no entry is\r\n * buffered.\r\n *\r\n * NOTE: This class was introduced in iOS to work around a limitation in\r\n * LevelDB. Given IndexedDb has full transaction support with\r\n * read-your-own-writes capability, this class is not technically needed, but\r\n * has been preserved as a convenience and to aid portability.\r\n */\r\nvar RemoteDocumentChangeBuffer = /** @class */ (function () {\r\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\r\n this.remoteDocumentCache = remoteDocumentCache;\r\n this.changes = maybeDocumentMap();\r\n }\r\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\r\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\r\n var changes = this.assertChanges();\r\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\r\n };\r\n // NOTE: removeEntry() is not presently necessary and so is omitted.\r\n /**\r\n * Looks up an entry in the cache. The buffered changes will first be checked,\r\n * and if no buffered change applies, this will forward to\r\n * `RemoteDocumentCache.getEntry()`.\r\n *\r\n * @param transaction The transaction in which to perform any persistence\r\n * operations.\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached Document or NoDocument entry, or null if we have nothing\r\n * cached.\r\n */\r\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\r\n var changes = this.assertChanges();\r\n var bufferedEntry = changes.get(documentKey);\r\n if (bufferedEntry) {\r\n return PersistencePromise.resolve(bufferedEntry);\r\n }\r\n else {\r\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\r\n }\r\n };\r\n /**\r\n * Applies buffered changes to the underlying RemoteDocumentCache, using\r\n * the provided transaction.\r\n */\r\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\r\n var _this = this;\r\n var changes = this.assertChanges();\r\n var promises = [];\r\n changes.forEach(function (key, maybeDoc) {\r\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\r\n });\r\n // We should not be used to buffer any more changes.\r\n this.changes = null;\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n /** Helper to assert this.changes is not null and return it. */\r\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\r\n assert(this.changes !== null, 'Changes have already been applied.');\r\n return this.changes;\r\n };\r\n return RemoteDocumentChangeBuffer;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$4 = 'LocalStore';\r\n/**\r\n * Local storage in the Firestore client. Coordinates persistence components\r\n * like the mutation queue and remote document cache to present a\r\n * latency-compensated view of stored data.\r\n *\r\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\r\n * Writes from the client are put into a queue as provisional Mutations until\r\n * they are processed by the RemoteStore and confirmed as having been written\r\n * to the server.\r\n *\r\n * The local store provides the local version of documents that have been\r\n * modified locally. It maintains the constraint:\r\n *\r\n * LocalDocument = RemoteDocument + Active(LocalMutations)\r\n *\r\n * (Active mutations are those that are enqueued and have not been previously\r\n * acknowledged or rejected).\r\n *\r\n * The RemoteDocument (\"ground truth\") state is provided via the\r\n * applyChangeBatch method. It will be some version of a server-provided\r\n * document OR will be a server-provided document PLUS acknowledged mutations:\r\n *\r\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\r\n *\r\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\r\n * server base version, since it has LocalMutations added to it pending getting\r\n * an authoritative copy from the server.\r\n *\r\n * Since LocalMutations can be rejected by the server, we have to be able to\r\n * revert a LocalMutation that has already been applied to the LocalDocument\r\n * (typically done by replaying all remaining LocalMutations to the\r\n * RemoteDocument to re-apply).\r\n *\r\n * The LocalStore is responsible for the garbage collection of the documents it\r\n * contains. For now, it every doc referenced by a view, the mutation queue, or\r\n * the RemoteStore.\r\n *\r\n * It also maintains the persistence of mapping queries to resume tokens and\r\n * target ids. It needs to know this data about queries to properly know what\r\n * docs it would be allowed to garbage collect.\r\n *\r\n * The LocalStore must be able to efficiently execute queries against its local\r\n * cache of the documents, to provide the initial set of results before any\r\n * remote changes have been received.\r\n *\r\n * Note: In TypeScript, most methods return Promises since the implementation\r\n * may rely on fetching data from IndexedDB which is async.\r\n * These Promises will only be rejected on an I/O error or other internal\r\n * (unexpected) failure (e.g. failed assert) and always represent an\r\n * unrecoverable error (should be caught / reported by the async_queue).\r\n */\r\nvar LocalStore = /** @class */ (function () {\r\n function LocalStore(\r\n /** Manages our in-memory or durable persistence. */\r\n persistence, initialUser, \r\n /**\r\n * The garbage collector collects documents that should no longer be\r\n * cached (e.g. if they are no longer retained by the above reference sets\r\n * and the garbage collector is performing eager collection).\r\n */\r\n garbageCollector) {\r\n this.persistence = persistence;\r\n this.garbageCollector = garbageCollector;\r\n /**\r\n * The set of document references maintained by any local views.\r\n */\r\n this.localViewReferences = new ReferenceSet();\r\n /** Maps a targetID to data about its query. */\r\n this.targetIds = {};\r\n /** Used to generate targetIDs for queries tracked locally. */\r\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\r\n /**\r\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\r\n * that arrived before the watch stream got notified of a snapshot that\r\n * includes the write. So we \"hold\" it until the watch stream catches up. It\r\n * ensures that the local write remains visible (latency compensation) and\r\n * doesn't temporarily appear reverted because the watch stream is slower than\r\n * the write stream and so wasn't reflecting it.\r\n *\r\n * NOTE: Eventually we want to move this functionality into the remote store.\r\n */\r\n this.heldBatchResults = [];\r\n this.mutationQueue = persistence.getMutationQueue(initialUser);\r\n this.remoteDocuments = persistence.getRemoteDocumentCache();\r\n this.queryCache = persistence.getQueryCache();\r\n this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\r\n this.garbageCollector.addGarbageSource(this.localViewReferences);\r\n this.garbageCollector.addGarbageSource(this.queryCache);\r\n this.garbageCollector.addGarbageSource(this.mutationQueue);\r\n }\r\n /** Performs any initial startup actions required by the local store. */\r\n LocalStore.prototype.start = function () {\r\n var _this = this;\r\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\r\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\r\n });\r\n };\r\n /**\r\n * Tells the LocalStore that the currently authenticated user has changed.\r\n *\r\n * In response the local store switches the mutation queue to the new user and\r\n * returns any resulting document changes.\r\n */\r\n LocalStore.prototype.handleUserChange = function (user) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Handle user change', function (txn) {\r\n // Swap out the mutation queue, grabbing the pending mutation batches\r\n // before and after.\r\n var oldBatches;\r\n return _this.mutationQueue\r\n .getAllMutationBatches(txn)\r\n .next(function (promisedOldBatches) {\r\n oldBatches = promisedOldBatches;\r\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\r\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\r\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\r\n return _this.startMutationQueue(txn);\r\n })\r\n .next(function () {\r\n // Recreate our LocalDocumentsView using the new\r\n // MutationQueue.\r\n _this.localDocuments = new LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\r\n return _this.mutationQueue.getAllMutationBatches(txn);\r\n })\r\n .next(function (newBatches) {\r\n // Union the old/new changed keys.\r\n var changedKeys = documentKeySet();\r\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\r\n var batches = _a[_i];\r\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\r\n var batch = batches_1[_b];\r\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\r\n var mutation = _d[_c];\r\n changedKeys = changedKeys.add(mutation.key);\r\n }\r\n }\r\n }\r\n // Return the set of all (potentially) changed documents as the\r\n // result of the user change.\r\n return _this.localDocuments.getDocuments(txn, changedKeys);\r\n });\r\n });\r\n };\r\n LocalStore.prototype.startQueryCache = function (txn) {\r\n var _this = this;\r\n return this.queryCache.start(txn).next(function () {\r\n var targetId = _this.queryCache.getHighestTargetId();\r\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\r\n });\r\n };\r\n LocalStore.prototype.startMutationQueue = function (txn) {\r\n var _this = this;\r\n return this.mutationQueue\r\n .start(txn)\r\n .next(function () {\r\n // If we have any leftover mutation batch results from a prior run,\r\n // just drop them.\r\n // TODO(http://b/33446471): We probably need to repopulate\r\n // heldBatchResults or similar instead, but that is not\r\n // straightforward since we're not persisting the write ack versions.\r\n _this.heldBatchResults = [];\r\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\r\n })\r\n .next(function (highestAck) {\r\n // TODO(mikelehen): This is the only usage of\r\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\r\n // favor of a getAcknowledgedBatches() method.\r\n if (highestAck !== BATCHID_UNKNOWN) {\r\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\r\n }\r\n else {\r\n return PersistencePromise.resolve([]);\r\n }\r\n })\r\n .next(function (ackedBatches) {\r\n if (ackedBatches.length > 0) {\r\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n };\r\n /* Accept locally generated Mutations and commit them to storage. */\r\n LocalStore.prototype.localWrite = function (mutations) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\r\n var batch;\r\n var localWriteTime = Timestamp.now();\r\n return _this.mutationQueue\r\n .addMutationBatch(txn, localWriteTime, mutations)\r\n .next(function (promisedBatch) {\r\n batch = promisedBatch;\r\n // TODO(koss): This is doing an N^2 update by replaying ALL the\r\n // mutations on each document (instead of just the ones added) in\r\n // this batch.\r\n var keys = batch.keys();\r\n return _this.localDocuments.getDocuments(txn, keys);\r\n })\r\n .next(function (changedDocuments) {\r\n return { batchId: batch.batchId, changes: changedDocuments };\r\n });\r\n });\r\n };\r\n /**\r\n * Acknowledge the given batch.\r\n *\r\n * On the happy path when a batch is acknowledged, the local store will\r\n *\r\n * + remove the batch from the mutation queue;\r\n * + apply the changes to the remote document cache;\r\n * + recalculate the latency compensated view implied by those changes (there\r\n * may be mutations in the queue that affect the documents but haven't been\r\n * acknowledged yet); and\r\n * + give the changed documents back the sync engine\r\n *\r\n * @returns The resulting (modified) documents.\r\n */\r\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\r\n var affected;\r\n return _this.mutationQueue\r\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\r\n .next(function () {\r\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\r\n _this.heldBatchResults.push(batchResult);\r\n affected = documentKeySet();\r\n return PersistencePromise.resolve();\r\n }\r\n else {\r\n var documentBuffer_1 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\r\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\r\n affected = promisedAffectedKeys;\r\n return documentBuffer_1.apply(txn);\r\n });\r\n }\r\n })\r\n .next(function () {\r\n return _this.mutationQueue.performConsistencyCheck(txn);\r\n })\r\n .next(function () {\r\n return _this.localDocuments.getDocuments(txn, affected);\r\n });\r\n });\r\n };\r\n /**\r\n * Remove mutations from the MutationQueue for the specified batch;\r\n * LocalDocuments will be recalculated.\r\n *\r\n * @returns The resulting modified documents.\r\n */\r\n LocalStore.prototype.rejectBatch = function (batchId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Reject batch', function (txn) {\r\n var toReject;\r\n var affectedKeys;\r\n return _this.mutationQueue\r\n .lookupMutationBatch(txn, batchId)\r\n .next(function (promisedToReject) {\r\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\r\n toReject = promisedToReject;\r\n return _this.mutationQueue\r\n .getHighestAcknowledgedBatchId(txn)\r\n .next(function (lastAcked) {\r\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\r\n return toReject;\r\n });\r\n })\r\n .next(function () {\r\n return _this.removeMutationBatch(txn, toReject);\r\n })\r\n .next(function (promisedAffectedKeys) {\r\n affectedKeys = promisedAffectedKeys;\r\n return _this.mutationQueue.performConsistencyCheck(txn);\r\n })\r\n .next(function () {\r\n return _this.localDocuments.getDocuments(txn, affectedKeys);\r\n });\r\n });\r\n };\r\n /** Returns the last recorded stream token for the current user. */\r\n LocalStore.prototype.getLastStreamToken = function () {\r\n var _this = this;\r\n return this.persistence.runTransaction('Get last stream token', function (txn) {\r\n return _this.mutationQueue.getLastStreamToken(txn);\r\n });\r\n };\r\n /**\r\n * Sets the stream token for the current user without acknowledging any\r\n * mutation batch. This is usually only useful after a stream handshake or in\r\n * response to an error that requires clearing the stream token.\r\n */\r\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Set last stream token', function (txn) {\r\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\r\n });\r\n };\r\n /**\r\n * Returns the last consistent snapshot processed (used by the RemoteStore to\r\n * determine whether to buffer incoming snapshots from the backend).\r\n */\r\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\r\n return this.queryCache.getLastRemoteSnapshotVersion();\r\n };\r\n /**\r\n * Update the \"ground-state\" (remote) documents. We assume that the remote\r\n * event reflects any write batches that have been acknowledged or rejected\r\n * (i.e. we do not re-apply local mutations to updates from this event).\r\n *\r\n * LocalDocuments are re-calculated if there are remaining mutations in the\r\n * queue.\r\n */\r\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\r\n var _this = this;\r\n var documentBuffer = new RemoteDocumentChangeBuffer(this.remoteDocuments);\r\n return this.persistence.runTransaction('Apply remote event', function (txn) {\r\n var promises = [];\r\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\r\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\r\n var queryData = _this.targetIds[targetId];\r\n if (!queryData)\r\n return;\r\n var mapping = change.mapping;\r\n if (mapping) {\r\n // First make sure that all references are deleted\r\n if (mapping instanceof ResetMapping) {\r\n promises.push(_this.queryCache\r\n .removeMatchingKeysForTargetId(txn, targetId)\r\n .next(function () {\r\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\r\n }));\r\n }\r\n else if (mapping instanceof UpdateMapping) {\r\n promises.push(_this.queryCache\r\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\r\n .next(function () {\r\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\r\n }));\r\n }\r\n else {\r\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\r\n }\r\n }\r\n // Update the resume token if the change includes one. Don't clear\r\n // any preexisting value.\r\n var resumeToken = change.resumeToken;\r\n if (resumeToken.length > 0) {\r\n queryData = queryData.update({\r\n resumeToken: resumeToken,\r\n snapshotVersion: change.snapshotVersion\r\n });\r\n _this.targetIds[targetId] = queryData;\r\n promises.push(_this.queryCache.updateQueryData(txn, queryData));\r\n }\r\n });\r\n var changedDocKeys = documentKeySet();\r\n remoteEvent.documentUpdates.forEach(function (key, doc) {\r\n changedDocKeys = changedDocKeys.add(key);\r\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\r\n // Make sure we don't apply an old document version to the remote\r\n // cache, though we make an exception for SnapshotVersion.MIN which\r\n // can happen for manufactured events (e.g. in the case of a limbo\r\n // document resolution failing).\r\n if (existingDoc == null ||\r\n doc.version.isEqual(SnapshotVersion.MIN) ||\r\n doc.version.compareTo(existingDoc.version) >= 0) {\r\n documentBuffer.addEntry(doc);\r\n }\r\n else {\r\n debug(LOG_TAG$4, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\r\n }\r\n // The document might be garbage because it was unreferenced by\r\n // everything. Make sure to mark it as garbage if it is...\r\n _this.garbageCollector.addPotentialGarbageKey(key);\r\n }));\r\n });\r\n // HACK: The only reason we allow a null snapshot version is so that we\r\n // can synthesize remote events when we get permission denied errors while\r\n // trying to resolve the state of a locally cached document that is in\r\n // limbo.\r\n var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\r\n var remoteVersion = remoteEvent.snapshotVersion;\r\n if (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\r\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\r\n remoteVersion +\r\n ' < ' +\r\n lastRemoteVersion);\r\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\r\n }\r\n var releasedWriteKeys;\r\n return PersistencePromise.waitFor(promises)\r\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\r\n .next(function (promisedReleasedWriteKeys) {\r\n releasedWriteKeys = promisedReleasedWriteKeys;\r\n return documentBuffer.apply(txn);\r\n })\r\n .next(function () {\r\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\r\n });\r\n });\r\n };\r\n /**\r\n * Notify local store of the changed views to locally pin documents.\r\n */\r\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\r\n var promises = [];\r\n var _loop_1 = function (view) {\r\n promises.push(_this.queryCache\r\n .getQueryData(txn, view.query)\r\n .next(function (queryData) {\r\n assert(queryData !== null, 'Local view changes contain unallocated query.');\r\n var targetId = queryData.targetId;\r\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\r\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\r\n }));\r\n };\r\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\r\n var view = viewChanges_1[_i];\r\n _loop_1(view);\r\n }\r\n return PersistencePromise.waitFor(promises);\r\n });\r\n };\r\n /**\r\n * Gets the mutation batch after the passed in batchId in the mutation queue\r\n * or null if empty.\r\n * @param afterBatchId If provided, the batch to search after.\r\n * @returns The next mutation or null if there wasn't one.\r\n */\r\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\r\n if (afterBatchId === undefined) {\r\n afterBatchId = BATCHID_UNKNOWN;\r\n }\r\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\r\n });\r\n };\r\n /**\r\n * Read the current value of a Document with a given key or null if not\r\n * found - used for testing.\r\n */\r\n LocalStore.prototype.readDocument = function (key) {\r\n var _this = this;\r\n return this.persistence.runTransaction('read document', function (txn) {\r\n return _this.localDocuments.getDocument(txn, key);\r\n });\r\n };\r\n /**\r\n * Assigns the given query an internal ID so that its results can be pinned so\r\n * they don't get GC'd. A query must be allocated in the local store before\r\n * the store can be used to manage its view.\r\n */\r\n LocalStore.prototype.allocateQuery = function (query) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Allocate query', function (txn) {\r\n var queryData;\r\n return _this.queryCache\r\n .getQueryData(txn, query)\r\n .next(function (cached) {\r\n if (cached) {\r\n // This query has been listened to previously, so reuse the\r\n // previous targetID.\r\n // TODO(mcg): freshen last accessed date?\r\n queryData = cached;\r\n return PersistencePromise.resolve();\r\n }\r\n else {\r\n var targetId = _this.targetIdGenerator.next();\r\n queryData = new QueryData(query, targetId, QueryPurpose.Listen);\r\n return _this.queryCache.addQueryData(txn, queryData);\r\n }\r\n })\r\n .next(function () {\r\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\r\n _this.targetIds[queryData.targetId] = queryData;\r\n return queryData;\r\n });\r\n });\r\n };\r\n /** Unpin all the documents associated with the given query. */\r\n LocalStore.prototype.releaseQuery = function (query) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Release query', function (txn) {\r\n return _this.queryCache\r\n .getQueryData(txn, query)\r\n .next(function (queryData) {\r\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\r\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\r\n delete _this.targetIds[queryData.targetId];\r\n if (_this.garbageCollector.isEager) {\r\n return _this.queryCache.removeQueryData(txn, queryData);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n })\r\n .next(function () {\r\n // If this was the last watch target, then we won't get any more\r\n // watch snapshots, so we should release any held batch results.\r\n if (isEmpty(_this.targetIds)) {\r\n var documentBuffer_2 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\r\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\r\n documentBuffer_2.apply(txn);\r\n });\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Runs the specified query against all the documents in the local store and\r\n * returns the results.\r\n */\r\n LocalStore.prototype.executeQuery = function (query) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Execute query', function (txn) {\r\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\r\n });\r\n };\r\n /**\r\n * Returns the keys of the documents that are associated with the given\r\n * target id in the remote table.\r\n */\r\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Remote document keys', function (txn) {\r\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\r\n });\r\n };\r\n /**\r\n * Collect garbage if necessary.\r\n * Should be called periodically by Sync Engine to recover resources. The\r\n * implementation must guarantee that GC won't happen in other places than\r\n * this method call.\r\n */\r\n LocalStore.prototype.collectGarbage = function () {\r\n var _this = this;\r\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\r\n // doesn't continue to accumulate the garbage keys.\r\n return this.persistence.runTransaction('Garbage collection', function (txn) {\r\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\r\n var promises = [];\r\n garbage.forEach(function (key) {\r\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\r\n });\r\n return PersistencePromise.waitFor(promises);\r\n });\r\n });\r\n };\r\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\r\n var toRelease = [];\r\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\r\n var batchResult = _a[_i];\r\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\r\n break;\r\n }\r\n toRelease.push(batchResult);\r\n }\r\n if (toRelease.length === 0) {\r\n return PersistencePromise.resolve(documentKeySet());\r\n }\r\n else {\r\n this.heldBatchResults.splice(0, toRelease.length);\r\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\r\n }\r\n };\r\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\r\n // If there are no watch targets, then we won't get remote snapshots, and\r\n // we are always \"up-to-date.\"\r\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\r\n return (version.compareTo(lastRemoteVersion) <= 0 ||\r\n isEmpty(this.targetIds));\r\n };\r\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\r\n // Check if watcher isn't up to date or prior results are already held.\r\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\r\n };\r\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\r\n var _this = this;\r\n var promiseChain = PersistencePromise.resolve();\r\n var _loop_2 = function (batchResult) {\r\n promiseChain = promiseChain.next(function () {\r\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\r\n });\r\n };\r\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\r\n var batchResult = batchResults_1[_i];\r\n _loop_2(batchResult);\r\n }\r\n return promiseChain.next(function () {\r\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\r\n });\r\n };\r\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\r\n return this.removeMutationBatches(txn, [batch]);\r\n };\r\n /** Removes all the mutation batches named in the given array. */\r\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\r\n var affectedDocs = documentKeySet();\r\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\r\n var batch = batches_2[_i];\r\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\r\n var mutation = _b[_a];\r\n var key = mutation.key;\r\n affectedDocs = affectedDocs.add(key);\r\n }\r\n }\r\n return this.mutationQueue\r\n .removeMutationBatches(txn, batches)\r\n .next(function () { return affectedDocs; });\r\n };\r\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\r\n var batch = batchResult.batch;\r\n var docKeys = batch.keys();\r\n var promiseChain = PersistencePromise.resolve();\r\n docKeys.forEach(function (docKey) {\r\n promiseChain = promiseChain\r\n .next(function () {\r\n return documentBuffer.getEntry(txn, docKey);\r\n })\r\n .next(function (remoteDoc) {\r\n var doc = remoteDoc;\r\n var ackVersion = batchResult.docVersions.get(docKey);\r\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\r\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\r\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\r\n if (!doc) {\r\n assert(!remoteDoc, 'Mutation batch ' +\r\n batch +\r\n ' applied to document ' +\r\n remoteDoc +\r\n ' resulted in null');\r\n }\r\n else {\r\n documentBuffer.addEntry(doc);\r\n }\r\n }\r\n });\r\n });\r\n return promiseChain;\r\n };\r\n return LocalStore;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar MemoryMutationQueue = /** @class */ (function () {\r\n function MemoryMutationQueue() {\r\n /**\r\n * The set of all mutations that have been sent but not yet been applied to\r\n * the backend.\r\n */\r\n this.mutationQueue = [];\r\n /** Next value to use when assigning sequential IDs to each mutation batch. */\r\n this.nextBatchId = 1;\r\n /** The highest acknowledged mutation in the queue. */\r\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\r\n /** The last received stream token from the server, used to acknowledge which\r\n * responses the client has processed. Stream tokens are opaque checkpoint\r\n * markers whose only real value is their inclusion in the next request.\r\n */\r\n this.lastStreamToken = emptyByteString();\r\n /** The garbage collector to notify about potential garbage keys. */\r\n this.garbageCollector = null;\r\n /** An ordered mapping between documents and the mutations batch IDs. */\r\n this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\r\n }\r\n MemoryMutationQueue.prototype.start = function (transaction) {\r\n // NOTE: The queue may be shutdown / started multiple times, since we\r\n // maintain the queue for the duration of the app session in case a user\r\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\r\n // accommodate tests that expect as much), we reset nextBatchId and\r\n // highestAcknowledgedBatchId if the queue is empty.\r\n if (this.mutationQueue.length === 0) {\r\n this.nextBatchId = 1;\r\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\r\n }\r\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\r\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\r\n };\r\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\r\n return PersistencePromise.resolve(this.nextBatchId);\r\n };\r\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\r\n return PersistencePromise.resolve(this.highestAcknowledgedBatchId);\r\n };\r\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\r\n var batchId = batch.batchId;\r\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\r\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\r\n // Verify that the batch in the queue is the one to be acknowledged.\r\n var check = this.mutationQueue[batchIndex];\r\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\r\n batchId +\r\n ', got batch ' +\r\n check.batchId);\r\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\r\n this.highestAcknowledgedBatchId = batchId;\r\n this.lastStreamToken = streamToken;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\r\n return PersistencePromise.resolve(this.lastStreamToken);\r\n };\r\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\r\n this.lastStreamToken = streamToken;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\r\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\r\n var batchId = this.nextBatchId;\r\n this.nextBatchId++;\r\n if (this.mutationQueue.length > 0) {\r\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\r\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\r\n }\r\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\r\n this.mutationQueue.push(batch);\r\n // Track references by document key.\r\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\r\n var mutation = mutations_1[_i];\r\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId));\r\n }\r\n return PersistencePromise.resolve(batch);\r\n };\r\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\r\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\r\n };\r\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\r\n var size = this.mutationQueue.length;\r\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\r\n // acknowledged so the first unacknowledged batch after batchID will have a\r\n // batchID larger than both of these values.\r\n var nextBatchId = Math.max(batchId, this.highestAcknowledgedBatchId) + 1;\r\n // The requested batchId may still be out of range so normalize it to the\r\n // start of the queue.\r\n var rawIndex = this.indexOfBatchId(nextBatchId);\r\n var index = rawIndex < 0 ? 0 : rawIndex;\r\n // Finally return the first non-tombstone batch.\r\n for (; index < size; index++) {\r\n var batch = this.mutationQueue[index];\r\n if (!batch.isTombstone()) {\r\n return PersistencePromise.resolve(batch);\r\n }\r\n }\r\n return PersistencePromise.resolve(null);\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\r\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\r\n var count = this.mutationQueue.length;\r\n var endIndex = this.indexOfBatchId(batchId);\r\n if (endIndex < 0) {\r\n endIndex = 0;\r\n }\r\n else if (endIndex >= count) {\r\n endIndex = count;\r\n }\r\n else {\r\n // The endIndex is in the queue so increment to pull everything in the\r\n // queue including it.\r\n endIndex++;\r\n }\r\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\r\n var _this = this;\r\n var start = new DocReference(documentKey, 0);\r\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\r\n var result = [];\r\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\r\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\r\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\r\n assert(batch !== null, 'Batches in the index must exist in the main table');\r\n result.push(batch);\r\n });\r\n return PersistencePromise.resolve(result);\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\r\n var _this = this;\r\n // Use the query path as a prefix for testing if a document matches the\r\n // query.\r\n var prefix = query.path;\r\n var immediateChildrenPathLength = prefix.length + 1;\r\n // Construct a document reference for actually scanning the index. Unlike\r\n // the prefix the document key in this reference must have an even number of\r\n // segments. The empty segment can be used a suffix of the query path\r\n // because it precedes all other segments in an ordered traversal.\r\n var startPath = prefix;\r\n if (!DocumentKey.isDocumentKey(startPath)) {\r\n startPath = startPath.child('');\r\n }\r\n var start = new DocReference(new DocumentKey(startPath), 0);\r\n // Find unique batchIDs referenced by all documents potentially matching the\r\n // query.\r\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\r\n this.batchesByDocumentKey.forEachWhile(function (ref) {\r\n var rowKeyPath = ref.key.path;\r\n if (!prefix.isPrefixOf(rowKeyPath)) {\r\n return false;\r\n }\r\n else {\r\n // Rows with document keys more than one segment longer than the query\r\n // path can't be matches. For example, a query on 'rooms' can't match\r\n // the document /rooms/abc/messages/xyx.\r\n // TODO(mcg): we'll need a different scanner when we implement\r\n // ancestor queries.\r\n if (rowKeyPath.length === immediateChildrenPathLength) {\r\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\r\n }\r\n return true;\r\n }\r\n }, start);\r\n // Construct an array of matching batches, sorted by batchID to ensure that\r\n // multiple mutations affecting the same document key are applied in order.\r\n var result = [];\r\n uniqueBatchIDs.forEach(function (batchId) {\r\n var batch = _this.findMutationBatch(batchId);\r\n if (batch !== null) {\r\n result.push(batch);\r\n }\r\n });\r\n return PersistencePromise.resolve(result);\r\n };\r\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\r\n var batchCount = batches.length;\r\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\r\n var firstBatchId = batches[0].batchId;\r\n var queueCount = this.mutationQueue.length;\r\n // Find the position of the first batch for removal. This need not be the\r\n // first entry in the queue.\r\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\r\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\r\n // Check that removed batches are contiguous (while excluding tombstones).\r\n var batchIndex = 1;\r\n var queueIndex = startIndex + 1;\r\n while (batchIndex < batchCount && queueIndex < queueCount) {\r\n var batch = this.mutationQueue[queueIndex];\r\n if (batch.isTombstone()) {\r\n queueIndex++;\r\n continue;\r\n }\r\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\r\n batchIndex++;\r\n queueIndex++;\r\n }\r\n // Only actually remove batches if removing at the front of the queue.\r\n // Previously rejected batches may have left tombstones in the queue, so\r\n // expand the removal range to include any tombstones.\r\n if (startIndex === 0) {\r\n for (; queueIndex < queueCount; queueIndex++) {\r\n var batch = this.mutationQueue[queueIndex];\r\n if (!batch.isTombstone()) {\r\n break;\r\n }\r\n }\r\n var length_1 = queueIndex - startIndex;\r\n this.mutationQueue.splice(startIndex, length_1);\r\n }\r\n else {\r\n // Mark the tombstones\r\n for (var i = startIndex; i < queueIndex; i++) {\r\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\r\n }\r\n }\r\n var references = this.batchesByDocumentKey;\r\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\r\n var batch = batches_1[_i];\r\n var batchId = batch.batchId;\r\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\r\n var mutation = _b[_a];\r\n var key = mutation.key;\r\n if (this.garbageCollector !== null) {\r\n this.garbageCollector.addPotentialGarbageKey(key);\r\n }\r\n var ref = new DocReference(key, batchId);\r\n references = references.delete(ref);\r\n }\r\n }\r\n this.batchesByDocumentKey = references;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\r\n this.garbageCollector = garbageCollector;\r\n };\r\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\r\n var ref = new DocReference(key, 0);\r\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\r\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\r\n };\r\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\r\n if (this.mutationQueue.length === 0) {\r\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\r\n }\r\n return PersistencePromise.resolve();\r\n };\r\n /**\r\n * A private helper that collects all the mutations batches in the queue up to\r\n * but not including the given endIndex. All tombstones in the queue are\r\n * excluded.\r\n */\r\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\r\n var result = [];\r\n for (var i = 0; i < endIndex; i++) {\r\n var batch = this.mutationQueue[i];\r\n if (!batch.isTombstone()) {\r\n result.push(batch);\r\n }\r\n }\r\n return result;\r\n };\r\n /**\r\n * Finds the index of the given batchId in the mutation queue and asserts that\r\n * the resulting index is within the bounds of the queue.\r\n *\r\n * @param batchId The batchId to search for\r\n * @param action A description of what the caller is doing, phrased in passive\r\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\r\n */\r\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\r\n var index = this.indexOfBatchId(batchId);\r\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\r\n return index;\r\n };\r\n /**\r\n * Finds the index of the given batchId in the mutation queue. This operation\r\n * is O(1).\r\n *\r\n * @return The computed index of the batch with the given batchId, based on\r\n * the state of the queue. Note this index can be negative if the requested\r\n * batchId has already been remvoed from the queue or past the end of the\r\n * queue if the batchId is larger than the last added batch.\r\n */\r\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\r\n if (this.mutationQueue.length === 0) {\r\n // As an index this is past the end of the queue\r\n return 0;\r\n }\r\n // Examine the front of the queue to figure out the difference between the\r\n // batchId and indexes in the array. Note that since the queue is ordered\r\n // by batchId, if the first batch has a larger batchId then the requested\r\n // batchId doesn't exist in the queue.\r\n var firstBatchId = this.mutationQueue[0].batchId;\r\n return batchId - firstBatchId;\r\n };\r\n /**\r\n * A version of lookupMutationBatch that doesn't return a promise, this makes\r\n * other functions that uses this code easier to read and more efficent.\r\n */\r\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\r\n var index = this.indexOfBatchId(batchId);\r\n if (index < 0 || index >= this.mutationQueue.length) {\r\n return null;\r\n }\r\n var batch = this.mutationQueue[index];\r\n assert(batch.batchId === batchId, 'If found batch must match');\r\n return batch.isTombstone() ? null : batch;\r\n };\r\n return MemoryMutationQueue;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar MemoryQueryCache = /** @class */ (function () {\r\n function MemoryQueryCache() {\r\n /**\r\n * Maps a query to the data about that query\r\n */\r\n this.queries = new ObjectMap(function (q) { return q.canonicalId(); });\r\n /** The last received snapshot version. */\r\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\r\n /** The highest numbered target ID encountered. */\r\n this.highestTargetId = 0;\r\n /**\r\n * A ordered bidirectional mapping between documents and the remote target\r\n * IDs.\r\n */\r\n this.references = new ReferenceSet();\r\n this.targetCount = 0;\r\n }\r\n MemoryQueryCache.prototype.start = function (transaction) {\r\n // Nothing to do.\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\r\n return this.lastRemoteSnapshotVersion;\r\n };\r\n MemoryQueryCache.prototype.getHighestTargetId = function () {\r\n return this.highestTargetId;\r\n };\r\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\r\n this.lastRemoteSnapshotVersion = snapshotVersion;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.saveQueryData = function (queryData) {\r\n this.queries.set(queryData.query, queryData);\r\n var targetId = queryData.targetId;\r\n if (targetId > this.highestTargetId) {\r\n this.highestTargetId = targetId;\r\n }\r\n // TODO(GC): track sequence number\r\n };\r\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\r\n assert(!this.queries.has(queryData.query), 'Adding a query that already exists');\r\n this.saveQueryData(queryData);\r\n this.targetCount += 1;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.updateQueryData = function (transaction, queryData) {\r\n assert(this.queries.has(queryData.query), 'Updating a non-existent query');\r\n this.saveQueryData(queryData);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\r\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\r\n assert(this.queries.has(queryData.query), 'Removing a non-existent target from the cache');\r\n this.queries.delete(queryData.query);\r\n this.references.removeReferencesForId(queryData.targetId);\r\n this.targetCount -= 1;\r\n return PersistencePromise.resolve();\r\n };\r\n Object.defineProperty(MemoryQueryCache.prototype, \"count\", {\r\n get: function () {\r\n return this.targetCount;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\r\n var queryData = this.queries.get(query) || null;\r\n return PersistencePromise.resolve(queryData);\r\n };\r\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\r\n this.references.addReferences(keys, targetId);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\r\n this.references.removeReferences(keys, targetId);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\r\n this.references.removeReferencesForId(targetId);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\r\n var matchingKeys = this.references.referencesForId(targetId);\r\n return PersistencePromise.resolve(matchingKeys);\r\n };\r\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\r\n this.references.setGarbageCollector(gc);\r\n };\r\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\r\n return this.references.containsKey(txn, key);\r\n };\r\n return MemoryQueryCache;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar MemoryRemoteDocumentCache = /** @class */ (function () {\r\n function MemoryRemoteDocumentCache() {\r\n this.docs = maybeDocumentMap();\r\n }\r\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\r\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\r\n this.docs = this.docs.remove(documentKey);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\r\n return PersistencePromise.resolve(this.docs.get(documentKey));\r\n };\r\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\r\n var results = documentMap();\r\n // Documents are ordered by key, so we can use a prefix scan to narrow down\r\n // the documents we need to match the query against.\r\n var prefix = new DocumentKey(query.path.child(''));\r\n var iterator = this.docs.getIteratorFrom(prefix);\r\n while (iterator.hasNext()) {\r\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\r\n if (!query.path.isPrefixOf(key.path)) {\r\n break;\r\n }\r\n if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\r\n results = results.insert(maybeDoc.key, maybeDoc);\r\n }\r\n }\r\n return PersistencePromise.resolve(results);\r\n };\r\n return MemoryRemoteDocumentCache;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$5 = 'MemoryPersistence';\r\n/**\r\n * A memory-backed instance of Persistence. Data is stored only in RAM and\r\n * not persisted across sessions.\r\n */\r\nvar MemoryPersistence = /** @class */ (function () {\r\n function MemoryPersistence() {\r\n /**\r\n * Note that these are retained here to make it easier to write tests\r\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\r\n * can create a new LocalStore wrapping this Persistence instance and this\r\n * will make the in-memory persistence layer behave as if it were actually\r\n * persisting values.\r\n */\r\n this.mutationQueues = {};\r\n this.remoteDocumentCache = new MemoryRemoteDocumentCache();\r\n this.queryCache = new MemoryQueryCache();\r\n this.started = false;\r\n }\r\n MemoryPersistence.prototype.start = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // No durable state to read on startup.\r\n assert(!this.started, 'MemoryPersistence double-started!');\r\n this.started = true;\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n MemoryPersistence.prototype.shutdown = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // No durable state to ensure is closed on shutdown.\r\n assert(this.started, 'MemoryPersistence shutdown without start!');\r\n this.started = false;\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n MemoryPersistence.prototype.getMutationQueue = function (user) {\r\n var queue = this.mutationQueues[user.toKey()];\r\n if (!queue) {\r\n queue = new MemoryMutationQueue();\r\n this.mutationQueues[user.toKey()] = queue;\r\n }\r\n return queue;\r\n };\r\n MemoryPersistence.prototype.getQueryCache = function () {\r\n return this.queryCache;\r\n };\r\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\r\n return this.remoteDocumentCache;\r\n };\r\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\r\n debug(LOG_TAG$5, 'Starting transaction:', action);\r\n return operation(new MemoryPersistenceTransaction()).toPromise();\r\n };\r\n return MemoryPersistence;\r\n}());\r\n/** Dummy class since memory persistence doesn't actually use transactions. */\r\nvar MemoryPersistenceTransaction = /** @class */ (function () {\r\n function MemoryPersistenceTransaction() {\r\n }\r\n return MemoryPersistenceTransaction;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A garbage collector implementation that does absolutely nothing. It ignores\r\n * all addGarbageSource and addPotentialGarbageKey messages and and never\r\n * produces any garbage.\r\n */\r\nvar NoOpGarbageCollector = /** @class */ (function () {\r\n function NoOpGarbageCollector() {\r\n this.isEager = false;\r\n }\r\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\r\n // Not tracking garbage so don't track sources.\r\n };\r\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\r\n // Not tracking garbage so don't track sources.\r\n };\r\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\r\n // Not tracking garbage so ignore.\r\n };\r\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\r\n return PersistencePromise.resolve(documentKeySet());\r\n };\r\n return NoOpGarbageCollector;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar Deferred = /** @class */ (function () {\r\n function Deferred() {\r\n var _this = this;\r\n this.promise = new Promise(function (resolve, reject) {\r\n _this.resolve = resolve;\r\n _this.reject = reject;\r\n });\r\n }\r\n return Deferred;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Wellknown \"timer\" IDs used when scheduling delayed operations on the\r\n * AsyncQueue. These IDs can then be used from tests to check for the presence\r\n * of operations or to run them early.\r\n *\r\n * The string values are used when encoding these timer IDs in JSON spec tests.\r\n */\r\nvar TimerId;\r\n(function (TimerId) {\r\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\r\n TimerId[\"All\"] = \"all\";\r\n /**\r\n * The following 4 timers are used in persistent_stream.ts for the listen and\r\n * write streams. The \"Idle\" timer is used to close the stream due to\r\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\r\n * the appropriate backoff delay has elapsed.\r\n */\r\n TimerId[\"ListenStreamIdle\"] = \"listen_stream_idle\";\r\n TimerId[\"ListenStreamConnectionBackoff\"] = \"listen_stream_connection_backoff\";\r\n TimerId[\"WriteStreamIdle\"] = \"write_stream_idle\";\r\n TimerId[\"WriteStreamConnectionBackoff\"] = \"write_stream_connection_backoff\";\r\n /**\r\n * A timer used in online_state_tracker.ts to transition from\r\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\r\n * indefinitely for success or failure.\r\n */\r\n TimerId[\"OnlineStateTimeout\"] = \"online_state_timeout\";\r\n})(TimerId || (TimerId = {}));\r\n/**\r\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\r\n *\r\n * It is created via DelayedOperation.createAndSchedule().\r\n *\r\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\r\n */\r\nvar DelayedOperation = /** @class */ (function () {\r\n function DelayedOperation(asyncQueue, timerId, targetTimeMs, op, removalCallback) {\r\n this.asyncQueue = asyncQueue;\r\n this.timerId = timerId;\r\n this.targetTimeMs = targetTimeMs;\r\n this.op = op;\r\n this.removalCallback = removalCallback;\r\n this.deferred = new Deferred();\r\n this.then = this.deferred.promise.then.bind(this.deferred.promise);\r\n this.catch = this.deferred.promise.catch.bind(this.deferred.promise);\r\n // It's normal for the deferred promise to be canceled (due to cancellation)\r\n // and so we attach a dummy catch callback to avoid\r\n // 'UnhandledPromiseRejectionWarning' log spam.\r\n this.deferred.promise.catch(function (err) { });\r\n }\r\n /**\r\n * Creates and returns a DelayedOperation that has been scheduled to be\r\n * executed on the provided asyncQueue after the provided delayMs.\r\n *\r\n * @param asyncQueue The queue to schedule the operation on.\r\n * @param id A Timer ID identifying the type of operation this is.\r\n * @param delayMs The delay (ms) before the operation should be scheduled.\r\n * @param op The operation to run.\r\n * @param removalCallback A callback to be called synchronously once the\r\n * operation is executed or canceled, notifying the AsyncQueue to remove it\r\n * from its delayedOperations list.\r\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\r\n * the DelayedOperation class public.\r\n */\r\n DelayedOperation.createAndSchedule = function (asyncQueue, timerId, delayMs, op, removalCallback) {\r\n var targetTime = Date.now() + delayMs;\r\n var delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);\r\n delayedOp.start(delayMs);\r\n return delayedOp;\r\n };\r\n /**\r\n * Starts the timer. This is called immediately after construction by\r\n * createAndSchedule().\r\n */\r\n DelayedOperation.prototype.start = function (delayMs) {\r\n var _this = this;\r\n this.timerHandle = setTimeout(function () { return _this.handleDelayElapsed(); }, delayMs);\r\n };\r\n /**\r\n * Queues the operation to run immediately (if it hasn't already been run or\r\n * canceled).\r\n */\r\n DelayedOperation.prototype.skipDelay = function () {\r\n return this.handleDelayElapsed();\r\n };\r\n /**\r\n * Cancels the operation if it hasn't already been executed or canceled. The\r\n * promise will be rejected.\r\n *\r\n * As long as the operation has not yet been run, calling cancel() provides a\r\n * guarantee that the operation will not be run.\r\n */\r\n DelayedOperation.prototype.cancel = function (reason) {\r\n if (this.timerHandle !== null) {\r\n this.clearTimeout();\r\n this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));\r\n }\r\n };\r\n DelayedOperation.prototype.handleDelayElapsed = function () {\r\n var _this = this;\r\n this.asyncQueue.enqueue(function () {\r\n if (_this.timerHandle !== null) {\r\n _this.clearTimeout();\r\n return _this.op().then(function (result) {\r\n return _this.deferred.resolve(result);\r\n });\r\n }\r\n else {\r\n return Promise.resolve();\r\n }\r\n });\r\n };\r\n DelayedOperation.prototype.clearTimeout = function () {\r\n if (this.timerHandle !== null) {\r\n this.removalCallback(this);\r\n clearTimeout(this.timerHandle);\r\n this.timerHandle = null;\r\n }\r\n };\r\n return DelayedOperation;\r\n}());\r\nvar AsyncQueue = /** @class */ (function () {\r\n function AsyncQueue() {\r\n // The last promise in the queue.\r\n this.tail = Promise.resolve();\r\n // Operations scheduled to be queued in the future. Operations are\r\n // automatically removed after they are run or canceled.\r\n this.delayedOperations = [];\r\n // Flag set while there's an outstanding AsyncQueue operation, used for\r\n // assertion sanity-checks.\r\n this.operationInProgress = false;\r\n }\r\n /**\r\n * Adds a new operation to the queue. Returns a promise that will be resolved\r\n * when the promise returned by the new operation is (with its value).\r\n */\r\n AsyncQueue.prototype.enqueue = function (op) {\r\n var _this = this;\r\n this.verifyNotFailed();\r\n var newTail = this.tail.then(function () {\r\n _this.operationInProgress = true;\r\n return op()\r\n .catch(function (error$$1) {\r\n _this.failure = error$$1;\r\n _this.operationInProgress = false;\r\n var message = error$$1.stack || error$$1.message || '';\r\n error('INTERNAL UNHANDLED ERROR: ', message);\r\n // Escape the promise chain and throw the error globally so that\r\n // e.g. any global crash reporting library detects and reports it.\r\n // (but not for simulated errors in our tests since this breaks mocha)\r\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\r\n setTimeout(function () {\r\n throw error$$1;\r\n }, 0);\r\n }\r\n // Re-throw the error so that this.tail becomes a rejected Promise and\r\n // all further attempts to chain (via .then) will just short-circuit\r\n // and return the rejected Promise.\r\n throw error$$1;\r\n })\r\n .then(function (result) {\r\n _this.operationInProgress = false;\r\n return result;\r\n });\r\n });\r\n this.tail = newTail;\r\n return newTail;\r\n };\r\n /**\r\n * Schedules an operation to be queued on the AsyncQueue once the specified\r\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\r\n * the operation prior to its running.\r\n */\r\n AsyncQueue.prototype.enqueueAfterDelay = function (timerId, delayMs, op) {\r\n var _this = this;\r\n this.verifyNotFailed();\r\n // While not necessarily harmful, we currently don't expect to have multiple\r\n // ops with the same timer id in the queue, so defensively reject them.\r\n assert(!this.containsDelayedOperation(timerId), \"Attempted to schedule multiple operations with timer id \" + timerId + \".\");\r\n var delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, function (op) { return _this.removeDelayedOperation(op); });\r\n this.delayedOperations.push(delayedOp);\r\n return delayedOp;\r\n };\r\n AsyncQueue.prototype.verifyNotFailed = function () {\r\n if (this.failure) {\r\n fail('AsyncQueue is already failed: ' +\r\n (this.failure.stack || this.failure.message));\r\n }\r\n };\r\n /**\r\n * Verifies there's an operation currently in-progress on the AsyncQueue.\r\n * Unfortunately we can't verify that the running code is in the promise chain\r\n * of that operation, so this isn't a foolproof check, but it should be enough\r\n * to catch some bugs.\r\n */\r\n AsyncQueue.prototype.verifyOperationInProgress = function () {\r\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\r\n };\r\n /**\r\n * Waits until all currently queued tasks are finished executing. Delayed\r\n * operations are not run.\r\n */\r\n AsyncQueue.prototype.drain = function () {\r\n return this.enqueue(function () { return Promise.resolve(); });\r\n };\r\n /**\r\n * For Tests: Determine if a delayed operation with a particular TimerId\r\n * exists.\r\n */\r\n AsyncQueue.prototype.containsDelayedOperation = function (timerId) {\r\n return this.delayedOperations.findIndex(function (op) { return op.timerId === timerId; }) >= 0;\r\n };\r\n /**\r\n * For Tests: Runs some or all delayed operations early.\r\n *\r\n * @param lastTimerId Delayed operations up to and including this TimerId will\r\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\r\n * all delayed operations.\r\n * @returns a Promise that resolves once all operations have been run.\r\n */\r\n AsyncQueue.prototype.runDelayedOperationsEarly = function (lastTimerId) {\r\n var _this = this;\r\n // Note that draining may generate more delayed ops, so we do that first.\r\n return this.drain().then(function () {\r\n assert(lastTimerId === TimerId.All ||\r\n _this.containsDelayedOperation(lastTimerId), \"Attempted to drain to missing operation \" + lastTimerId);\r\n // Run ops in the same order they'd run if they ran naturally.\r\n _this.delayedOperations.sort(function (a, b) { return a.targetTimeMs - b.targetTimeMs; });\r\n for (var _i = 0, _a = _this.delayedOperations; _i < _a.length; _i++) {\r\n var op = _a[_i];\r\n op.skipDelay();\r\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\r\n break;\r\n }\r\n }\r\n return _this.drain();\r\n });\r\n };\r\n /** Called once a DelayedOperation is run or canceled. */\r\n AsyncQueue.prototype.removeDelayedOperation = function (op) {\r\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\r\n var index = this.delayedOperations.indexOf(op);\r\n assert(index >= 0, 'Delayed operation not found.');\r\n this.delayedOperations.splice(index, 1);\r\n };\r\n return AsyncQueue;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$6 = 'ExponentialBackoff';\r\n/**\r\n * A helper for running delayed tasks following an exponential backoff curve\r\n * between attempts.\r\n *\r\n * Each delay is made up of a \"base\" delay which follows the exponential\r\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\r\n * base delay. This prevents clients from accidentally synchronizing their\r\n * delays causing spikes of load to the backend.\r\n */\r\nvar ExponentialBackoff = /** @class */ (function () {\r\n function ExponentialBackoff(\r\n /**\r\n * The AsyncQueue to run backoff operations on.\r\n */\r\n queue, \r\n /**\r\n * The ID to use when scheduling backoff operations on the AsyncQueue.\r\n */\r\n timerId, \r\n /**\r\n * The initial delay (used as the base delay on the first retry attempt).\r\n * Note that jitter will still be applied, so the actual delay could be as\r\n * little as 0.5*initialDelayMs.\r\n */\r\n initialDelayMs, \r\n /**\r\n * The multiplier to use to determine the extended base delay after each\r\n * attempt.\r\n */\r\n backoffFactor, \r\n /**\r\n * The maximum base delay after which no further backoff is performed.\r\n * Note that jitter will still be applied, so the actual delay could be as\r\n * much as 1.5*maxDelayMs.\r\n */\r\n maxDelayMs) {\r\n this.queue = queue;\r\n this.timerId = timerId;\r\n this.initialDelayMs = initialDelayMs;\r\n this.backoffFactor = backoffFactor;\r\n this.maxDelayMs = maxDelayMs;\r\n this.timerPromise = null;\r\n this.reset();\r\n }\r\n /**\r\n * Resets the backoff delay.\r\n *\r\n * The very next backoffAndWait() will have no delay. If it is called again\r\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\r\n * subsequent ones will increase according to the backoffFactor.\r\n */\r\n ExponentialBackoff.prototype.reset = function () {\r\n this.currentBaseMs = 0;\r\n };\r\n /**\r\n * Resets the backoff delay to the maximum delay (e.g. for use after a\r\n * RESOURCE_EXHAUSTED error).\r\n */\r\n ExponentialBackoff.prototype.resetToMax = function () {\r\n this.currentBaseMs = this.maxDelayMs;\r\n };\r\n /**\r\n * Returns a promise that resolves after currentDelayMs, and increases the\r\n * delay for any subsequent attempts. If there was a pending backoff operation\r\n * already, it will be canceled.\r\n */\r\n ExponentialBackoff.prototype.backoffAndRun = function (op) {\r\n // Cancel any pending backoff operation.\r\n this.cancel();\r\n // First schedule using the current base (which may be 0 and should be\r\n // honored as such).\r\n var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\r\n if (this.currentBaseMs > 0) {\r\n debug(LOG_TAG$6, \"Backing off for \" + delayWithJitterMs + \" ms \" +\r\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\r\n }\r\n this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, delayWithJitterMs, op);\r\n // Apply backoff factor to determine next delay and ensure it is within\r\n // bounds.\r\n this.currentBaseMs *= this.backoffFactor;\r\n if (this.currentBaseMs < this.initialDelayMs) {\r\n this.currentBaseMs = this.initialDelayMs;\r\n }\r\n if (this.currentBaseMs > this.maxDelayMs) {\r\n this.currentBaseMs = this.maxDelayMs;\r\n }\r\n };\r\n ExponentialBackoff.prototype.cancel = function () {\r\n if (this.timerPromise !== null) {\r\n this.timerPromise.cancel();\r\n this.timerPromise = null;\r\n }\r\n };\r\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\r\n ExponentialBackoff.prototype.jitterDelayMs = function () {\r\n return (Math.random() - 0.5) * this.currentBaseMs;\r\n };\r\n return ExponentialBackoff;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$7 = 'PersistentStream';\r\nvar PersistentStreamState;\r\n(function (PersistentStreamState) {\r\n /**\r\n * The streaming RPC is not running and there's no error condition.\r\n * Calling `start` will start the stream immediately without backoff.\r\n * While in this state isStarted will return false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\r\n /**\r\n * The stream is starting, and is waiting for an auth token to attach to\r\n * the initial request. While in this state, isStarted will return\r\n * true but isOpen will return false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\r\n /**\r\n * The streaming RPC is up and running. Requests and responses can flow\r\n * freely. Both isStarted and isOpen will return true.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\r\n /**\r\n * The stream encountered an error. The next start attempt will back off.\r\n * While in this state isStarted() will return false.\r\n *\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\r\n /**\r\n * An in-between state after an error where the stream is waiting before\r\n * re-starting. After\r\n * waiting is complete, the stream will try to open. While in this\r\n * state isStarted() will return YES but isOpen will return false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\r\n /**\r\n * The stream has been explicitly stopped; no further events will be emitted.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\r\n})(PersistentStreamState || (PersistentStreamState = {}));\r\n/**\r\n * Initial backoff time in milliseconds after an error.\r\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\r\n */\r\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\r\n/** Maximum backoff time in milliseconds */\r\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\r\nvar BACKOFF_FACTOR = 1.5;\r\n/** The time a stream stays open after it is marked idle. */\r\nvar IDLE_TIMEOUT_MS = 60 * 1000;\r\n/**\r\n * A PersistentStream is an abstract base class that represents a streaming RPC\r\n * to the Firestore backend. It's built on top of the connections own support\r\n * for streaming RPCs, and adds several critical features for our clients:\r\n *\r\n * - Exponential backoff on failure\r\n * - Authentication via CredentialsProvider\r\n * - Dispatching all callbacks into the shared worker queue\r\n *\r\n * Subclasses of PersistentStream implement serialization of models to and\r\n * from the JSON representation of the protocol buffers for a specific\r\n * streaming RPC.\r\n *\r\n * ## Starting and Stopping\r\n *\r\n * Streaming RPCs are stateful and need to be `start`ed before messages can\r\n * be sent and received. The PersistentStream will call the onOpen function\r\n * of the listener once the stream is ready to accept requests.\r\n *\r\n * Should a `start` fail, PersistentStream will call the registered\r\n * onClose with a FirestoreError indicating what went wrong.\r\n *\r\n * A PersistentStream can be started and stopped repeatedly.\r\n *\r\n * Generic types:\r\n * SendType: The type of the outgoing message of the underlying\r\n * connection stream\r\n * ReceiveType: The type of the incoming message of the underlying\r\n * connection stream\r\n * ListenerType: The type of the listener that will be used for callbacks\r\n */\r\nvar PersistentStream = /** @class */ (function () {\r\n function PersistentStream(queue, connectionTimerId, idleTimerId, connection, credentialsProvider) {\r\n this.queue = queue;\r\n this.idleTimerId = idleTimerId;\r\n this.connection = connection;\r\n this.credentialsProvider = credentialsProvider;\r\n this.inactivityTimerPromise = null;\r\n this.stream = null;\r\n this.listener = null;\r\n this.backoff = new ExponentialBackoff(queue, connectionTimerId, BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\r\n this.state = PersistentStreamState.Initial;\r\n }\r\n /**\r\n * Returns true if `start` has been called and no error has occurred. True\r\n * indicates the stream is open or in the process of opening (which\r\n * encompasses respecting backoff, getting auth tokens, and starting the\r\n * actual RPC). Use `isOpen` to determine if the stream is open and ready for\r\n * outbound requests.\r\n */\r\n PersistentStream.prototype.isStarted = function () {\r\n return (this.state === PersistentStreamState.Backoff ||\r\n this.state === PersistentStreamState.Auth ||\r\n this.state === PersistentStreamState.Open);\r\n };\r\n /**\r\n * Returns true if the underlying RPC is open (the openHandler has been\r\n * called) and the stream is ready for outbound requests.\r\n */\r\n PersistentStream.prototype.isOpen = function () {\r\n return this.state === PersistentStreamState.Open;\r\n };\r\n /**\r\n * Starts the RPC. Only allowed if isStarted returns false. The stream is\r\n * not immediately ready for use: onOpen will be invoked when the RPC is ready\r\n * for outbound requests, at which point isOpen will return true.\r\n *\r\n * When start returns, isStarted will return true.\r\n */\r\n PersistentStream.prototype.start = function (listener) {\r\n if (this.state === PersistentStreamState.Error) {\r\n this.performBackoff(listener);\r\n return;\r\n }\r\n assert(this.state === PersistentStreamState.Initial, 'Already started');\r\n this.listener = listener;\r\n this.auth();\r\n };\r\n /**\r\n * Stops the RPC. This call is idempotent and allowed regardless of the\r\n * current isStarted state.\r\n *\r\n * When stop returns, isStarted and isOpen will both return false.\r\n */\r\n PersistentStream.prototype.stop = function () {\r\n if (this.isStarted()) {\r\n this.close(PersistentStreamState.Stopped);\r\n }\r\n };\r\n /**\r\n * After an error the stream will usually back off on the next attempt to\r\n * start it. If the error warrants an immediate restart of the stream, the\r\n * sender can use this to indicate that the receiver should not back off.\r\n *\r\n * Each error will call the onClose function. That function can decide to\r\n * inhibit backoff if required.\r\n */\r\n PersistentStream.prototype.inhibitBackoff = function () {\r\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\r\n this.state = PersistentStreamState.Initial;\r\n this.backoff.reset();\r\n };\r\n /**\r\n * Marks this stream as idle. If no further actions are performed on the\r\n * stream for one minute, the stream will automatically close itself and\r\n * notify the stream's onClose() handler with Status.OK. The stream will then\r\n * be in a !isStarted() state, requiring the caller to start the stream again\r\n * before further use.\r\n *\r\n * Only streams that are in state 'Open' can be marked idle, as all other\r\n * states imply pending network operations.\r\n */\r\n PersistentStream.prototype.markIdle = function () {\r\n var _this = this;\r\n // Starts the idle time if we are in state 'Open' and are not yet already\r\n // running a timer (in which case the previous idle timeout still applies).\r\n if (this.isOpen() && this.inactivityTimerPromise === null) {\r\n this.inactivityTimerPromise = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, function () { return _this.handleIdleCloseTimer(); });\r\n }\r\n };\r\n /** Sends a message to the underlying stream. */\r\n PersistentStream.prototype.sendRequest = function (msg) {\r\n this.cancelIdleCheck();\r\n this.stream.send(msg);\r\n };\r\n /** Called by the idle timer when the stream should close due to inactivity. */\r\n PersistentStream.prototype.handleIdleCloseTimer = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (this.isOpen()) {\r\n // When timing out an idle stream there's no reason to force the stream into backoff when\r\n // it restarts so set the stream state to Initial instead of Error.\r\n return [2 /*return*/, this.close(PersistentStreamState.Initial)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /** Marks the stream as active again. */\r\n PersistentStream.prototype.cancelIdleCheck = function () {\r\n if (this.inactivityTimerPromise) {\r\n this.inactivityTimerPromise.cancel();\r\n this.inactivityTimerPromise = null;\r\n }\r\n };\r\n /**\r\n * Closes the stream and cleans up as necessary:\r\n *\r\n * * closes the underlying GRPC stream;\r\n * * calls the onClose handler with the given 'error';\r\n * * sets internal stream state to 'finalState';\r\n * * adjusts the backoff timer based on the error\r\n *\r\n * A new stream can be opened by calling `start` unless `finalState` is set to\r\n * `PersistentStreamState.Stopped`.\r\n *\r\n * @param finalState the intended state of the stream after closing.\r\n * @param error the error the connection was closed with.\r\n */\r\n PersistentStream.prototype.close = function (finalState, error$$1) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var listener;\r\n return __generator(this, function (_a) {\r\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error$$1), \"Can't provide an error when not in an error state.\");\r\n // The stream will be closed so we don't need our idle close timer anymore.\r\n this.cancelIdleCheck();\r\n // Ensure we don't leave a pending backoff operation queued (in case close()\r\n // was called while we were waiting to reconnect).\r\n this.backoff.cancel();\r\n if (finalState !== PersistentStreamState.Error) {\r\n // If this is an intentional close ensure we don't delay our next connection attempt.\r\n this.backoff.reset();\r\n }\r\n else if (error$$1 && error$$1.code === Code.RESOURCE_EXHAUSTED) {\r\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\r\n error(error$$1.toString());\r\n error('Using maximum backoff delay to prevent overloading the backend.');\r\n this.backoff.resetToMax();\r\n }\r\n // Clean up the underlying stream because we are no longer interested in events.\r\n if (this.stream !== null) {\r\n this.tearDown();\r\n this.stream.close();\r\n this.stream = null;\r\n }\r\n // This state must be assigned before calling onClose() to allow the callback to\r\n // inhibit backoff or otherwise manipulate the state in its non-started state.\r\n this.state = finalState;\r\n listener = this.listener;\r\n // Clear the listener to avoid bleeding of events from the underlying streams.\r\n this.listener = null;\r\n // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it\r\n // could trigger undesirable recovery logic, etc.).\r\n if (finalState !== PersistentStreamState.Stopped) {\r\n return [2 /*return*/, listener.onClose(error$$1)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /**\r\n * Can be overridden to perform additional cleanup before the stream is closed.\r\n * Calling super.tearDown() is not required.\r\n */\r\n PersistentStream.prototype.tearDown = function () { };\r\n PersistentStream.prototype.auth = function () {\r\n var _this = this;\r\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\r\n this.state = PersistentStreamState.Auth;\r\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\r\n // Normally we'd have to schedule the callback on the AsyncQueue.\r\n // However, the following calls are safe to be called outside the\r\n // AsyncQueue since they don't chain asynchronous calls\r\n _this.startStream(token);\r\n }, function (error$$1) {\r\n _this.queue.enqueue(function () { return __awaiter(_this, void 0, void 0, function () {\r\n var rpcError;\r\n return __generator(this, function (_a) {\r\n if (this.state !== PersistentStreamState.Stopped) {\r\n rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error$$1.message);\r\n return [2 /*return*/, this.handleStreamClose(rpcError)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n });\r\n };\r\n PersistentStream.prototype.startStream = function (token) {\r\n var _this = this;\r\n if (this.state === PersistentStreamState.Stopped) {\r\n // Stream can be stopped while waiting for authorization.\r\n return;\r\n }\r\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\r\n // Helper function to dispatch to AsyncQueue and make sure that any\r\n // close will seem instantaneous and events are prevented from being\r\n // raised after the close call\r\n var dispatchIfStillActive = function (stream, fn) {\r\n _this.queue.enqueue(function () { return __awaiter(_this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // Only raise events if the stream instance has not changed\r\n if (this.stream === stream) {\r\n return [2 /*return*/, fn()];\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n };\r\n // Only start stream if listener has not changed\r\n if (this.listener !== null) {\r\n var currentStream_1 = this.startRpc(token);\r\n this.stream = currentStream_1;\r\n this.stream.onOpen(function () {\r\n dispatchIfStillActive(currentStream_1, function () {\r\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\r\n _this.state = PersistentStreamState.Open;\r\n return _this.listener.onOpen();\r\n });\r\n });\r\n this.stream.onClose(function (error$$1) {\r\n dispatchIfStillActive(currentStream_1, function () {\r\n return _this.handleStreamClose(error$$1);\r\n });\r\n });\r\n this.stream.onMessage(function (msg) {\r\n dispatchIfStillActive(currentStream_1, function () {\r\n return _this.onMessage(msg);\r\n });\r\n });\r\n }\r\n };\r\n PersistentStream.prototype.performBackoff = function (listener) {\r\n var _this = this;\r\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\r\n this.state = PersistentStreamState.Backoff;\r\n this.backoff.backoffAndRun(function () { return __awaiter(_this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (this.state === PersistentStreamState.Stopped) {\r\n // We should have canceled the backoff timer when the stream was\r\n // closed, but just in case we make this a no-op.\r\n return [2 /*return*/];\r\n }\r\n this.state = PersistentStreamState.Initial;\r\n this.start(listener);\r\n assert(this.isStarted(), 'PersistentStream should have started');\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n };\r\n PersistentStream.prototype.handleStreamClose = function (error$$1) {\r\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\r\n debug(LOG_TAG$7, \"close with error: \" + error$$1);\r\n this.stream = null;\r\n // In theory the stream could close cleanly, however, in our current model\r\n // we never expect this to happen because if we stop a stream ourselves,\r\n // this callback will never be called. To prevent cases where we retry\r\n // without a backoff accidentally, we set the stream to error in all cases.\r\n return this.close(PersistentStreamState.Error, error$$1);\r\n };\r\n return PersistentStream;\r\n}());\r\n/**\r\n * A PersistentStream that implements the Listen RPC.\r\n *\r\n * Once the Listen stream has called the openHandler, any number of listen and\r\n * unlisten calls calls can be sent to control what changes will be sent from\r\n * the server for ListenResponses.\r\n */\r\nvar PersistentListenStream = /** @class */ (function (_super) {\r\n __extends(PersistentListenStream, _super);\r\n function PersistentListenStream(queue, connection, credentials, serializer) {\r\n var _this = _super.call(this, queue, TimerId.ListenStreamConnectionBackoff, TimerId.ListenStreamIdle, connection, credentials) || this;\r\n _this.serializer = serializer;\r\n return _this;\r\n }\r\n PersistentListenStream.prototype.startRpc = function (token) {\r\n return this.connection.openStream('Listen', token);\r\n };\r\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\r\n // A successful response means the stream is healthy\r\n this.backoff.reset();\r\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\r\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\r\n return this.listener.onWatchChange(watchChange, snapshot);\r\n };\r\n /**\r\n * Registers interest in the results of the given query. If the query\r\n * includes a resumeToken it will be included in the request. Results that\r\n * affect the query will be streamed back as WatchChange messages that\r\n * reference the targetId.\r\n */\r\n PersistentListenStream.prototype.watch = function (queryData) {\r\n var request = {};\r\n request.database = this.serializer.encodedDatabaseId;\r\n request.addTarget = this.serializer.toTarget(queryData);\r\n var labels = this.serializer.toListenRequestLabels(queryData);\r\n if (labels) {\r\n request.labels = labels;\r\n }\r\n this.sendRequest(request);\r\n };\r\n /**\r\n * Unregisters interest in the results of the query associated with the\r\n * given targetId.\r\n */\r\n PersistentListenStream.prototype.unwatch = function (targetId) {\r\n var request = {};\r\n request.database = this.serializer.encodedDatabaseId;\r\n request.removeTarget = targetId;\r\n this.sendRequest(request);\r\n };\r\n return PersistentListenStream;\r\n}(PersistentStream));\r\n/**\r\n * A Stream that implements the Write RPC.\r\n *\r\n * The Write RPC requires the caller to maintain special streamToken\r\n * state in between calls, to help the server understand which responses the\r\n * client has processed by the time the next request is made. Every response\r\n * will contain a streamToken; this value must be passed to the next\r\n * request.\r\n *\r\n * After calling start() on this stream, the next request must be a handshake,\r\n * containing whatever streamToken is on hand. Once a response to this\r\n * request is received, all pending mutations may be submitted. When\r\n * submitting multiple batches of mutations at the same time, it's\r\n * okay to use the same streamToken for the calls to writeMutations.\r\n *\r\n * TODO(b/33271235): Use proto types\r\n */\r\nvar PersistentWriteStream = /** @class */ (function (_super) {\r\n __extends(PersistentWriteStream, _super);\r\n function PersistentWriteStream(queue, connection, credentials, serializer) {\r\n var _this = _super.call(this, queue, TimerId.WriteStreamConnectionBackoff, TimerId.WriteStreamIdle, connection, credentials) || this;\r\n _this.serializer = serializer;\r\n _this.handshakeComplete_ = false;\r\n return _this;\r\n }\r\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\r\n /**\r\n * Tracks whether or not a handshake has been successfully exchanged and\r\n * the stream is ready to accept mutations.\r\n */\r\n get: function () {\r\n return this.handshakeComplete_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n // Override of PersistentStream.start\r\n PersistentWriteStream.prototype.start = function (listener) {\r\n this.handshakeComplete_ = false;\r\n _super.prototype.start.call(this, listener);\r\n };\r\n PersistentWriteStream.prototype.tearDown = function () {\r\n if (this.handshakeComplete_) {\r\n this.writeMutations([]);\r\n }\r\n };\r\n PersistentWriteStream.prototype.startRpc = function (token) {\r\n return this.connection.openStream('Write', token);\r\n };\r\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\r\n // Always capture the last stream token.\r\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\r\n this.lastStreamToken = responseProto.streamToken;\r\n if (!this.handshakeComplete_) {\r\n // The first response is always the handshake response\r\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\r\n this.handshakeComplete_ = true;\r\n return this.listener.onHandshakeComplete();\r\n }\r\n else {\r\n // A successful first write response means the stream is healthy,\r\n // Note, that we could consider a successful handshake healthy, however,\r\n // the write itself might be causing an error we want to back off from.\r\n this.backoff.reset();\r\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\r\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\r\n return this.listener.onMutationResult(commitVersion, results);\r\n }\r\n };\r\n /**\r\n * Sends an initial streamToken to the server, performing the handshake\r\n * required to make the StreamingWrite RPC work. Subsequent\r\n * calls should wait until onHandshakeComplete was called.\r\n */\r\n PersistentWriteStream.prototype.writeHandshake = function () {\r\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\r\n assert(!this.handshakeComplete_, 'Handshake already completed');\r\n // TODO(dimond): Support stream resumption. We intentionally do not set the\r\n // stream token on the handshake, ignoring any stream token we might have.\r\n var request = {};\r\n request.database = this.serializer.encodedDatabaseId;\r\n this.sendRequest(request);\r\n };\r\n /** Sends a group of mutations to the Firestore backend to apply. */\r\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\r\n var _this = this;\r\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\r\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\r\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\r\n var request = {\r\n // Protos are typed with string, but we support UInt8Array on Node\r\n // tslint:disable-next-line:no-any\r\n streamToken: this.lastStreamToken,\r\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\r\n };\r\n this.sendRequest(request);\r\n };\r\n return PersistentWriteStream;\r\n}(PersistentStream));\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\r\n * which provides an interface that is more convenient for the rest of the\r\n * client SDK architecture to consume.\r\n */\r\nvar Datastore = /** @class */ (function () {\r\n function Datastore(queue, connection, credentials, serializer) {\r\n this.queue = queue;\r\n this.connection = connection;\r\n this.credentials = credentials;\r\n this.serializer = serializer;\r\n }\r\n Datastore.prototype.newPersistentWriteStream = function () {\r\n return new PersistentWriteStream(this.queue, this.connection, this.credentials, this.serializer);\r\n };\r\n Datastore.prototype.newPersistentWatchStream = function () {\r\n return new PersistentListenStream(this.queue, this.connection, this.credentials, this.serializer);\r\n };\r\n Datastore.prototype.commit = function (mutations) {\r\n var _this = this;\r\n var params = {\r\n database: this.serializer.encodedDatabaseId,\r\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\r\n };\r\n return this.invokeRPC('Commit', params).then(function (response) {\r\n return _this.serializer.fromWriteResults(response.writeResults);\r\n });\r\n };\r\n Datastore.prototype.lookup = function (keys) {\r\n var _this = this;\r\n var params = {\r\n database: this.serializer.encodedDatabaseId,\r\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\r\n };\r\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\r\n var docs = maybeDocumentMap();\r\n response.forEach(function (proto) {\r\n var doc = _this.serializer.fromMaybeDocument(proto);\r\n docs = docs.insert(doc.key, doc);\r\n });\r\n var result = [];\r\n keys.forEach(function (key) {\r\n var doc = docs.get(key);\r\n assert(!!doc, 'Missing entity in write response for ' + key);\r\n result.push(doc);\r\n });\r\n return result;\r\n });\r\n };\r\n /** Gets an auth token and invokes the provided RPC. */\r\n Datastore.prototype.invokeRPC = function (rpcName, request) {\r\n var _this = this;\r\n // TODO(mikelehen): Retry (with backoff) on token failures?\r\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\r\n return _this.connection.invokeRPC(rpcName, request, token);\r\n });\r\n };\r\n /** Gets an auth token and invokes the provided RPC with streamed results. */\r\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\r\n var _this = this;\r\n // TODO(mikelehen): Retry (with backoff) on token failures?\r\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\r\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\r\n });\r\n };\r\n return Datastore;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Internal transaction object responsible for accumulating the mutations to\r\n * perform and the base versions for any documents read.\r\n */\r\nvar Transaction = /** @class */ (function () {\r\n function Transaction(datastore) {\r\n this.datastore = datastore;\r\n // The version of each document that was read during this transaction.\r\n this.readVersions = documentVersionMap();\r\n this.mutations = [];\r\n this.committed = false;\r\n }\r\n Transaction.prototype.recordVersion = function (doc) {\r\n var docVersion = doc.version;\r\n if (doc instanceof NoDocument) {\r\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\r\n docVersion = SnapshotVersion.forDeletedDoc();\r\n }\r\n var existingVersion = this.readVersions.get(doc.key);\r\n if (existingVersion !== null) {\r\n if (!docVersion.isEqual(existingVersion)) {\r\n // This transaction will fail no matter what.\r\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\r\n }\r\n }\r\n else {\r\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\r\n }\r\n };\r\n Transaction.prototype.lookup = function (keys) {\r\n var _this = this;\r\n if (this.committed) {\r\n return Promise.reject('Transaction has already completed.');\r\n }\r\n if (this.mutations.length > 0) {\r\n return Promise.reject('Transactions lookups are invalid after writes.');\r\n }\r\n return this.datastore.lookup(keys).then(function (docs) {\r\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\r\n return docs;\r\n });\r\n };\r\n Transaction.prototype.write = function (mutations) {\r\n if (this.committed) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\r\n }\r\n this.mutations = this.mutations.concat(mutations);\r\n };\r\n /**\r\n * Returns the version of this document when it was read in this transaction,\r\n * as a precondition, or no precondition if it was not read.\r\n */\r\n Transaction.prototype.precondition = function (key) {\r\n var version = this.readVersions.get(key);\r\n if (version) {\r\n return Precondition.updateTime(version);\r\n }\r\n else {\r\n return Precondition.NONE;\r\n }\r\n };\r\n /**\r\n * Returns the precondition for a document if the operation is an update.\r\n */\r\n Transaction.prototype.preconditionForUpdate = function (key) {\r\n var version = this.readVersions.get(key);\r\n if (version && version.isEqual(SnapshotVersion.forDeletedDoc())) {\r\n // The document doesn't exist, so fail the transaction.\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\r\n }\r\n else if (version) {\r\n // Document exists, base precondition on document update time.\r\n return Precondition.updateTime(version);\r\n }\r\n else {\r\n // Document was not read, so we just use the preconditions for a blind\r\n // update.\r\n return Precondition.exists(true);\r\n }\r\n };\r\n Transaction.prototype.set = function (key, data) {\r\n this.write(data.toMutations(key, this.precondition(key)));\r\n };\r\n Transaction.prototype.update = function (key, data) {\r\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\r\n };\r\n Transaction.prototype.delete = function (key) {\r\n this.write([new DeleteMutation(key, this.precondition(key))]);\r\n // Since the delete will be applied before all following writes, we need to\r\n // ensure that the precondition for the next write will be exists: false.\r\n this.readVersions = this.readVersions.insert(key, SnapshotVersion.forDeletedDoc());\r\n };\r\n Transaction.prototype.commit = function () {\r\n var _this = this;\r\n var unwritten = this.readVersions;\r\n // For each mutation, note that the doc was written.\r\n this.mutations.forEach(function (mutation) {\r\n unwritten = unwritten.remove(mutation.key);\r\n });\r\n if (!unwritten.isEmpty()) {\r\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\r\n }\r\n return this.datastore.commit(this.mutations).then(function () {\r\n _this.committed = true;\r\n });\r\n };\r\n return Transaction;\r\n}());\n\n/**\r\n * Copyright 2018 Google Inc.\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\nvar LOG_TAG$8 = 'OnlineStateTracker';\r\n// To deal with transient failures, we allow multiple stream attempts before\r\n// giving up and transitioning from OnlineState.Unknown to Offline.\r\nvar MAX_WATCH_STREAM_FAILURES = 2;\r\n// To deal with stream attempts that don't succeed or fail in a timely manner,\r\n// we have a timeout for OnlineState to reach Online or Offline.\r\n// If the timeout is reached, we transition to Offline rather than waiting\r\n// indefinitely.\r\nvar ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\r\n/**\r\n * A component used by the RemoteStore to track the OnlineState (that is,\r\n * whether or not the client as a whole should be considered to be online or\r\n * offline), implementing the appropriate heuristics.\r\n *\r\n * In particular, when the client is trying to connect to the backend, we\r\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\r\n * a connection to succeed. If we have too many failures or the timeout elapses,\r\n * then we set the OnlineState to Offline, and the client will behave as if\r\n * it is offline (get()s will return cached data, etc.).\r\n */\r\nvar OnlineStateTracker = /** @class */ (function () {\r\n function OnlineStateTracker(asyncQueue, onlineStateHandler) {\r\n this.asyncQueue = asyncQueue;\r\n this.onlineStateHandler = onlineStateHandler;\r\n /** The current OnlineState. */\r\n this.state = OnlineState.Unknown;\r\n /**\r\n * A count of consecutive failures to open the stream. If it reaches the\r\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\r\n * Offline.\r\n */\r\n this.watchStreamFailures = 0;\r\n /**\r\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\r\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\r\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\r\n */\r\n this.onlineStateTimer = null;\r\n /**\r\n * Whether the client should log a warning message if it fails to connect to\r\n * the backend (initially true, cleared after a successful stream, or if we've\r\n * logged the message already).\r\n */\r\n this.shouldWarnClientIsOffline = true;\r\n }\r\n /**\r\n * Called by RemoteStore when a watch stream is started (including on each\r\n * backoff attempt).\r\n *\r\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\r\n * the onlineStateTimer.\r\n */\r\n OnlineStateTracker.prototype.handleWatchStreamStart = function () {\r\n var _this = this;\r\n if (this.watchStreamFailures === 0) {\r\n this.setAndBroadcast(OnlineState.Unknown);\r\n assert(this.onlineStateTimer === null, \"onlineStateTimer shouldn't be started yet\");\r\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(TimerId.OnlineStateTimeout, ONLINE_STATE_TIMEOUT_MS, function () {\r\n _this.onlineStateTimer = null;\r\n assert(_this.state === OnlineState.Unknown, 'Timer should be canceled if we transitioned to a different state.');\r\n debug(LOG_TAG$8, \"Watch stream didn't reach online or offline within \" +\r\n (ONLINE_STATE_TIMEOUT_MS + \"ms. Considering client offline.\"));\r\n _this.logClientOfflineWarningIfNecessary();\r\n _this.setAndBroadcast(OnlineState.Offline);\r\n // NOTE: handleWatchStreamFailure() will continue to increment\r\n // watchStreamFailures even though we are already marked Offline,\r\n // but this is non-harmful.\r\n return Promise.resolve();\r\n });\r\n }\r\n };\r\n /**\r\n * Updates our OnlineState as appropriate after the watch stream reports a\r\n * failure. The first failure moves us to the 'Unknown' state. We then may\r\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\r\n * actually transition to the 'Offline' state.\r\n */\r\n OnlineStateTracker.prototype.handleWatchStreamFailure = function () {\r\n if (this.state === OnlineState.Online) {\r\n this.setAndBroadcast(OnlineState.Unknown);\r\n // To get to OnlineState.Online, set() must have been called which would\r\n // have reset our heuristics.\r\n assert(this.watchStreamFailures === 0, 'watchStreamFailures must be 0');\r\n assert(this.onlineStateTimer === null, 'onlineStateTimer must be null');\r\n }\r\n else {\r\n this.watchStreamFailures++;\r\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\r\n this.clearOnlineStateTimer();\r\n this.logClientOfflineWarningIfNecessary();\r\n this.setAndBroadcast(OnlineState.Offline);\r\n }\r\n }\r\n };\r\n /**\r\n * Explicitly sets the OnlineState to the specified state.\r\n *\r\n * Note that this resets our timers / failure counters, etc. used by our\r\n * Offline heuristics, so must not be used in place of\r\n * handleWatchStreamStart() and handleWatchStreamFailure().\r\n */\r\n OnlineStateTracker.prototype.set = function (newState) {\r\n this.clearOnlineStateTimer();\r\n this.watchStreamFailures = 0;\r\n if (newState === OnlineState.Online) {\r\n // We've connected to watch at least once. Don't warn the developer\r\n // about being offline going forward.\r\n this.shouldWarnClientIsOffline = false;\r\n }\r\n this.setAndBroadcast(newState);\r\n };\r\n OnlineStateTracker.prototype.setAndBroadcast = function (newState) {\r\n if (newState !== this.state) {\r\n this.state = newState;\r\n this.onlineStateHandler(newState);\r\n }\r\n };\r\n OnlineStateTracker.prototype.logClientOfflineWarningIfNecessary = function () {\r\n if (this.shouldWarnClientIsOffline) {\r\n error('Could not reach Firestore backend.');\r\n this.shouldWarnClientIsOffline = false;\r\n }\r\n };\r\n OnlineStateTracker.prototype.clearOnlineStateTimer = function () {\r\n if (this.onlineStateTimer !== null) {\r\n this.onlineStateTimer.cancel();\r\n this.onlineStateTimer = null;\r\n }\r\n };\r\n return OnlineStateTracker;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$9 = 'RemoteStore';\r\n// TODO(b/35853402): Negotiate this with the stream.\r\nvar MAX_PENDING_WRITES = 10;\r\n/**\r\n * RemoteStore - An interface to remotely stored data, basically providing a\r\n * wrapper around the Datastore that is more reliable for the rest of the\r\n * system.\r\n *\r\n * RemoteStore is responsible for maintaining the connection to the server.\r\n * - maintaining a list of active listens.\r\n * - reconnecting when the connection is dropped.\r\n * - resuming all the active listens on reconnect.\r\n *\r\n * RemoteStore handles all incoming events from the Datastore.\r\n * - listening to the watch stream and repackaging the events as RemoteEvents\r\n * - notifying SyncEngine of any changes to the active listens.\r\n *\r\n * RemoteStore takes writes from other components and handles them reliably.\r\n * - pulling pending mutations from LocalStore and sending them to Datastore.\r\n * - retrying mutations that failed because of network problems.\r\n * - acking mutations to the SyncEngine once they are accepted or rejected.\r\n */\r\nvar RemoteStore = /** @class */ (function () {\r\n function RemoteStore(\r\n /**\r\n * The local store, used to fill the write pipeline with outbound\r\n * mutations and resolve existence filter mismatches.\r\n */\r\n localStore, \r\n /** The client-side proxy for interacting with the backend. */\r\n datastore, asyncQueue, onlineStateHandler) {\r\n this.localStore = localStore;\r\n this.datastore = datastore;\r\n this.pendingWrites = [];\r\n this.lastBatchSeen = BATCHID_UNKNOWN;\r\n /**\r\n * A mapping of watched targets that the client cares about tracking and the\r\n * user has explicitly called a 'listen' for this target.\r\n *\r\n * These targets may or may not have been sent to or acknowledged by the\r\n * server. On re-establishing the listen stream, these targets should be sent\r\n * to the server. The targets removed with unlistens are removed eagerly\r\n * without waiting for confirmation from the listen stream.\r\n */\r\n this.listenTargets = {};\r\n /**\r\n * A mapping of targetId to pending acks needed.\r\n *\r\n * If a targetId is present in this map, then we're waiting for watch to\r\n * acknowledge a removal or addition of the target. If a target is not in this\r\n * mapping, and it's in the listenTargets map, then we consider the target to\r\n * be active.\r\n *\r\n * We increment the count here every time we issue a request over the stream\r\n * to watch or unwatch. We then decrement the count every time we get a target\r\n * added or target removed message from the server. Once the count is equal to\r\n * 0 we know that the client and server are in the same state (once this state\r\n * is reached the targetId is removed from the map to free the memory).\r\n */\r\n this.pendingTargetResponses = {};\r\n this.accumulatedWatchChanges = [];\r\n this.watchStream = null;\r\n this.writeStream = null;\r\n this.onlineStateTracker = new OnlineStateTracker(asyncQueue, onlineStateHandler);\r\n }\r\n /**\r\n * Starts up the remote store, creating streams, restoring state from\r\n * LocalStore, etc.\r\n */\r\n RemoteStore.prototype.start = function () {\r\n return this.enableNetwork();\r\n };\r\n RemoteStore.prototype.isNetworkEnabled = function () {\r\n assert((this.watchStream == null) === (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\r\n return this.watchStream != null;\r\n };\r\n /** Re-enables the network. Idempotent. */\r\n RemoteStore.prototype.enableNetwork = function () {\r\n var _this = this;\r\n if (this.isNetworkEnabled()) {\r\n return Promise.resolve();\r\n }\r\n // Create new streams (but note they're not started yet).\r\n this.watchStream = this.datastore.newPersistentWatchStream();\r\n this.writeStream = this.datastore.newPersistentWriteStream();\r\n // Load any saved stream token from persistent storage\r\n return this.localStore.getLastStreamToken().then(function (token) {\r\n _this.writeStream.lastStreamToken = token;\r\n if (_this.shouldStartWatchStream()) {\r\n _this.startWatchStream();\r\n }\r\n else {\r\n _this.onlineStateTracker.set(OnlineState.Unknown);\r\n }\r\n return _this.fillWritePipeline(); // This may start the writeStream.\r\n });\r\n };\r\n /**\r\n * Temporarily disables the network. The network can be re-enabled using\r\n * enableNetwork().\r\n */\r\n RemoteStore.prototype.disableNetwork = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n this.disableNetworkInternal();\r\n // Set the OnlineState to Offline so get()s return from cache, etc.\r\n this.onlineStateTracker.set(OnlineState.Offline);\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /**\r\n * Disables the network, if it is currently enabled.\r\n */\r\n RemoteStore.prototype.disableNetworkInternal = function () {\r\n if (this.isNetworkEnabled()) {\r\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\r\n // event).\r\n this.watchStream.stop();\r\n this.writeStream.stop();\r\n this.cleanUpWatchStreamState();\r\n this.cleanUpWriteStreamState();\r\n this.writeStream = null;\r\n this.watchStream = null;\r\n }\r\n };\r\n RemoteStore.prototype.shutdown = function () {\r\n debug(LOG_TAG$9, 'RemoteStore shutting down.');\r\n this.disableNetworkInternal();\r\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\r\n // triggering spurious listener events with cached data, etc.\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n return Promise.resolve();\r\n };\r\n /** Starts new listen for the given query. Uses resume token if provided */\r\n RemoteStore.prototype.listen = function (queryData) {\r\n assert(!contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\r\n // Mark this as something the client is currently listening for.\r\n this.listenTargets[queryData.targetId] = queryData;\r\n if (this.shouldStartWatchStream()) {\r\n // The listen will be sent in onWatchStreamOpen\r\n this.startWatchStream();\r\n }\r\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\r\n this.sendWatchRequest(queryData);\r\n }\r\n };\r\n /** Removes the listen from server */\r\n RemoteStore.prototype.unlisten = function (targetId) {\r\n assert(contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\r\n delete this.listenTargets[targetId];\r\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\r\n this.sendUnwatchRequest(targetId);\r\n if (isEmpty(this.listenTargets)) {\r\n this.watchStream.markIdle();\r\n }\r\n }\r\n };\r\n /**\r\n * We need to increment the the expected number of pending responses we're due\r\n * from watch so we wait for the ack to process any messages from this target.\r\n */\r\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\r\n this.recordPendingTargetRequest(queryData.targetId);\r\n this.watchStream.watch(queryData);\r\n };\r\n /**\r\n * We need to increment the expected number of pending responses we're due\r\n * from watch so we wait for the removal on the server before we process any\r\n * messages from this target.\r\n */\r\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\r\n this.recordPendingTargetRequest(targetId);\r\n this.watchStream.unwatch(targetId);\r\n };\r\n /**\r\n * Increment the mapping of how many acks are needed from watch before we can\r\n * consider the server to be 'in-sync' with the client's active targets.\r\n */\r\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\r\n // For each request we get we need to record we need a response for it.\r\n this.pendingTargetResponses[targetId] =\r\n (this.pendingTargetResponses[targetId] || 0) + 1;\r\n };\r\n RemoteStore.prototype.startWatchStream = function () {\r\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\r\n this.watchStream.start({\r\n onOpen: this.onWatchStreamOpen.bind(this),\r\n onClose: this.onWatchStreamClose.bind(this),\r\n onWatchChange: this.onWatchStreamChange.bind(this)\r\n });\r\n this.onlineStateTracker.handleWatchStreamStart();\r\n };\r\n /**\r\n * Returns whether the watch stream should be started because it's necessary\r\n * and has not yet been started.\r\n */\r\n RemoteStore.prototype.shouldStartWatchStream = function () {\r\n return (this.isNetworkEnabled() &&\r\n !this.watchStream.isStarted() &&\r\n !isEmpty(this.listenTargets));\r\n };\r\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\r\n // If the connection is closed then we'll never get a snapshot version for\r\n // the accumulated changes and so we'll never be able to complete the batch.\r\n // When we start up again the server is going to resend these changes\r\n // anyway, so just toss the accumulated state.\r\n this.accumulatedWatchChanges = [];\r\n this.pendingTargetResponses = {};\r\n };\r\n RemoteStore.prototype.onWatchStreamOpen = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n return __generator(this, function (_a) {\r\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\r\n // targets are active\r\n forEachNumber(this.listenTargets, function (targetId, queryData) {\r\n _this.sendWatchRequest(queryData);\r\n });\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.onWatchStreamClose = function (error$$1) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\r\n this.cleanUpWatchStreamState();\r\n this.onlineStateTracker.handleWatchStreamFailure();\r\n // If there was an error, retry the connection.\r\n if (this.shouldStartWatchStream()) {\r\n this.startWatchStream();\r\n }\r\n else {\r\n // No need to restart watch stream because there are no active targets.\r\n // The online state is set to unknown because there is no active attempt\r\n // at establishing a connection\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var changes;\r\n return __generator(this, function (_a) {\r\n // Mark the client as online since we got a message from the server\r\n this.onlineStateTracker.set(OnlineState.Online);\r\n if (watchChange instanceof WatchTargetChange &&\r\n watchChange.state === WatchTargetChangeState.Removed &&\r\n watchChange.cause) {\r\n // There was an error on a target, don't wait for a consistent snapshot\r\n // to raise events\r\n return [2 /*return*/, this.handleTargetError(watchChange)];\r\n }\r\n // Accumulate watch changes but don't process them if there's no\r\n // snapshotVersion or it's older than a previous snapshot we've processed\r\n // (can happen after we resume a target using a resume token).\r\n this.accumulatedWatchChanges.push(watchChange);\r\n if (!snapshotVersion.isEqual(SnapshotVersion.MIN) &&\r\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\r\n changes = this.accumulatedWatchChanges;\r\n this.accumulatedWatchChanges = [];\r\n return [2 /*return*/, this.handleWatchChangeBatch(snapshotVersion, changes)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /**\r\n * Takes a batch of changes from the Datastore, repackages them as a\r\n * RemoteEvent, and passes that on to the listener, which is typically the\r\n * SyncEngine.\r\n */\r\n RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\r\n var _this = this;\r\n var aggregator = new WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\r\n aggregator.addChanges(changes);\r\n var remoteEvent = aggregator.createRemoteEvent();\r\n // Get the new response counts from the aggregator\r\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\r\n var promises = [];\r\n // Handle existence filters and existence filter mismatches.\r\n forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\r\n var queryData = _this.listenTargets[targetId];\r\n if (!queryData) {\r\n // A watched target might have been removed already.\r\n return;\r\n }\r\n var query = queryData.query;\r\n if (query.isDocumentQuery()) {\r\n if (filter.count === 0) {\r\n // The existence filter told us the document does not exist.\r\n // We need to deduce that this document does not exist and apply\r\n // a deleted document to our updates. Without applying a deleted\r\n // document there might be another query that will raise this\r\n // document as part of a snapshot until it is resolved,\r\n // essentially exposing inconsistency between queries.\r\n var key = new DocumentKey(query.path);\r\n var deletedDoc = new NoDocument(key, snapshotVersion);\r\n remoteEvent.addDocumentUpdate(deletedDoc);\r\n }\r\n else {\r\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\r\n }\r\n }\r\n else {\r\n // Not a document query.\r\n var promise = _this.localStore\r\n .remoteDocumentKeys(targetId)\r\n .then(function (trackedRemote) {\r\n if (remoteEvent.targetChanges[targetId]) {\r\n var mapping = remoteEvent.targetChanges[targetId].mapping;\r\n if (mapping !== null) {\r\n if (mapping instanceof UpdateMapping) {\r\n trackedRemote = mapping.applyToKeySet(trackedRemote);\r\n }\r\n else {\r\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\r\n mapping);\r\n trackedRemote = mapping.documents;\r\n }\r\n }\r\n }\r\n if (trackedRemote.size !== filter.count) {\r\n // Existence filter mismatch, resetting mapping.\r\n // Make sure the mismatch is exposed in the remote event.\r\n remoteEvent.handleExistenceFilterMismatch(targetId);\r\n // Clear the resume token for the query, since we're in a\r\n // known mismatch state.\r\n var newQueryData = new QueryData(query, targetId, queryData.purpose);\r\n _this.listenTargets[targetId] = newQueryData;\r\n // Cause a hard reset by unwatching and rewatching\r\n // immediately, but deliberately don't send a resume token\r\n // so that we get a full update.\r\n // Make sure we expect that this acks are going to happen.\r\n _this.sendUnwatchRequest(targetId);\r\n // Mark the query we send as being on behalf of an existence\r\n // filter mismatch, but don't actually retain that in\r\n // listenTargets. This ensures that we flag the first\r\n // re-listen this way without impacting future listens of\r\n // this target (that might happen e.g. on reconnect).\r\n var requestQueryData = new QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\r\n _this.sendWatchRequest(requestQueryData);\r\n }\r\n });\r\n promises.push(promise);\r\n }\r\n });\r\n return Promise.all(promises).then(function () {\r\n // Update in-memory resume tokens. LocalStore will update the\r\n // persistent view of these when applying the completed RemoteEvent.\r\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\r\n if (change.resumeToken.length > 0) {\r\n var queryData = _this.listenTargets[targetId];\r\n // A watched target might have been removed already.\r\n if (queryData) {\r\n _this.listenTargets[targetId] = queryData.update({\r\n resumeToken: change.resumeToken,\r\n snapshotVersion: change.snapshotVersion\r\n });\r\n }\r\n }\r\n });\r\n // Finally handle remote event\r\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\r\n });\r\n };\r\n /** Handles an error on a target */\r\n RemoteStore.prototype.handleTargetError = function (watchChange) {\r\n var _this = this;\r\n assert(!!watchChange.cause, 'Handling target error without a cause');\r\n var error$$1 = watchChange.cause;\r\n var promiseChain = Promise.resolve();\r\n watchChange.targetIds.forEach(function (targetId) {\r\n promiseChain = promiseChain.then(function () { return __awaiter(_this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // A watched target might have been removed already.\r\n if (contains(this.listenTargets, targetId)) {\r\n delete this.listenTargets[targetId];\r\n return [2 /*return*/, this.syncEngine.rejectListen(targetId, error$$1)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n });\r\n return promiseChain;\r\n };\r\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\r\n this.lastBatchSeen = BATCHID_UNKNOWN;\r\n debug(LOG_TAG$9, 'Stopping write stream with ' +\r\n this.pendingWrites.length +\r\n ' pending writes');\r\n this.pendingWrites = [];\r\n };\r\n /**\r\n * Notifies that there are new mutations to process in the queue. This is\r\n * typically called by SyncEngine after it has sent mutations to LocalStore.\r\n */\r\n RemoteStore.prototype.fillWritePipeline = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n return __generator(this, function (_a) {\r\n if (this.canWriteMutations()) {\r\n return [2 /*return*/, this.localStore\r\n .nextMutationBatch(this.lastBatchSeen)\r\n .then(function (batch) {\r\n if (batch === null) {\r\n if (_this.pendingWrites.length === 0) {\r\n _this.writeStream.markIdle();\r\n }\r\n }\r\n else {\r\n _this.commit(batch);\r\n return _this.fillWritePipeline();\r\n }\r\n })];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /**\r\n * Returns true if the backend can accept additional write requests.\r\n *\r\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\r\n * call this method first to check if more mutations can be sent.\r\n *\r\n * Currently the only thing that can prevent the backend from accepting\r\n * write requests is if there are too many requests already outstanding. As\r\n * writes complete the backend will be able to accept more.\r\n */\r\n RemoteStore.prototype.canWriteMutations = function () {\r\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\r\n };\r\n // For testing\r\n RemoteStore.prototype.outstandingWrites = function () {\r\n return this.pendingWrites.length;\r\n };\r\n /**\r\n * Given mutations to commit, actually commits them to the Datastore. Note\r\n * that this does *not* return a Promise specifically because the AsyncQueue\r\n * should not block operations for this.\r\n */\r\n RemoteStore.prototype.commit = function (batch) {\r\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\r\n this.lastBatchSeen = batch.batchId;\r\n this.pendingWrites.push(batch);\r\n if (this.shouldStartWriteStream()) {\r\n this.startWriteStream();\r\n }\r\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\r\n this.writeStream.writeMutations(batch.mutations);\r\n }\r\n };\r\n RemoteStore.prototype.shouldStartWriteStream = function () {\r\n return (this.isNetworkEnabled() &&\r\n !this.writeStream.isStarted() &&\r\n this.pendingWrites.length > 0);\r\n };\r\n RemoteStore.prototype.startWriteStream = function () {\r\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\r\n this.writeStream.start({\r\n onOpen: this.onWriteStreamOpen.bind(this),\r\n onClose: this.onWriteStreamClose.bind(this),\r\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\r\n onMutationResult: this.onMutationResult.bind(this)\r\n });\r\n };\r\n RemoteStore.prototype.onWriteStreamOpen = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n this.writeStream.writeHandshake();\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\r\n var _this = this;\r\n // Record the stream token.\r\n return this.localStore\r\n .setLastStreamToken(this.writeStream.lastStreamToken)\r\n .then(function () {\r\n // Drain any pending writes.\r\n //\r\n // Note that at this point pendingWrites contains mutations that\r\n // have already been accepted by fillWritePipeline/commitBatch. If\r\n // the pipeline is full, canWriteMutations will be false, despite\r\n // the fact that we actually need to send mutations over.\r\n //\r\n // This also means that this method indirectly respects the limits\r\n // imposed by canWriteMutations since writes can't be added to the\r\n // pendingWrites array when canWriteMutations is false. If the\r\n // limits imposed by canWriteMutations actually protect us from\r\n // DOSing ourselves then those limits won't be exceeded here and\r\n // we'll continue to make progress.\r\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\r\n var batch = _a[_i];\r\n _this.writeStream.writeMutations(batch.mutations);\r\n }\r\n });\r\n };\r\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\r\n var _this = this;\r\n // This is a response to a write containing mutations and should be\r\n // correlated to the first pending write.\r\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\r\n var batch = this.pendingWrites.shift();\r\n var success = MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\r\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\r\n // It's possible that with the completion of this mutation another\r\n // slot has freed up.\r\n return _this.fillWritePipeline();\r\n });\r\n };\r\n RemoteStore.prototype.onWriteStreamClose = function (error$$1) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n var errorHandling;\r\n return __generator(this, function (_a) {\r\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\r\n // If the write stream closed due to an error, invoke the error callbacks if\r\n // there are pending writes.\r\n if (error$$1 && this.pendingWrites.length > 0) {\r\n assert(!!error$$1, 'We have pending writes, but the write stream closed without an error');\r\n errorHandling = void 0;\r\n if (this.writeStream.handshakeComplete) {\r\n // This error affects the actual write.\r\n errorHandling = this.handleWriteError(error$$1);\r\n }\r\n else {\r\n // If there was an error before the handshake has finished, it's\r\n // possible that the server is unable to process the stream token\r\n // we're sending. (Perhaps it's too old?)\r\n errorHandling = this.handleHandshakeError(error$$1);\r\n }\r\n return [2 /*return*/, errorHandling.then(function () {\r\n // The write stream might have been started by refilling the write\r\n // pipeline for failed writes\r\n if (_this.shouldStartWriteStream()) {\r\n _this.startWriteStream();\r\n }\r\n })];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.handleHandshakeError = function (error$$1) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // Reset the token if it's a permanent error or the error code is\r\n // ABORTED, signaling the write stream is no longer valid.\r\n if (isPermanentError(error$$1.code) || error$$1.code === Code.ABORTED) {\r\n debug(LOG_TAG$9, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\r\n this.writeStream.lastStreamToken = emptyByteString();\r\n return [2 /*return*/, this.localStore.setLastStreamToken(emptyByteString())];\r\n }\r\n else {\r\n // Some other error, don't reset stream token. Our stream logic will\r\n // just retry with exponential backoff.\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.handleWriteError = function (error$$1) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n var batch;\r\n return __generator(this, function (_a) {\r\n if (isPermanentError(error$$1.code)) {\r\n batch = this.pendingWrites.shift();\r\n // In this case it's also unlikely that the server itself is melting\r\n // down -- this was just a bad request so inhibit backoff on the next\r\n // restart.\r\n this.writeStream.inhibitBackoff();\r\n return [2 /*return*/, this.syncEngine\r\n .rejectFailedWrite(batch.batchId, error$$1)\r\n .then(function () {\r\n // It's possible that with the completion of this mutation\r\n // another slot has freed up.\r\n return _this.fillWritePipeline();\r\n })];\r\n }\r\n else {\r\n // Transient error, just let the retry logic kick in.\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.createTransaction = function () {\r\n return new Transaction(this.datastore);\r\n };\r\n RemoteStore.prototype.handleUserChange = function (user) {\r\n debug(LOG_TAG$9, 'RemoteStore changing users: uid=', user.uid);\r\n // If the network has been explicitly disabled, make sure we don't\r\n // accidentally re-enable it.\r\n if (this.isNetworkEnabled()) {\r\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\r\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\r\n // (since mutations are per-user).\r\n this.disableNetworkInternal();\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n return this.enableNetwork();\r\n }\r\n };\r\n return RemoteStore;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar LOG_TAG$10 = 'FirestoreClient';\r\n/**\r\n * FirestoreClient is a top-level class that constructs and owns all of the\r\n * pieces of the client SDK architecture. It is responsible for creating the\r\n * async queue that is shared by all of the other components in the system.\r\n */\r\nvar FirestoreClient = /** @class */ (function () {\r\n function FirestoreClient(platform, databaseInfo, credentials, \r\n /**\r\n * Asynchronous queue responsible for all of our internal processing. When\r\n * we get incoming work from the user (via public API) or the network\r\n * (incoming GRPC messages), we should always schedule onto this queue.\r\n * This ensures all of our work is properly serialized (e.g. we don't\r\n * start processing a new operation while the previous one is waiting for\r\n * an async I/O to complete).\r\n */\r\n asyncQueue) {\r\n this.platform = platform;\r\n this.databaseInfo = databaseInfo;\r\n this.credentials = credentials;\r\n this.asyncQueue = asyncQueue;\r\n }\r\n /**\r\n * Starts up the FirestoreClient, returning only whether or not enabling\r\n * persistence succeeded.\r\n *\r\n * The intent here is to \"do the right thing\" as far as users are concerned.\r\n * Namely, in cases where offline persistence is requested and possible,\r\n * enable it, but otherwise fall back to persistence disabled. For the most\r\n * part we expect this to succeed one way or the other so we don't expect our\r\n * users to actually wait on the firestore.enablePersistence Promise since\r\n * they generally won't care.\r\n *\r\n * Of course some users actually do care about whether or not persistence\r\n * was successfully enabled, so the Promise returned from this method\r\n * indicates this outcome.\r\n *\r\n * This presents a problem though: even before enablePersistence resolves or\r\n * rejects, users may have made calls to e.g. firestore.collection() which\r\n * means that the FirestoreClient in there will be available and will be\r\n * enqueuing actions on the async queue.\r\n *\r\n * Meanwhile any failure of an operation on the async queue causes it to\r\n * panic and reject any further work, on the premise that unhandled errors\r\n * are fatal.\r\n *\r\n * Consequently the fallback is handled internally here in start, and if the\r\n * fallback succeeds we signal success to the async queue even though the\r\n * start() itself signals failure.\r\n *\r\n * @param usePersistence Whether or not to attempt to enable persistence.\r\n * @returns A deferred result indicating the user-visible result of enabling\r\n * offline persistence. This method will reject this if IndexedDB fails to\r\n * start for any reason. If usePersistence is false this is\r\n * unconditionally resolved.\r\n */\r\n FirestoreClient.prototype.start = function (usePersistence) {\r\n var _this = this;\r\n // We defer our initialization until we get the current user from\r\n // setUserChangeListener(). We block the async queue until we got the\r\n // initial user and the initialization is completed. This will prevent\r\n // any scheduled work from happening before initialization is completed.\r\n //\r\n // If initializationDone resolved then the FirestoreClient is in a usable\r\n // state.\r\n var initializationDone = new Deferred();\r\n // If usePersistence is true, certain classes of errors while starting are\r\n // recoverable but only by falling back to persistence disabled.\r\n //\r\n // If there's an error in the first case but not in recovery we cannot\r\n // reject the promise blocking the async queue because this will cause the\r\n // async queue to panic.\r\n var persistenceResult = new Deferred();\r\n var initialized = false;\r\n this.credentials.setUserChangeListener(function (user) {\r\n if (!initialized) {\r\n initialized = true;\r\n _this.initializePersistence(usePersistence, persistenceResult)\r\n .then(function () { return _this.initializeRest(user); })\r\n .then(initializationDone.resolve, initializationDone.reject);\r\n }\r\n else {\r\n _this.asyncQueue.enqueue(function () {\r\n return _this.handleUserChange(user);\r\n });\r\n }\r\n });\r\n // Block the async queue until initialization is done\r\n this.asyncQueue.enqueue(function () {\r\n return initializationDone.promise;\r\n });\r\n // Return only the result of enabling persistence. Note that this does not\r\n // need to await the completion of initializationDone because the result of\r\n // this method should not reflect any other kind of failure to start.\r\n return persistenceResult.promise;\r\n };\r\n /** Enables the network connection and requeues all pending operations. */\r\n FirestoreClient.prototype.enableNetwork = function () {\r\n var _this = this;\r\n return this.asyncQueue.enqueue(function () {\r\n return _this.remoteStore.enableNetwork();\r\n });\r\n };\r\n /**\r\n * Initializes persistent storage, attempting to use IndexedDB if\r\n * usePersistence is true or memory-only if false.\r\n *\r\n * If IndexedDB fails because it's already open in another tab or because the\r\n * platform can't possibly support our implementation then this method rejects\r\n * the persistenceResult and falls back on memory-only persistence.\r\n *\r\n * @param usePersistence indicates whether or not to use offline persistence\r\n * @param persistenceResult A deferred result indicating the user-visible\r\n * result of enabling offline persistence. This method will reject this if\r\n * IndexedDB fails to start for any reason. If usePersistence is false\r\n * this is unconditionally resolved.\r\n * @returns a Promise indicating whether or not initialization should\r\n * continue, i.e. that one of the persistence implementations actually\r\n * succeeded.\r\n */\r\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\r\n var _this = this;\r\n if (usePersistence) {\r\n return this.startIndexedDbPersistence()\r\n .then(persistenceResult.resolve)\r\n .catch(function (error$$1) {\r\n // Regardless of whether or not the retry succeeds, from an user\r\n // perspective, offline persistence has failed.\r\n persistenceResult.reject(error$$1);\r\n // An unknown failure on the first stage shuts everything down.\r\n if (!_this.canFallback(error$$1)) {\r\n return Promise.reject(error$$1);\r\n }\r\n console.warn('Error enabling offline storage. Falling back to' +\r\n ' storage disabled: ' +\r\n error$$1);\r\n return _this.startMemoryPersistence();\r\n });\r\n }\r\n else {\r\n // When usePersistence == false, enabling offline persistence is defined\r\n // to unconditionally succeed. This allows start() to have the same\r\n // signature for both cases, despite the fact that the returned promise\r\n // is only used in the enablePersistence call.\r\n persistenceResult.resolve();\r\n return this.startMemoryPersistence();\r\n }\r\n };\r\n FirestoreClient.prototype.canFallback = function (error$$1) {\r\n return (error$$1.code === Code.FAILED_PRECONDITION ||\r\n error$$1.code === Code.UNIMPLEMENTED);\r\n };\r\n /**\r\n * Starts IndexedDB-based persistence.\r\n *\r\n * @returns A promise indicating success or failure.\r\n */\r\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\r\n // TODO(http://b/33384523): For now we just disable garbage collection\r\n // when persistence is enabled.\r\n this.garbageCollector = new NoOpGarbageCollector();\r\n var storagePrefix = IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\r\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\r\n var serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\r\n useProto3Json: true\r\n });\r\n this.persistence = new IndexedDbPersistence(storagePrefix, serializer);\r\n return this.persistence.start();\r\n };\r\n /**\r\n * Starts Memory-backed persistence. In practice this cannot fail.\r\n *\r\n * @returns A promise that will successfully resolve.\r\n */\r\n FirestoreClient.prototype.startMemoryPersistence = function () {\r\n this.garbageCollector = new EagerGarbageCollector();\r\n this.persistence = new MemoryPersistence();\r\n return this.persistence.start();\r\n };\r\n /**\r\n * Initializes the rest of the FirestoreClient, assuming the initial user\r\n * has been obtained from the credential provider and some persistence\r\n * implementation is available in this.persistence.\r\n */\r\n FirestoreClient.prototype.initializeRest = function (user) {\r\n var _this = this;\r\n return this.platform\r\n .loadConnection(this.databaseInfo)\r\n .then(function (connection) {\r\n _this.localStore = new LocalStore(_this.persistence, user, _this.garbageCollector);\r\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\r\n var datastore = new Datastore(_this.asyncQueue, connection, _this.credentials, serializer);\r\n var onlineStateChangedHandler = function (onlineState) {\r\n _this.syncEngine.applyOnlineStateChange(onlineState);\r\n _this.eventMgr.applyOnlineStateChange(onlineState);\r\n };\r\n _this.remoteStore = new RemoteStore(_this.localStore, datastore, _this.asyncQueue, onlineStateChangedHandler);\r\n _this.syncEngine = new SyncEngine(_this.localStore, _this.remoteStore, user);\r\n // Setup wiring between sync engine and remote store\r\n _this.remoteStore.syncEngine = _this.syncEngine;\r\n _this.eventMgr = new EventManager(_this.syncEngine);\r\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\r\n // tokens, refilling mutation queue, etc.) so must be started after\r\n // LocalStore.\r\n return _this.localStore.start();\r\n })\r\n .then(function () {\r\n return _this.remoteStore.start();\r\n });\r\n };\r\n FirestoreClient.prototype.handleUserChange = function (user) {\r\n this.asyncQueue.verifyOperationInProgress();\r\n debug(LOG_TAG$10, 'User Changed: ' + user.uid);\r\n return this.syncEngine.handleUserChange(user);\r\n };\r\n /** Disables the network connection. Pending operations will not complete. */\r\n FirestoreClient.prototype.disableNetwork = function () {\r\n var _this = this;\r\n return this.asyncQueue.enqueue(function () {\r\n return _this.remoteStore.disableNetwork();\r\n });\r\n };\r\n FirestoreClient.prototype.shutdown = function () {\r\n var _this = this;\r\n return this.asyncQueue\r\n .enqueue(function () {\r\n _this.credentials.removeUserChangeListener();\r\n return _this.remoteStore.shutdown();\r\n })\r\n .then(function () {\r\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\r\n return _this.persistence.shutdown();\r\n });\r\n };\r\n FirestoreClient.prototype.listen = function (query, observer, options) {\r\n var _this = this;\r\n var listener = new QueryListener(query, observer, options);\r\n this.asyncQueue.enqueue(function () {\r\n return _this.eventMgr.listen(listener);\r\n });\r\n return listener;\r\n };\r\n FirestoreClient.prototype.unlisten = function (listener) {\r\n var _this = this;\r\n this.asyncQueue.enqueue(function () {\r\n return _this.eventMgr.unlisten(listener);\r\n });\r\n };\r\n FirestoreClient.prototype.getDocumentFromLocalCache = function (docKey) {\r\n var _this = this;\r\n return this.asyncQueue\r\n .enqueue(function () {\r\n return _this.localStore.readDocument(docKey);\r\n })\r\n .then(function (maybeDoc) {\r\n if (maybeDoc instanceof Document) {\r\n return maybeDoc;\r\n }\r\n else {\r\n throw new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from cache. (However, this document may ' +\r\n \"exist on the server. Run again without setting 'source' in \" +\r\n 'the GetOptions to attempt to retrieve the document from the ' +\r\n 'server.)');\r\n }\r\n });\r\n };\r\n FirestoreClient.prototype.getDocumentsFromLocalCache = function (query) {\r\n var _this = this;\r\n return this.asyncQueue\r\n .enqueue(function () {\r\n return _this.localStore.executeQuery(query);\r\n })\r\n .then(function (docs) {\r\n var remoteKeys = documentKeySet();\r\n var view = new View(query, remoteKeys);\r\n var viewDocChanges = view.computeDocChanges(docs);\r\n return view.applyChanges(viewDocChanges).snapshot;\r\n });\r\n };\r\n FirestoreClient.prototype.write = function (mutations) {\r\n var _this = this;\r\n var deferred = new Deferred();\r\n this.asyncQueue.enqueue(function () { return _this.syncEngine.write(mutations, deferred); });\r\n return deferred.promise;\r\n };\r\n FirestoreClient.prototype.databaseId = function () {\r\n return this.databaseInfo.databaseId;\r\n };\r\n FirestoreClient.prototype.transaction = function (updateFunction) {\r\n var _this = this;\r\n // We have to wait for the async queue to be sure syncEngine is initialized.\r\n return this.asyncQueue\r\n .enqueue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {\r\n return [2 /*return*/];\r\n }); }); })\r\n .then(function () { return _this.syncEngine.runTransaction(updateFunction); });\r\n };\r\n return FirestoreClient;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * A wrapper implementation of Observer that will dispatch events\r\n * asynchronously. To allow immediate silencing, a mute call is added which\r\n * causes events scheduled to no longer be raised.\r\n */\r\nvar AsyncObserver = /** @class */ (function () {\r\n function AsyncObserver(observer) {\r\n this.observer = observer;\r\n /**\r\n * When set to true, will not raise future events. Necessary to deal with\r\n * async detachment of listener.\r\n */\r\n this.muted = false;\r\n }\r\n AsyncObserver.prototype.next = function (value) {\r\n this.scheduleEvent(this.observer.next, value);\r\n };\r\n AsyncObserver.prototype.error = function (error) {\r\n this.scheduleEvent(this.observer.error, error);\r\n };\r\n AsyncObserver.prototype.mute = function () {\r\n this.muted = true;\r\n };\r\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\r\n var _this = this;\r\n if (!this.muted) {\r\n setTimeout(function () {\r\n if (!_this.muted) {\r\n eventHandler(event);\r\n }\r\n }, 0);\r\n }\r\n };\r\n return AsyncObserver;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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 * Simple wrapper around a nullable UID. Mostly exists to make code more\r\n * readable.\r\n */\r\nvar User = /** @class */ (function () {\r\n function User(uid) {\r\n this.uid = uid;\r\n }\r\n User.prototype.isAuthenticated = function () {\r\n return this.uid != null;\r\n };\r\n /**\r\n * Returns a key representing this user, suitable for inclusion in a\r\n * dictionary.\r\n */\r\n User.prototype.toKey = function () {\r\n if (this.isAuthenticated()) {\r\n return 'uid:' + this.uid;\r\n }\r\n else {\r\n return 'anonymous-user';\r\n }\r\n };\r\n User.prototype.isEqual = function (otherUser) {\r\n return otherUser.uid === this.uid;\r\n };\r\n /** A user with a null UID. */\r\n User.UNAUTHENTICATED = new User(null);\r\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\r\n // non-FirebaseAuth providers.\r\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\r\n User.FIRST_PARTY = new User('first-party-uid');\r\n return User;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar OAuthToken = /** @class */ (function () {\r\n function OAuthToken(value, user) {\r\n this.user = user;\r\n this.type = 'OAuth';\r\n this.authHeaders = { Authorization: \"Bearer \" + value };\r\n }\r\n return OAuthToken;\r\n}());\r\n/** A CredentialsProvider that always yields an empty token. */\r\nvar EmptyCredentialsProvider = /** @class */ (function () {\r\n function EmptyCredentialsProvider() {\r\n /**\r\n * Stores the User listener registered with setUserChangeListener()\r\n * This isn't actually necessary since the UID never changes, but we use this\r\n * to verify the listen contract is adhered to in tests.\r\n */\r\n this.userListener = null;\r\n }\r\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\r\n return Promise.resolve(null);\r\n };\r\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\r\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\r\n this.userListener = listener;\r\n // Fire with initial user.\r\n listener(User.UNAUTHENTICATED);\r\n };\r\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\r\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\r\n this.userListener = null;\r\n };\r\n return EmptyCredentialsProvider;\r\n}());\r\nvar FirebaseCredentialsProvider = /** @class */ (function () {\r\n function FirebaseCredentialsProvider(app) {\r\n var _this = this;\r\n this.app = app;\r\n /**\r\n * The auth token listener registered with FirebaseApp, retained here so we\r\n * can unregister it.\r\n */\r\n this.tokenListener = null;\r\n /**\r\n * Counter used to detect if the user changed while a getToken request was\r\n * outstanding.\r\n */\r\n this.userCounter = 0;\r\n /** The User listener registered with setUserChangeListener(). */\r\n this.userListener = null;\r\n // We listen for token changes but all we really care about is knowing when\r\n // the uid may have changed.\r\n this.tokenListener = function () {\r\n var newUser = _this.getUser();\r\n if (!_this.currentUser || !newUser.isEqual(_this.currentUser)) {\r\n _this.currentUser = newUser;\r\n _this.userCounter++;\r\n if (_this.userListener) {\r\n _this.userListener(_this.currentUser);\r\n }\r\n }\r\n };\r\n this.userCounter = 0;\r\n // Will fire at least once where we set this.currentUser\r\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\r\n }\r\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\r\n var _this = this;\r\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\r\n // Take note of the current value of the userCounter so that this method can\r\n // fail (with an ABORTED error) if there is a user change while the request\r\n // is outstanding.\r\n var initialUserCounter = this.userCounter;\r\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\r\n // Cancel the request since the user changed while the request was\r\n // outstanding so the response is likely for a previous user (which\r\n // user, we can't be sure).\r\n if (_this.userCounter !== initialUserCounter) {\r\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\r\n }\r\n else {\r\n if (tokenData) {\r\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\r\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n });\r\n };\r\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\r\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\r\n this.userListener = listener;\r\n // Fire the initial event, but only if we received the initial user\r\n if (this.currentUser) {\r\n listener(this.currentUser);\r\n }\r\n };\r\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\r\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\r\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\r\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\r\n this.tokenListener = null;\r\n this.userListener = null;\r\n };\r\n FirebaseCredentialsProvider.prototype.getUser = function () {\r\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\r\n if (typeof this.app.INTERNAL.getUid !== 'function') {\r\n fail('This version of the Firestore SDK requires at least version' +\r\n ' 3.7.0 of firebase.js.');\r\n }\r\n var currentUid = this.app.INTERNAL.getUid();\r\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\r\n return new User(currentUid);\r\n };\r\n return FirebaseCredentialsProvider;\r\n}());\r\n/*\r\n * FirstPartyToken provides a fresh token each time its value\r\n * is requested, because if the token is too old, requests will be rejected.\r\n * TODO(b/33147818) this implementation violates the current assumption that\r\n * tokens are immutable. We need to either revisit this assumption or come\r\n * up with some way for FPA to use the listen/unlisten interface.\r\n */\r\nvar FirstPartyToken = /** @class */ (function () {\r\n function FirstPartyToken(gapi, sessionIndex) {\r\n this.gapi = gapi;\r\n this.sessionIndex = sessionIndex;\r\n this.type = 'FirstParty';\r\n this.user = User.FIRST_PARTY;\r\n assert(this.gapi &&\r\n this.gapi['auth'] &&\r\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\r\n }\r\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\r\n get: function () {\r\n return {\r\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\r\n 'X-Goog-AuthUser': this.sessionIndex\r\n };\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return FirstPartyToken;\r\n}());\r\n/*\r\n * Provides user credentials required for the Firestore JavaScript SDK\r\n * to authenticate the user, using technique that is only available\r\n * to applications hosted by Google.\r\n */\r\nvar FirstPartyCredentialsProvider = /** @class */ (function () {\r\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\r\n this.gapi = gapi;\r\n this.sessionIndex = sessionIndex;\r\n assert(this.gapi &&\r\n this.gapi['auth'] &&\r\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\r\n }\r\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\r\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\r\n };\r\n // TODO(33108925): can someone switch users w/o a page refresh?\r\n // TODO(33110621): need to understand token/session lifecycle\r\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\r\n // Fire with initial uid.\r\n listener(User.FIRST_PARTY);\r\n };\r\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\r\n return FirstPartyCredentialsProvider;\r\n}());\r\n/**\r\n * Builds a CredentialsProvider depending on the type of\r\n * the credentials passed in.\r\n */\r\nfunction makeCredentialsProvider(credentials) {\r\n if (!credentials) {\r\n return new EmptyCredentialsProvider();\r\n }\r\n switch (credentials.type) {\r\n case 'gapi':\r\n return new FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\r\n case 'provider':\r\n return credentials.client;\r\n default:\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nfunction isPartialObserver(obj) {\r\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\r\n}\r\n/**\r\n * Returns true if obj is an object and contains at least one of the specified\r\n * methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n var object = obj;\r\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\r\n var method = methods_1[_i];\r\n if (method in object && typeof object[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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 * An opaque base class for FieldValue sentinel objects in our public API,\r\n * with public static methods for creating said sentinel objects.\r\n */\r\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\r\nvar FieldValueImpl = /** @class */ (function () {\r\n function FieldValueImpl(methodName) {\r\n this.methodName = methodName;\r\n }\r\n FieldValueImpl.delete = function () {\r\n return DeleteFieldValueImpl.instance;\r\n };\r\n FieldValueImpl.serverTimestamp = function () {\r\n return ServerTimestampFieldValueImpl.instance;\r\n };\r\n FieldValueImpl.prototype.isEqual = function (other) {\r\n return this === other;\r\n };\r\n return FieldValueImpl;\r\n}());\r\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\r\n __extends(DeleteFieldValueImpl, _super);\r\n function DeleteFieldValueImpl() {\r\n return _super.call(this, 'FieldValue.delete()') || this;\r\n }\r\n /** Singleton instance. */\r\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\r\n return DeleteFieldValueImpl;\r\n}(FieldValueImpl));\r\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\r\n __extends(ServerTimestampFieldValueImpl, _super);\r\n function ServerTimestampFieldValueImpl() {\r\n return _super.call(this, 'FieldValue.serverTimestamp()') || this;\r\n }\r\n /** Singleton instance. */\r\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\r\n return ServerTimestampFieldValueImpl;\r\n}(FieldValueImpl));\r\n// Public instance that disallows construction at runtime. This constructor is\r\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\r\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\r\n// has a type-checked private constructor. Note that FieldValueImpl and\r\n// PublicFieldValue can be used interchangeably in instanceof checks.\r\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\r\n// and so we need to use FieldValueImpl as type and export it too.\r\n// tslint:disable-next-line:variable-name We treat this as a class name.\r\nvar PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\r\n/** The result of parsing document data (e.g. for a setData call). */\r\nvar ParsedSetData = /** @class */ (function () {\r\n function ParsedSetData(data, fieldMask, fieldTransforms) {\r\n this.data = data;\r\n this.fieldMask = fieldMask;\r\n this.fieldTransforms = fieldTransforms;\r\n }\r\n ParsedSetData.prototype.toMutations = function (key, precondition) {\r\n var mutations = [];\r\n if (this.fieldMask !== null) {\r\n mutations.push(new PatchMutation(key, this.data, this.fieldMask, precondition));\r\n }\r\n else {\r\n mutations.push(new SetMutation(key, this.data, precondition));\r\n }\r\n if (this.fieldTransforms.length > 0) {\r\n mutations.push(new TransformMutation(key, this.fieldTransforms));\r\n }\r\n return mutations;\r\n };\r\n return ParsedSetData;\r\n}());\r\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\r\nvar ParsedUpdateData = /** @class */ (function () {\r\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\r\n this.data = data;\r\n this.fieldMask = fieldMask;\r\n this.fieldTransforms = fieldTransforms;\r\n }\r\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\r\n var mutations = [\r\n new PatchMutation(key, this.data, this.fieldMask, precondition)\r\n ];\r\n if (this.fieldTransforms.length > 0) {\r\n mutations.push(new TransformMutation(key, this.fieldTransforms));\r\n }\r\n return mutations;\r\n };\r\n return ParsedUpdateData;\r\n}());\r\n/*\r\n * Represents what type of API method provided the data being parsed; useful\r\n * for determining which error conditions apply during parsing and providing\r\n * better error messages.\r\n */\r\nvar UserDataSource;\r\n(function (UserDataSource) {\r\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\r\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\r\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\r\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\r\n})(UserDataSource || (UserDataSource = {}));\r\nfunction isWrite(dataSource) {\r\n switch (dataSource) {\r\n case UserDataSource.Set: // fall through\r\n case UserDataSource.MergeSet: // fall through\r\n case UserDataSource.Update:\r\n return true;\r\n case UserDataSource.QueryValue:\r\n return false;\r\n default:\r\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\r\n }\r\n}\r\n/** A \"context\" object passed around while parsing user data. */\r\nvar ParseContext = /** @class */ (function () {\r\n /**\r\n * Initializes a ParseContext with the given source and path.\r\n *\r\n * @param dataSource Indicates what kind of API method this data came from.\r\n * @param methodName The name of the method the user called to create this\r\n * ParseContext.\r\n * @param path A path within the object being parsed. This could be an empty\r\n * path (in which case the context represents the root of the data being\r\n * parsed), or a nonempty path (indicating the context represents a nested\r\n * location within the data).\r\n * @param arrayElement Whether or not this context corresponds to an element\r\n * of an array.\r\n * @param fieldTransforms A mutable list of field transforms encountered while\r\n * parsing the data.\r\n * @param fieldMask A mutable list of field paths encountered while parsing\r\n * the data.\r\n *\r\n * TODO(b/34871131): We don't support array paths right now, so path can be\r\n * null to indicate the context represents any location within an array (in\r\n * which case certain features will not work and errors will be somewhat\r\n * compromised).\r\n */\r\n function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\r\n this.dataSource = dataSource;\r\n this.methodName = methodName;\r\n this.path = path;\r\n this.arrayElement = arrayElement;\r\n // Minor hack: If fieldTransforms is undefined, we assume this is an\r\n // external call and we need to validate the entire path.\r\n if (fieldTransforms === undefined) {\r\n this.validatePath();\r\n }\r\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\r\n this.fieldTransforms = fieldTransforms || [];\r\n this.fieldMask = fieldMask || [];\r\n }\r\n ParseContext.prototype.childContextForField = function (field) {\r\n var childPath = this.path == null ? null : this.path.child(field);\r\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \r\n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\r\n context.validatePathSegment(field);\r\n return context;\r\n };\r\n ParseContext.prototype.childContextForFieldPath = function (field) {\r\n var childPath = this.path == null ? null : this.path.child(field);\r\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \r\n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\r\n context.validatePath();\r\n return context;\r\n };\r\n ParseContext.prototype.childContextForArray = function (index) {\r\n // TODO(b/34871131): We don't support array paths right now; so make path\r\n // null.\r\n return new ParseContext(this.dataSource, this.methodName, \r\n /*path=*/ null, \r\n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\r\n };\r\n ParseContext.prototype.createError = function (reason) {\r\n var fieldDescription = this.path === null || this.path.isEmpty()\r\n ? ''\r\n : \" (found in field \" + this.path.toString() + \")\";\r\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\r\n reason +\r\n fieldDescription);\r\n };\r\n ParseContext.prototype.validatePath = function () {\r\n // TODO(b/34871131): Remove null check once we have proper paths for fields\r\n // within arrays.\r\n if (this.path === null) {\r\n return;\r\n }\r\n for (var i = 0; i < this.path.length; i++) {\r\n this.validatePathSegment(this.path.get(i));\r\n }\r\n };\r\n ParseContext.prototype.validatePathSegment = function (segment) {\r\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\r\n throw this.createError('Document fields cannot begin and end with __');\r\n }\r\n };\r\n return ParseContext;\r\n}());\r\n/**\r\n * A placeholder object for DocumentReferences in this file, in order to\r\n * avoid a circular dependency. See the comments for `DataPreConverter` for\r\n * the full context.\r\n */\r\nvar DocumentKeyReference = /** @class */ (function () {\r\n function DocumentKeyReference(databaseId, key) {\r\n this.databaseId = databaseId;\r\n this.key = key;\r\n }\r\n return DocumentKeyReference;\r\n}());\r\n/**\r\n * Helper for parsing raw user input (provided via the API) into internal model\r\n * classes.\r\n */\r\nvar UserDataConverter = /** @class */ (function () {\r\n function UserDataConverter(preConverter) {\r\n this.preConverter = preConverter;\r\n }\r\n /** Parse document data from a non-merge set() call. */\r\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\r\n var context = new ParseContext(UserDataSource.Set, methodName, FieldPath.EMPTY_PATH);\r\n validatePlainObject('Data must be an object, but it was:', context, input);\r\n var updateData = this.parseData(input, context);\r\n return new ParsedSetData(updateData, \r\n /* fieldMask= */ null, context.fieldTransforms);\r\n };\r\n /** Parse document data from a set() call with '{merge:true}'. */\r\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\r\n var context = new ParseContext(UserDataSource.MergeSet, methodName, FieldPath.EMPTY_PATH);\r\n validatePlainObject('Data must be an object, but it was:', context, input);\r\n var updateData = this.parseData(input, context);\r\n var fieldMask = new FieldMask(context.fieldMask);\r\n return new ParsedSetData(updateData, fieldMask, context.fieldTransforms);\r\n };\r\n /** Parse update data from an update() call. */\r\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\r\n var _this = this;\r\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\r\n validatePlainObject('Data must be an object, but it was:', context, input);\r\n var fieldMaskPaths = [];\r\n var updateData = ObjectValue.EMPTY;\r\n forEach(input, function (key, value) {\r\n var path = fieldPathFromDotSeparatedString(methodName, key);\r\n var childContext = context.childContextForFieldPath(path);\r\n value = _this.runPreConverter(value, childContext);\r\n if (value instanceof DeleteFieldValueImpl) {\r\n // Add it to the field mask, but don't add anything to updateData.\r\n fieldMaskPaths.push(path);\r\n }\r\n else {\r\n var parsedValue = _this.parseData(value, childContext);\r\n if (parsedValue != null) {\r\n fieldMaskPaths.push(path);\r\n updateData = updateData.set(path, parsedValue);\r\n }\r\n }\r\n });\r\n var mask = new FieldMask(fieldMaskPaths);\r\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\r\n };\r\n /** Parse update data from a list of field/value arguments. */\r\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\r\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\r\n var keys = [fieldPathFromArgument(methodName, field)];\r\n var values = [value];\r\n if (moreFieldsAndValues.length % 2 !== 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\r\n 'of arguments that alternate between field names and values.');\r\n }\r\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\r\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\r\n values.push(moreFieldsAndValues[i + 1]);\r\n }\r\n var fieldMaskPaths = [];\r\n var updateData = ObjectValue.EMPTY;\r\n for (var i = 0; i < keys.length; ++i) {\r\n var path = keys[i];\r\n var childContext = context.childContextForFieldPath(path);\r\n var value_1 = this.runPreConverter(values[i], childContext);\r\n if (value_1 instanceof DeleteFieldValueImpl) {\r\n // Add it to the field mask, but don't add anything to updateData.\r\n fieldMaskPaths.push(path);\r\n }\r\n else {\r\n var parsedValue = this.parseData(value_1, childContext);\r\n if (parsedValue != null) {\r\n fieldMaskPaths.push(path);\r\n updateData = updateData.set(path, parsedValue);\r\n }\r\n }\r\n }\r\n var mask = new FieldMask(fieldMaskPaths);\r\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\r\n };\r\n /**\r\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\r\n * bound).\r\n */\r\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\r\n var context = new ParseContext(UserDataSource.QueryValue, methodName, FieldPath.EMPTY_PATH);\r\n var parsed = this.parseData(input, context);\r\n assert(parsed != null, 'Parsed data should not be null.');\r\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\r\n return parsed;\r\n };\r\n /** Sends data through this.preConverter, handling any thrown errors. */\r\n UserDataConverter.prototype.runPreConverter = function (input, context) {\r\n try {\r\n return this.preConverter(input);\r\n }\r\n catch (e) {\r\n var message = errorMessage(e);\r\n throw context.createError(message);\r\n }\r\n };\r\n /**\r\n * Internal helper for parsing user data.\r\n *\r\n * @param input Data to be parsed.\r\n * @param context A context object representing the current path being parsed,\r\n * the source of the data being parsed, etc.\r\n * @return The parsed value, or null if the value was a FieldValue sentinel\r\n * that should not be included in the resulting parsed data.\r\n */\r\n UserDataConverter.prototype.parseData = function (input, context) {\r\n input = this.runPreConverter(input, context);\r\n if (looksLikeJsonObject(input)) {\r\n validatePlainObject('Unsupported field value:', context, input);\r\n return this.parseObject(input, context);\r\n }\r\n else {\r\n // If context.path is null we are inside an array and we don't support\r\n // field mask paths more granular than the top-level array.\r\n if (context.path) {\r\n context.fieldMask.push(context.path);\r\n }\r\n if (input instanceof Array) {\r\n // TODO(b/34871131): Include the path containing the array in the error\r\n // message.\r\n if (context.arrayElement) {\r\n throw context.createError('Nested arrays are not supported');\r\n }\r\n return this.parseArray(input, context);\r\n }\r\n else if (input instanceof FieldValueImpl) {\r\n // parseSentinelFieldValue() may add a FieldTransform, but we return\r\n // null since nothing should be included in the actual parsed data.\r\n this.parseSentinelFieldValue(input, context);\r\n return null;\r\n }\r\n else {\r\n return this.parseScalarValue(input, context);\r\n }\r\n }\r\n };\r\n UserDataConverter.prototype.parseObject = function (obj, context) {\r\n var _this = this;\r\n var result = new SortedMap(primitiveComparator);\r\n forEach(obj, function (key, val) {\r\n var parsedValue = _this.parseData(val, context.childContextForField(key));\r\n if (parsedValue != null) {\r\n result = result.insert(key, parsedValue);\r\n }\r\n });\r\n return new ObjectValue(result);\r\n };\r\n UserDataConverter.prototype.parseArray = function (array, context) {\r\n var result = [];\r\n var entryIndex = 0;\r\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\r\n var entry = array_1[_i];\r\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\r\n if (parsedEntry == null) {\r\n // Just include nulls in the array for fields being replaced with a\r\n // sentinel.\r\n parsedEntry = NullValue.INSTANCE;\r\n }\r\n result.push(parsedEntry);\r\n entryIndex++;\r\n }\r\n return new ArrayValue(result);\r\n };\r\n /**\r\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\r\n * context.fieldTransforms.\r\n */\r\n UserDataConverter.prototype.parseSentinelFieldValue = function (value, context) {\r\n // Sentinels are only supported with writes, and not within arrays.\r\n if (!isWrite(context.dataSource)) {\r\n throw context.createError(value.methodName + \" can only be used with update() and set()\");\r\n }\r\n if (context.path === null) {\r\n throw context.createError(value.methodName + \" is not currently supported inside arrays\");\r\n }\r\n if (value instanceof DeleteFieldValueImpl) {\r\n if (context.dataSource === UserDataSource.MergeSet) {\r\n // No transform to add for a delete, so we do nothing.\r\n }\r\n else if (context.dataSource === UserDataSource.Update) {\r\n assert(context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\r\n ' been handled.');\r\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\r\n 'of your update data');\r\n }\r\n else {\r\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\r\n throw context.createError('FieldValue.delete() cannot be used with set() unless you pass ' +\r\n '{merge:true}');\r\n }\r\n }\r\n else if (value instanceof ServerTimestampFieldValueImpl) {\r\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\r\n }\r\n else {\r\n fail('Unknown FieldValue type: ' + value);\r\n }\r\n };\r\n /**\r\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\r\n *\r\n * @return The parsed value\r\n */\r\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\r\n if (value === null) {\r\n return NullValue.INSTANCE;\r\n }\r\n else if (typeof value === 'number') {\r\n if (isSafeInteger(value)) {\r\n return new IntegerValue(value);\r\n }\r\n else {\r\n return new DoubleValue(value);\r\n }\r\n }\r\n else if (typeof value === 'boolean') {\r\n return BooleanValue.of(value);\r\n }\r\n else if (typeof value === 'string') {\r\n return new StringValue(value);\r\n }\r\n else if (value instanceof Date) {\r\n return new TimestampValue(Timestamp.fromDate(value));\r\n }\r\n else if (value instanceof Timestamp) {\r\n // Firestore backend truncates precision down to microseconds. To ensure\r\n // offline mode works the same with regards to truncation, perform the\r\n // truncation immediately without waiting for the backend to do that.\r\n return new TimestampValue(new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000));\r\n }\r\n else if (value instanceof GeoPoint) {\r\n return new GeoPointValue(value);\r\n }\r\n else if (value instanceof Blob) {\r\n return new BlobValue(value);\r\n }\r\n else if (value instanceof DocumentKeyReference) {\r\n return new RefValue(value.databaseId, value.key);\r\n }\r\n else {\r\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\r\n }\r\n };\r\n return UserDataConverter;\r\n}());\r\n/**\r\n * Checks whether an object looks like a JSON object that should be converted\r\n * into a struct. Normal class/prototype instances are considered to look like\r\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\r\n * GeoPoints, etc. are not considered to look like JSON objects since they map\r\n * to specific FieldValue types other than ObjectValue.\r\n */\r\nfunction looksLikeJsonObject(input) {\r\n return (typeof input === 'object' &&\r\n input !== null &&\r\n !(input instanceof Array) &&\r\n !(input instanceof Date) &&\r\n !(input instanceof Timestamp) &&\r\n !(input instanceof GeoPoint) &&\r\n !(input instanceof Blob) &&\r\n !(input instanceof DocumentKeyReference) &&\r\n !(input instanceof FieldValueImpl));\r\n}\r\nfunction validatePlainObject(message, context, input) {\r\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\r\n var description = valueDescription(input);\r\n if (description === 'an object') {\r\n // Massage the error if it was an object.\r\n throw context.createError(message + ' a custom object');\r\n }\r\n else {\r\n throw context.createError(message + ' ' + description);\r\n }\r\n }\r\n}\r\n/**\r\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\r\n */\r\nfunction fieldPathFromArgument(methodName, path) {\r\n if (path instanceof FieldPath$1) {\r\n return path._internalPath;\r\n }\r\n else if (typeof path === 'string') {\r\n return fieldPathFromDotSeparatedString(methodName, path);\r\n }\r\n else {\r\n var message = 'Field path arguments must be of type string or FieldPath.';\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\r\n }\r\n}\r\n/**\r\n * Wraps fromDotSeparatedString with an error message about the method that\r\n * was thrown.\r\n * @param methodName The publicly visible method name\r\n * @param path The dot-separated string form of a field path which will be split\r\n * on dots.\r\n */\r\nfunction fieldPathFromDotSeparatedString(methodName, path) {\r\n try {\r\n return fromDotSeparatedString(path)._internalPath;\r\n }\r\n catch (e) {\r\n var message = errorMessage(e);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\r\n }\r\n}\r\n/**\r\n * Extracts the message from a caught exception, which should be an Error object\r\n * though JS doesn't guarantee that.\r\n */\r\nfunction errorMessage(error) {\r\n return error instanceof Error ? error.message : error.toString();\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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// The objects that are a part of this API are exposed to third-parties as\r\n// compiled javascript so we want to flag our private members with a leading\r\n// underscore to discourage their use.\r\n// tslint:disable:strip-private-property-underscore\r\nvar DEFAULT_HOST = 'firestore.googleapis.com';\r\nvar DEFAULT_SSL = true;\r\nvar DEFAULT_TIMESTAMPS_IN_SNAPSHOTS = false;\r\n/**\r\n * A concrete type describing all the values that can be applied via a\r\n * user-supplied firestore.Settings object. This is a separate type so that\r\n * defaults can be supplied and the value can be checked for equality.\r\n */\r\nvar FirestoreSettings = /** @class */ (function () {\r\n function FirestoreSettings(settings) {\r\n if (settings.host === undefined) {\r\n if (settings.ssl !== undefined) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\r\n }\r\n this.host = DEFAULT_HOST;\r\n this.ssl = DEFAULT_SSL;\r\n }\r\n else {\r\n validateNamedType('settings', 'string', 'host', settings.host);\r\n this.host = settings.host;\r\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\r\n this.ssl = defaulted(settings.ssl, DEFAULT_SSL);\r\n }\r\n validateOptionNames('settings', settings, [\r\n 'host',\r\n 'ssl',\r\n 'credentials',\r\n 'timestampsInSnapshots'\r\n ]);\r\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\r\n this.credentials = settings.credentials;\r\n validateNamedOptionalType('settings', 'boolean', 'timestampsInSnapshots', settings.timestampsInSnapshots);\r\n this.timestampsInSnapshots = defaulted(settings.timestampsInSnapshots, DEFAULT_TIMESTAMPS_IN_SNAPSHOTS);\r\n }\r\n FirestoreSettings.prototype.isEqual = function (other) {\r\n return (this.host === other.host &&\r\n this.ssl === other.ssl &&\r\n this.timestampsInSnapshots === other.timestampsInSnapshots &&\r\n this.credentials === other.credentials);\r\n };\r\n return FirestoreSettings;\r\n}());\r\nvar FirestoreConfig = /** @class */ (function () {\r\n function FirestoreConfig() {\r\n }\r\n return FirestoreConfig;\r\n}());\r\n/**\r\n * The root reference to the database.\r\n */\r\nvar Firestore = /** @class */ (function () {\r\n function Firestore(databaseIdOrApp) {\r\n var _this = this;\r\n // Public for use in tests.\r\n // TODO(mikelehen): Use modularized initialization instead.\r\n this._queue = new AsyncQueue();\r\n this.INTERNAL = {\r\n delete: function () { return __awaiter(_this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (this._firestoreClient) {\r\n return [2 /*return*/, this._firestoreClient.shutdown()];\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); }\r\n };\r\n var config = new FirestoreConfig();\r\n if (typeof databaseIdOrApp.options === 'object') {\r\n // This is very likely a Firebase app object\r\n // TODO(b/34177605): Can we somehow use instanceof?\r\n var app = databaseIdOrApp;\r\n config.firebaseApp = app;\r\n config.databaseId = Firestore.databaseIdFromApp(app);\r\n config.persistenceKey = config.firebaseApp.name;\r\n config.credentials = new FirebaseCredentialsProvider(app);\r\n }\r\n else {\r\n var external_1 = databaseIdOrApp;\r\n if (!external_1.projectId) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\r\n }\r\n config.databaseId = new DatabaseId(external_1.projectId, external_1.database);\r\n // Use a default persistenceKey that lines up with FirebaseApp.\r\n config.persistenceKey = '[DEFAULT]';\r\n config.credentials = new EmptyCredentialsProvider();\r\n }\r\n config.settings = new FirestoreSettings({});\r\n this._config = config;\r\n this._databaseId = config.databaseId;\r\n }\r\n Firestore.prototype.settings = function (settingsLiteral) {\r\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\r\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\r\n if (contains(settingsLiteral, 'persistence')) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\r\n 'firestore.enablePersistence().');\r\n }\r\n var newSettings = new FirestoreSettings(settingsLiteral);\r\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\r\n 'be changed. You can only call settings() before calling any other ' +\r\n 'methods on a Firestore object.');\r\n }\r\n this._config.settings = newSettings;\r\n if (newSettings.credentials !== undefined) {\r\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\r\n }\r\n };\r\n Firestore.prototype.enableNetwork = function () {\r\n this.ensureClientConfigured();\r\n return this._firestoreClient.enableNetwork();\r\n };\r\n Firestore.prototype.disableNetwork = function () {\r\n this.ensureClientConfigured();\r\n return this._firestoreClient.disableNetwork();\r\n };\r\n Firestore.prototype.enablePersistence = function () {\r\n if (this._firestoreClient) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\r\n 'be enabled. You can only call enablePersistence() before calling ' +\r\n 'any other methods on a Firestore object.');\r\n }\r\n return this.configureClient(/* persistence= */ true);\r\n };\r\n Firestore.prototype.ensureClientConfigured = function () {\r\n if (!this._firestoreClient) {\r\n this.configureClient(/* persistence= */ false);\r\n }\r\n return this._firestoreClient;\r\n };\r\n Firestore.prototype.configureClient = function (persistence) {\r\n var _this = this;\r\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\r\n if (!this._config.settings.timestampsInSnapshots) {\r\n error(\"\\nThe behavior for Date objects stored in Firestore is going to change\\nAND YOUR APP MAY BREAK.\\nTo hide this warning and ensure your app does not break, you need to add the\\nfollowing code to your app before calling any other Cloud Firestore methods:\\n\\n const firestore = firebase.firestore();\\n const settings = {/* your settings... */ timestampsInSnapshots: true};\\n firestore.settings(settings);\\n\\nWith this change, timestamps stored in Cloud Firestore will be read back as\\nFirebase Timestamp objects instead of as system Date objects. So you will also\\nneed to update code expecting a Date to instead expect a Timestamp. For example:\\n\\n // Old:\\n const date = snapshot.get('created_at');\\n // New:\\n const timestamp = snapshot.get('created_at');\\n const date = timestamp.toDate();\\n\\nPlease audit all existing usages of Date when you enable the new behavior. In a\\nfuture release, the behavior will change to the new behavior, so if you do not\\nfollow these steps, YOUR APP MAY BREAK.\");\r\n }\r\n assert(!this._firestoreClient, 'configureClient() called multiple times');\r\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\r\n var preConverter = function (value) {\r\n if (value instanceof DocumentReference) {\r\n var thisDb = _this._config.databaseId;\r\n var otherDb = value.firestore._config.databaseId;\r\n if (!otherDb.isEqual(thisDb)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\r\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\r\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\r\n }\r\n return new DocumentKeyReference(_this._config.databaseId, value._key);\r\n }\r\n else {\r\n return value;\r\n }\r\n };\r\n this._dataConverter = new UserDataConverter(preConverter);\r\n this._firestoreClient = new FirestoreClient(PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\r\n return this._firestoreClient.start(persistence);\r\n };\r\n Firestore.databaseIdFromApp = function (app) {\r\n var options = app.options;\r\n if (!contains(options, 'projectId')) {\r\n // TODO(b/62673263): We can safely remove the special handling of\r\n // 'firestoreId' once alpha testers have upgraded.\r\n if (contains(options, 'firestoreId')) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\r\n 'firebase.initializeApp.');\r\n }\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\r\n }\r\n if (contains(options, 'firestoreOptions')) {\r\n // TODO(b/62673263): We can safely remove the special handling of\r\n // 'firestoreOptions' once alpha testers have upgraded.\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\r\n 'Firestore.settings()');\r\n }\r\n var projectId = options['projectId'];\r\n if (!projectId || typeof projectId !== 'string') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\r\n }\r\n return new DatabaseId(projectId);\r\n };\r\n Object.defineProperty(Firestore.prototype, \"app\", {\r\n get: function () {\r\n if (!this._config.firebaseApp) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\r\n 'not available');\r\n }\r\n return this._config.firebaseApp;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Firestore.prototype.collection = function (pathString) {\r\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\r\n validateArgType('Firestore.collection', 'string', 1, pathString);\r\n if (!pathString) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\r\n }\r\n this.ensureClientConfigured();\r\n return new CollectionReference(ResourcePath.fromString(pathString), this);\r\n };\r\n Firestore.prototype.doc = function (pathString) {\r\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\r\n validateArgType('Firestore.doc', 'string', 1, pathString);\r\n if (!pathString) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\r\n }\r\n this.ensureClientConfigured();\r\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\r\n };\r\n Firestore.prototype.runTransaction = function (updateFunction) {\r\n var _this = this;\r\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\r\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\r\n return this.ensureClientConfigured().transaction(function (transaction) {\r\n return updateFunction(new Transaction$1(_this, transaction));\r\n });\r\n };\r\n Firestore.prototype.batch = function () {\r\n this.ensureClientConfigured();\r\n return new WriteBatch(this);\r\n };\r\n Object.defineProperty(Firestore, \"logLevel\", {\r\n get: function () {\r\n switch (getLogLevel()) {\r\n case LogLevel$1.DEBUG:\r\n return 'debug';\r\n case LogLevel$1.ERROR:\r\n return 'error';\r\n case LogLevel$1.SILENT:\r\n return 'silent';\r\n default:\r\n return fail('Unknown log level: ' + getLogLevel());\r\n }\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Firestore.setLogLevel = function (level) {\r\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\r\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\r\n switch (level) {\r\n case 'debug':\r\n setLogLevel(LogLevel$1.DEBUG);\r\n break;\r\n case 'error':\r\n setLogLevel(LogLevel$1.ERROR);\r\n break;\r\n case 'silent':\r\n setLogLevel(LogLevel$1.SILENT);\r\n break;\r\n default:\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\r\n }\r\n };\r\n // Note: this is not a property because the minifier can't work correctly with\r\n // the way TypeScript compiler outputs properties.\r\n Firestore.prototype._areTimestampsInSnapshotsEnabled = function () {\r\n return this._config.settings.timestampsInSnapshots;\r\n };\r\n return Firestore;\r\n}());\r\n/**\r\n * A reference to a transaction.\r\n */\r\nvar Transaction$1 = /** @class */ (function () {\r\n function Transaction(_firestore, _transaction) {\r\n this._firestore = _firestore;\r\n this._transaction = _transaction;\r\n }\r\n Transaction.prototype.get = function (documentRef) {\r\n var _this = this;\r\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\r\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\r\n return this._transaction\r\n .lookup([ref._key])\r\n .then(function (docs) {\r\n if (!docs || docs.length !== 1) {\r\n return fail('Mismatch in docs returned from document lookup.');\r\n }\r\n var doc = docs[0];\r\n if (doc instanceof NoDocument) {\r\n return new DocumentSnapshot(_this._firestore, ref._key, null, false);\r\n }\r\n return new DocumentSnapshot(_this._firestore, ref._key, doc, false);\r\n });\r\n };\r\n Transaction.prototype.set = function (documentRef, value, options) {\r\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\r\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\r\n options = validateSetOptions('Transaction.set', options);\r\n var parsed = options.merge\r\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\r\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\r\n this._transaction.set(ref._key, parsed);\r\n return this;\r\n };\r\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\r\n var moreFieldsAndValues = [];\r\n for (var _i = 3; _i < arguments.length; _i++) {\r\n moreFieldsAndValues[_i - 3] = arguments[_i];\r\n }\r\n var ref;\r\n var parsed;\r\n if (typeof fieldOrUpdateData === 'string' ||\r\n fieldOrUpdateData instanceof FieldPath$1) {\r\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\r\n ref = validateReference('Transaction.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\r\n }\r\n else {\r\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\r\n ref = validateReference('Transaction.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\r\n }\r\n this._transaction.update(ref._key, parsed);\r\n return this;\r\n };\r\n Transaction.prototype.delete = function (documentRef) {\r\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\r\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\r\n this._transaction.delete(ref._key);\r\n return this;\r\n };\r\n return Transaction;\r\n}());\r\nvar WriteBatch = /** @class */ (function () {\r\n function WriteBatch(_firestore) {\r\n this._firestore = _firestore;\r\n this._mutations = [];\r\n this._committed = false;\r\n }\r\n WriteBatch.prototype.set = function (documentRef, value, options) {\r\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\r\n this.verifyNotCommitted();\r\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\r\n options = validateSetOptions('WriteBatch.set', options);\r\n var parsed = options.merge\r\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\r\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\r\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.NONE));\r\n return this;\r\n };\r\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\r\n var moreFieldsAndValues = [];\r\n for (var _i = 3; _i < arguments.length; _i++) {\r\n moreFieldsAndValues[_i - 3] = arguments[_i];\r\n }\r\n this.verifyNotCommitted();\r\n var ref;\r\n var parsed;\r\n if (typeof fieldOrUpdateData === 'string' ||\r\n fieldOrUpdateData instanceof FieldPath$1) {\r\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\r\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\r\n }\r\n else {\r\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\r\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\r\n }\r\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.exists(true)));\r\n return this;\r\n };\r\n WriteBatch.prototype.delete = function (documentRef) {\r\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\r\n this.verifyNotCommitted();\r\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\r\n this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.NONE));\r\n return this;\r\n };\r\n WriteBatch.prototype.commit = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n this.verifyNotCommitted();\r\n this._committed = true;\r\n if (this._mutations.length > 0) {\r\n return [2 /*return*/, this._firestore.ensureClientConfigured().write(this._mutations)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n WriteBatch.prototype.verifyNotCommitted = function () {\r\n if (this._committed) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\r\n 'has been called.');\r\n }\r\n };\r\n return WriteBatch;\r\n}());\r\n/**\r\n * A reference to a particular document in a collection in the database.\r\n */\r\nvar DocumentReference = /** @class */ (function () {\r\n function DocumentReference(_key, firestore) {\r\n this._key = _key;\r\n this.firestore = firestore;\r\n this._firestoreClient = this.firestore.ensureClientConfigured();\r\n }\r\n DocumentReference.forPath = function (path, firestore) {\r\n if (path.length % 2 !== 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\r\n 'references must have an even number of segments, but ' +\r\n (path.canonicalString() + \" has \" + path.length));\r\n }\r\n return new DocumentReference(new DocumentKey(path), firestore);\r\n };\r\n Object.defineProperty(DocumentReference.prototype, \"id\", {\r\n get: function () {\r\n return this._key.path.lastSegment();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\r\n get: function () {\r\n return new CollectionReference(this._key.path.popLast(), this.firestore);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentReference.prototype, \"path\", {\r\n get: function () {\r\n return this._key.path.canonicalString();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n DocumentReference.prototype.collection = function (pathString) {\r\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\r\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\r\n if (!pathString) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\r\n }\r\n var path = ResourcePath.fromString(pathString);\r\n return new CollectionReference(this._key.path.child(path), this.firestore);\r\n };\r\n DocumentReference.prototype.isEqual = function (other) {\r\n if (!(other instanceof DocumentReference)) {\r\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\r\n }\r\n return this.firestore === other.firestore && this._key.isEqual(other._key);\r\n };\r\n DocumentReference.prototype.set = function (value, options) {\r\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\r\n options = validateSetOptions('DocumentReference.set', options);\r\n var parsed = options.merge\r\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\r\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\r\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.NONE));\r\n };\r\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\r\n var moreFieldsAndValues = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n moreFieldsAndValues[_i - 2] = arguments[_i];\r\n }\r\n var parsed;\r\n if (typeof fieldOrUpdateData === 'string' ||\r\n fieldOrUpdateData instanceof FieldPath$1) {\r\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\r\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\r\n }\r\n else {\r\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\r\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\r\n }\r\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.exists(true)));\r\n };\r\n DocumentReference.prototype.delete = function () {\r\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\r\n return this._firestoreClient.write([\r\n new DeleteMutation(this._key, Precondition.NONE)\r\n ]);\r\n };\r\n DocumentReference.prototype.onSnapshot = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\r\n var options = {\r\n includeMetadataChanges: false\r\n };\r\n var observer;\r\n var currArg = 0;\r\n if (typeof args[currArg] === 'object' &&\r\n !isPartialObserver(args[currArg])) {\r\n options = args[currArg];\r\n validateOptionNames('DocumentReference.onSnapshot', options, [\r\n 'includeMetadataChanges'\r\n ]);\r\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\r\n currArg++;\r\n }\r\n var internalOptions = {\r\n includeDocumentMetadataChanges: options.includeMetadataChanges,\r\n includeQueryMetadataChanges: options.includeMetadataChanges\r\n };\r\n if (isPartialObserver(args[currArg])) {\r\n observer = args[currArg];\r\n }\r\n else {\r\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\r\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\r\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\r\n observer = {\r\n next: args[currArg],\r\n error: args[currArg + 1],\r\n complete: args[currArg + 2]\r\n };\r\n }\r\n return this.onSnapshotInternal(internalOptions, observer);\r\n };\r\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\r\n var _this = this;\r\n var errHandler = function (err) {\r\n console.error('Uncaught Error in onSnapshot:', err);\r\n };\r\n if (observer.error) {\r\n errHandler = observer.error.bind(observer);\r\n }\r\n var asyncObserver = new AsyncObserver({\r\n next: function (snapshot) {\r\n if (observer.next) {\r\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\r\n var doc = snapshot.docs.get(_this._key);\r\n observer.next(new DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\r\n }\r\n },\r\n error: errHandler\r\n });\r\n var internalListener = this._firestoreClient.listen(Query.atPath(this._key.path), asyncObserver, options);\r\n return function () {\r\n asyncObserver.mute();\r\n _this._firestoreClient.unlisten(internalListener);\r\n };\r\n };\r\n DocumentReference.prototype.get = function (options) {\r\n var _this = this;\r\n validateOptionNames('DocumentReference.get', options, ['source']);\r\n if (options) {\r\n validateNamedOptionalPropertyEquals('DocumentReference.get', 'options', 'source', options.source, ['default', 'server', 'cache']);\r\n }\r\n return new Promise(function (resolve, reject) {\r\n if (options && options.source === 'cache') {\r\n _this.firestore\r\n .ensureClientConfigured()\r\n .getDocumentFromLocalCache(_this._key)\r\n .then(function (doc) {\r\n resolve(new DocumentSnapshot(_this.firestore, _this._key, doc, \r\n /*fromCache=*/ true));\r\n }, reject);\r\n }\r\n else {\r\n _this.getViaSnapshotListener(resolve, reject, options);\r\n }\r\n });\r\n };\r\n DocumentReference.prototype.getViaSnapshotListener = function (resolve, reject, options) {\r\n var unlisten = this.onSnapshotInternal({\r\n includeQueryMetadataChanges: true,\r\n includeDocumentMetadataChanges: true,\r\n waitForSyncWhenOnline: true\r\n }, {\r\n next: function (snap) {\r\n // Remove query first before passing event to user to avoid\r\n // user actions affecting the now stale query.\r\n unlisten();\r\n if (!snap.exists && snap.metadata.fromCache) {\r\n // TODO(dimond): If we're online and the document doesn't\r\n // exist then we resolve with a doc.exists set to false. If\r\n // we're offline however, we reject the Promise in this\r\n // case. Two options: 1) Cache the negative response from\r\n // the server so we can deliver that even when you're\r\n // offline 2) Actually reject the Promise in the online case\r\n // if the document doesn't exist.\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document because the client is ' + 'offline.'));\r\n }\r\n else if (snap.exists &&\r\n snap.metadata.fromCache &&\r\n options &&\r\n options.source === 'server') {\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from server. (However, this ' +\r\n 'document does exist in the local cache. Run again ' +\r\n 'without setting source to \"server\" to ' +\r\n 'retrieve the cached document.)'));\r\n }\r\n else {\r\n resolve(snap);\r\n }\r\n },\r\n error: reject\r\n });\r\n };\r\n return DocumentReference;\r\n}());\r\nvar SnapshotMetadata = /** @class */ (function () {\r\n function SnapshotMetadata(hasPendingWrites, fromCache) {\r\n this.hasPendingWrites = hasPendingWrites;\r\n this.fromCache = fromCache;\r\n }\r\n SnapshotMetadata.prototype.isEqual = function (other) {\r\n return (this.hasPendingWrites === other.hasPendingWrites &&\r\n this.fromCache === other.fromCache);\r\n };\r\n return SnapshotMetadata;\r\n}());\r\nvar DocumentSnapshot = /** @class */ (function () {\r\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\r\n this._firestore = _firestore;\r\n this._key = _key;\r\n this._document = _document;\r\n this._fromCache = _fromCache;\r\n }\r\n DocumentSnapshot.prototype.data = function (options) {\r\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\r\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\r\n return !this._document\r\n ? undefined\r\n : this.convertObject(this._document.data, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));\r\n };\r\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\r\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\r\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\r\n if (this._document) {\r\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\r\n if (value !== undefined) {\r\n return this.convertValue(value, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));\r\n }\r\n }\r\n return undefined;\r\n };\r\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\r\n get: function () {\r\n return this._key.path.lastSegment();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\r\n get: function () {\r\n return new DocumentReference(this._key, this._firestore);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\r\n get: function () {\r\n return this._document !== null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\r\n get: function () {\r\n return new SnapshotMetadata(this._document !== null && this._document.hasLocalMutations, this._fromCache);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n DocumentSnapshot.prototype.isEqual = function (other) {\r\n if (!(other instanceof DocumentSnapshot)) {\r\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\r\n }\r\n return (this._firestore === other._firestore &&\r\n this._fromCache === other._fromCache &&\r\n this._key.isEqual(other._key) &&\r\n (this._document === null\r\n ? other._document === null\r\n : this._document.isEqual(other._document)));\r\n };\r\n DocumentSnapshot.prototype.convertObject = function (data, options) {\r\n var _this = this;\r\n var result = {};\r\n data.forEach(function (key, value) {\r\n result[key] = _this.convertValue(value, options);\r\n });\r\n return result;\r\n };\r\n DocumentSnapshot.prototype.convertValue = function (value, options) {\r\n if (value instanceof ObjectValue) {\r\n return this.convertObject(value, options);\r\n }\r\n else if (value instanceof ArrayValue) {\r\n return this.convertArray(value, options);\r\n }\r\n else if (value instanceof RefValue) {\r\n var key = value.value(options);\r\n var database = this._firestore.ensureClientConfigured().databaseId();\r\n if (!value.databaseId.isEqual(database)) {\r\n // TODO(b/64130202): Somehow support foreign references.\r\n error(\"Document \" + this._key.path + \" contains a document \" +\r\n \"reference within a different database (\" +\r\n (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") +\r\n \"supported. It will be treated as a reference in the current \" +\r\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\r\n \"instead.\");\r\n }\r\n return new DocumentReference(key, this._firestore);\r\n }\r\n else {\r\n return value.value(options);\r\n }\r\n };\r\n DocumentSnapshot.prototype.convertArray = function (data, options) {\r\n var _this = this;\r\n return data.internalValue.map(function (value) {\r\n return _this.convertValue(value, options);\r\n });\r\n };\r\n return DocumentSnapshot;\r\n}());\r\nvar QueryDocumentSnapshot = /** @class */ (function (_super) {\r\n __extends(QueryDocumentSnapshot, _super);\r\n function QueryDocumentSnapshot(firestore, key, document, fromCache) {\r\n return _super.call(this, firestore, key, document, fromCache) || this;\r\n }\r\n QueryDocumentSnapshot.prototype.data = function (options) {\r\n var data = _super.prototype.data.call(this, options);\r\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\r\n return data;\r\n };\r\n return QueryDocumentSnapshot;\r\n}(DocumentSnapshot));\r\nvar Query$1 = /** @class */ (function () {\r\n function Query$$1(_query, firestore) {\r\n this._query = _query;\r\n this.firestore = firestore;\r\n }\r\n Query$$1.prototype.where = function (field, opStr, value) {\r\n validateExactNumberOfArgs('Query.where', arguments, 3);\r\n validateArgType('Query.where', 'string', 2, opStr);\r\n validateDefined('Query.where', 3, value);\r\n var fieldValue;\r\n var fieldPath = fieldPathFromArgument('Query.where', field);\r\n if (fieldPath.isKeyField()) {\r\n if (typeof value === 'string') {\r\n if (value.indexOf('/') !== -1) {\r\n // TODO(dimond): Allow slashes once ancestor queries are supported\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\r\n 'valid document ID if the first parameter is ' +\r\n 'FieldPath.documentId(), but it contains a slash.');\r\n }\r\n if (value === '') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\r\n 'valid document ID if the first parameter is ' +\r\n 'FieldPath.documentId(), but it was an empty string.');\r\n }\r\n var path = this._query.path.child(new ResourcePath([value]));\r\n assert(path.length % 2 === 0, 'Path should be a document key');\r\n fieldValue = new RefValue(this.firestore._databaseId, new DocumentKey(path));\r\n }\r\n else if (value instanceof DocumentReference) {\r\n var ref = value;\r\n fieldValue = new RefValue(this.firestore._databaseId, ref._key);\r\n }\r\n else {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\r\n \"string or a DocumentReference if the first parameter is \" +\r\n \"FieldPath.documentId(), but it was: \" +\r\n (valueDescription(value) + \".\"));\r\n }\r\n }\r\n else {\r\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\r\n }\r\n var filter = fieldFilter(fieldPath, RelationOp.fromString(opStr), fieldValue);\r\n this.validateNewFilter(filter);\r\n return new Query$$1(this._query.addFilter(filter), this.firestore);\r\n };\r\n Query$$1.prototype.orderBy = function (field, directionStr) {\r\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\r\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\r\n var direction;\r\n if (directionStr === undefined || directionStr === 'asc') {\r\n direction = Direction.ASCENDING;\r\n }\r\n else if (directionStr === 'desc') {\r\n direction = Direction.DESCENDING;\r\n }\r\n else {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\r\n \"expected 'asc' or 'desc'.\");\r\n }\r\n if (this._query.startAt !== null) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\r\n 'Query.startAfter() before calling Query.orderBy().');\r\n }\r\n if (this._query.endAt !== null) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\r\n 'Query.endBefore() before calling Query.orderBy().');\r\n }\r\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\r\n var orderBy = new OrderBy(fieldPath, direction);\r\n this.validateNewOrderBy(orderBy);\r\n return new Query$$1(this._query.addOrderBy(orderBy), this.firestore);\r\n };\r\n Query$$1.prototype.limit = function (n) {\r\n validateExactNumberOfArgs('Query.limit', arguments, 1);\r\n validateArgType('Query.limit', 'number', 1, n);\r\n if (n <= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\r\n 'positive.');\r\n }\r\n return new Query$$1(this._query.withLimit(n), this.firestore);\r\n };\r\n Query$$1.prototype.startAt = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \r\n /*before=*/ true);\r\n return new Query$$1(this._query.withStartAt(bound), this.firestore);\r\n };\r\n Query$$1.prototype.startAfter = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \r\n /*before=*/ false);\r\n return new Query$$1(this._query.withStartAt(bound), this.firestore);\r\n };\r\n Query$$1.prototype.endBefore = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \r\n /*before=*/ true);\r\n return new Query$$1(this._query.withEndAt(bound), this.firestore);\r\n };\r\n Query$$1.prototype.endAt = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \r\n /*before=*/ false);\r\n return new Query$$1(this._query.withEndAt(bound), this.firestore);\r\n };\r\n Query$$1.prototype.isEqual = function (other) {\r\n if (!(other instanceof Query$$1)) {\r\n throw invalidClassError('isEqual', 'Query', 1, other);\r\n }\r\n return (this.firestore === other.firestore && this._query.isEqual(other._query));\r\n };\r\n /** Helper function to create a bound from a document or fields */\r\n Query$$1.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\r\n validateDefined(methodName, 1, docOrField);\r\n if (docOrField instanceof DocumentSnapshot) {\r\n if (fields.length > 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\r\n }\r\n var snap = docOrField;\r\n if (!snap.exists) {\r\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\r\n (methodName + \"().\"));\r\n }\r\n return this.boundFromDocument(methodName, snap._document, before);\r\n }\r\n else {\r\n var allFields = [docOrField].concat(fields);\r\n return this.boundFromFields(methodName, allFields, before);\r\n }\r\n };\r\n /**\r\n * Create a Bound from a query and a document.\r\n *\r\n * Note that the Bound will always include the key of the document\r\n * and so only the provided document will compare equal to the returned\r\n * position.\r\n *\r\n * Will throw if the document does not contain all fields of the order by\r\n * of the query.\r\n */\r\n Query$$1.prototype.boundFromDocument = function (methodName, doc, before) {\r\n var components = [];\r\n // Because people expect to continue/end a query at the exact document\r\n // provided, we need to use the implicit sort order rather than the explicit\r\n // sort order, because it's guaranteed to contain the document key. That way\r\n // the position becomes unambiguous and the query continues/ends exactly at\r\n // the provided document. Without the key (by using the explicit sort\r\n // orders), multiple documents could match the position, yielding duplicate\r\n // results.\r\n for (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n if (orderBy.field.isKeyField()) {\r\n components.push(new RefValue(this.firestore._databaseId, doc.key));\r\n }\r\n else {\r\n var value = doc.field(orderBy.field);\r\n if (value !== undefined) {\r\n components.push(value);\r\n }\r\n else {\r\n var field = orderBy.field.canonicalString();\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\r\n (\"document for which the field '\" + field + \"' (used as the \") +\r\n \"orderBy) does not exist.\");\r\n }\r\n }\r\n }\r\n return new Bound(components, before);\r\n };\r\n /**\r\n * Converts a list of field values to a Bound for the given query.\r\n */\r\n Query$$1.prototype.boundFromFields = function (methodName, values, before) {\r\n // Use explicit order by's because it has to match the query the user made\r\n var orderBy = this._query.explicitOrderBy;\r\n if (values.length > orderBy.length) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\r\n \"The number of arguments must be less than or equal to the \" +\r\n \"number of Query.orderBy() clauses\");\r\n }\r\n var components = [];\r\n for (var i = 0; i < values.length; i++) {\r\n var rawValue = values[i];\r\n var orderByComponent = orderBy[i];\r\n if (orderByComponent.field.isKeyField()) {\r\n if (typeof rawValue !== 'string') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\r\n (methodName + \"(), but got a \" + typeof rawValue));\r\n }\r\n if (rawValue.indexOf('/') !== -1) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\r\n (methodName + \"()\"));\r\n }\r\n var key = new DocumentKey(this._query.path.child(rawValue));\r\n components.push(new RefValue(this.firestore._databaseId, key));\r\n }\r\n else {\r\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\r\n components.push(wrapped);\r\n }\r\n }\r\n return new Bound(components, before);\r\n };\r\n Query$$1.prototype.onSnapshot = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\r\n var options = {};\r\n var observer;\r\n var currArg = 0;\r\n if (typeof args[currArg] === 'object' &&\r\n !isPartialObserver(args[currArg])) {\r\n options = args[currArg];\r\n validateOptionNames('Query.onSnapshot', options, [\r\n 'includeQueryMetadataChanges',\r\n 'includeDocumentMetadataChanges'\r\n ]);\r\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\r\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\r\n currArg++;\r\n }\r\n if (isPartialObserver(args[currArg])) {\r\n observer = args[currArg];\r\n }\r\n else {\r\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\r\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\r\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\r\n observer = {\r\n next: args[currArg],\r\n error: args[currArg + 1],\r\n complete: args[currArg + 2]\r\n };\r\n }\r\n return this.onSnapshotInternal(options, observer);\r\n };\r\n Query$$1.prototype.onSnapshotInternal = function (options, observer) {\r\n var _this = this;\r\n var errHandler = function (err) {\r\n console.error('Uncaught Error in onSnapshot:', err);\r\n };\r\n if (observer.error) {\r\n errHandler = observer.error.bind(observer);\r\n }\r\n var asyncObserver = new AsyncObserver({\r\n next: function (result) {\r\n if (observer.next) {\r\n observer.next(new QuerySnapshot(_this.firestore, _this._query, result));\r\n }\r\n },\r\n error: errHandler\r\n });\r\n var firestoreClient = this.firestore.ensureClientConfigured();\r\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\r\n return function () {\r\n asyncObserver.mute();\r\n firestoreClient.unlisten(internalListener);\r\n };\r\n };\r\n Query$$1.prototype.get = function (options) {\r\n var _this = this;\r\n validateBetweenNumberOfArgs('Query.get', arguments, 0, 1);\r\n return new Promise(function (resolve, reject) {\r\n if (options && options.source === 'cache') {\r\n _this.firestore\r\n .ensureClientConfigured()\r\n .getDocumentsFromLocalCache(_this._query)\r\n .then(function (viewSnap) {\r\n resolve(new QuerySnapshot(_this.firestore, _this._query, viewSnap));\r\n }, reject);\r\n }\r\n else {\r\n _this.getViaSnapshotListener(resolve, reject, options);\r\n }\r\n });\r\n };\r\n Query$$1.prototype.getViaSnapshotListener = function (resolve, reject, options) {\r\n var unlisten = this.onSnapshotInternal({\r\n includeDocumentMetadataChanges: false,\r\n includeQueryMetadataChanges: true,\r\n waitForSyncWhenOnline: true\r\n }, {\r\n next: function (result) {\r\n // Remove query first before passing event to user to avoid\r\n // user actions affecting the now stale query.\r\n unlisten();\r\n if (result.metadata.fromCache &&\r\n options &&\r\n options.source === 'server') {\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get documents from server. (However, these ' +\r\n 'documents may exist in the local cache. Run again ' +\r\n 'without setting source to \"server\" to ' +\r\n 'retrieve the cached documents.)'));\r\n }\r\n else {\r\n resolve(result);\r\n }\r\n },\r\n error: reject\r\n });\r\n };\r\n Query$$1.prototype.validateNewFilter = function (filter) {\r\n if (filter instanceof RelationFilter && filter.isInequality()) {\r\n var existingField = this._query.getInequalityFilterField();\r\n if (existingField !== null && !existingField.isEqual(filter.field)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\r\n ' (<, <=, >, or >=) must be on the same field. But you have' +\r\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\r\n (\" and '\" + filter.field.toString() + \"'\"));\r\n }\r\n var firstOrderByField = this._query.getFirstOrderByField();\r\n if (firstOrderByField !== null) {\r\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\r\n }\r\n }\r\n };\r\n Query$$1.prototype.validateNewOrderBy = function (orderBy) {\r\n if (this._query.getFirstOrderByField() === null) {\r\n // This is the first order by. It must match any inequality.\r\n var inequalityField = this._query.getInequalityFilterField();\r\n if (inequalityField !== null) {\r\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\r\n }\r\n }\r\n };\r\n Query$$1.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\r\n if (!orderBy.isEqual(inequality)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\r\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\r\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\r\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\r\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\r\n }\r\n };\r\n return Query$$1;\r\n}());\r\nvar QuerySnapshot = /** @class */ (function () {\r\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\r\n this._firestore = _firestore;\r\n this._originalQuery = _originalQuery;\r\n this._snapshot = _snapshot;\r\n this._cachedChanges = null;\r\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\r\n }\r\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\r\n get: function () {\r\n var result = [];\r\n this.forEach(function (doc) { return result.push(doc); });\r\n return result;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\r\n get: function () {\r\n return this._snapshot.docs.isEmpty();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\r\n get: function () {\r\n return this._snapshot.docs.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\r\n var _this = this;\r\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\r\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\r\n this._snapshot.docs.forEach(function (doc) {\r\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\r\n });\r\n };\r\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\r\n get: function () {\r\n return new Query$1(this._originalQuery, this._firestore);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\r\n get: function () {\r\n if (!this._cachedChanges) {\r\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\r\n }\r\n return this._cachedChanges;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** Check the equality. The call can be very expensive. */\r\n QuerySnapshot.prototype.isEqual = function (other) {\r\n if (!(other instanceof QuerySnapshot)) {\r\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\r\n }\r\n return (this._firestore === other._firestore &&\r\n this._originalQuery.isEqual(other._originalQuery) &&\r\n this._snapshot.isEqual(other._snapshot));\r\n };\r\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\r\n return new QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\r\n };\r\n return QuerySnapshot;\r\n}());\r\nvar CollectionReference = /** @class */ (function (_super) {\r\n __extends(CollectionReference, _super);\r\n function CollectionReference(path, firestore) {\r\n var _this = _super.call(this, Query.atPath(path), firestore) || this;\r\n if (path.length % 2 !== 1) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\r\n 'references must have an odd number of segments, but ' +\r\n (path.canonicalString() + \" has \" + path.length));\r\n }\r\n return _this;\r\n }\r\n Object.defineProperty(CollectionReference.prototype, \"id\", {\r\n get: function () {\r\n return this._query.path.lastSegment();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\r\n get: function () {\r\n var parentPath = this._query.path.popLast();\r\n if (parentPath.isEmpty()) {\r\n return null;\r\n }\r\n else {\r\n return new DocumentReference(new DocumentKey(parentPath), this.firestore);\r\n }\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(CollectionReference.prototype, \"path\", {\r\n get: function () {\r\n return this._query.path.canonicalString();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n CollectionReference.prototype.doc = function (pathString) {\r\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\r\n // We allow omission of 'pathString' but explicitly prohibit passing in both\r\n // 'undefined' and 'null'.\r\n if (arguments.length === 0) {\r\n pathString = AutoId.newId();\r\n }\r\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\r\n if (pathString === '') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\r\n }\r\n var path = ResourcePath.fromString(pathString);\r\n return DocumentReference.forPath(this._query.path.child(path), this.firestore);\r\n };\r\n CollectionReference.prototype.add = function (value) {\r\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\r\n validateArgType('CollectionReference.add', 'object', 1, value);\r\n var docRef = this.doc();\r\n return docRef.set(value).then(function () { return docRef; });\r\n };\r\n return CollectionReference;\r\n}(Query$1));\r\nfunction validateSetOptions(methodName, options) {\r\n if (options === undefined) {\r\n return {\r\n merge: false\r\n };\r\n }\r\n validateOptionNames(methodName, options, ['merge']);\r\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\r\n return options;\r\n}\r\nfunction validateSnapshotOptions(methodName, options) {\r\n if (options === undefined) {\r\n return {};\r\n }\r\n validateOptionNames(methodName, options, ['serverTimestamps']);\r\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\r\n return options;\r\n}\r\nfunction validateReference(methodName, documentRef, firestore) {\r\n if (!(documentRef instanceof DocumentReference)) {\r\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\r\n }\r\n else if (documentRef.firestore !== firestore) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\r\n }\r\n else {\r\n return documentRef;\r\n }\r\n}\r\n/**\r\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\r\n *\r\n * Exported for testing.\r\n */\r\nfunction changesFromSnapshot(firestore, snapshot) {\r\n if (snapshot.oldDocs.isEmpty()) {\r\n // Special case the first snapshot because index calculation is easy and\r\n // fast\r\n var lastDoc_1;\r\n var index_1 = 0;\r\n return snapshot.docChanges.map(function (change) {\r\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\r\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\r\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\r\n lastDoc_1 = change.doc;\r\n return {\r\n type: 'added',\r\n doc: doc,\r\n oldIndex: -1,\r\n newIndex: index_1++\r\n };\r\n });\r\n }\r\n else {\r\n // A DocumentSet that is updated incrementally as changes are applied to use\r\n // to lookup the index of a document.\r\n var indexTracker_1 = snapshot.oldDocs;\r\n return snapshot.docChanges.map(function (change) {\r\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\r\n var oldIndex = -1;\r\n var newIndex = -1;\r\n if (change.type !== ChangeType.Added) {\r\n oldIndex = indexTracker_1.indexOf(change.doc.key);\r\n assert(oldIndex >= 0, 'Index for document not found');\r\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\r\n }\r\n if (change.type !== ChangeType.Removed) {\r\n indexTracker_1 = indexTracker_1.add(change.doc);\r\n newIndex = indexTracker_1.indexOf(change.doc.key);\r\n }\r\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\r\n });\r\n }\r\n}\r\nfunction resultChangeType(type) {\r\n switch (type) {\r\n case ChangeType.Added:\r\n return 'added';\r\n case ChangeType.Modified:\r\n case ChangeType.Metadata:\r\n return 'modified';\r\n case ChangeType.Removed:\r\n return 'removed';\r\n default:\r\n return fail('Unknown change type: ' + type);\r\n }\r\n}\r\n// Export the classes with a private constructor (it will fail if invoked\r\n// at runtime). Note that this still allows instanceof checks.\r\n// We're treating the variables as class names, so disable checking for lower\r\n// case variable names.\r\n// tslint:disable:variable-name\r\nvar PublicFirestore = makeConstructorPrivate(Firestore, 'Use firebase.firestore() instead.');\r\nvar PublicTransaction = makeConstructorPrivate(Transaction$1, 'Use firebase.firestore().runTransaction() instead.');\r\nvar PublicWriteBatch = makeConstructorPrivate(WriteBatch, 'Use firebase.firestore().batch() instead.');\r\nvar PublicDocumentReference = makeConstructorPrivate(DocumentReference, 'Use firebase.firestore().doc() instead.');\r\nvar PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\r\nvar PublicQueryDocumentSnapshot = makeConstructorPrivate(QueryDocumentSnapshot);\r\nvar PublicQuery = makeConstructorPrivate(Query$1);\r\nvar PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\r\nvar PublicCollectionReference = makeConstructorPrivate(CollectionReference, 'Use firebase.firestore().collection() instead.');\r\n// tslint:enable:variable-name\n\n/**\r\n * Copyright 2017 Google Inc.\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\nvar firestoreNamespace = {\r\n Firestore: PublicFirestore,\r\n GeoPoint: GeoPoint,\r\n Timestamp: Timestamp,\r\n Blob: PublicBlob,\r\n Transaction: PublicTransaction,\r\n WriteBatch: PublicWriteBatch,\r\n DocumentReference: PublicDocumentReference,\r\n DocumentSnapshot: PublicDocumentSnapshot,\r\n Query: PublicQuery,\r\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\r\n QuerySnapshot: PublicQuerySnapshot,\r\n CollectionReference: PublicCollectionReference,\r\n FieldPath: FieldPath$1,\r\n FieldValue: PublicFieldValue,\r\n setLogLevel: Firestore.setLogLevel\r\n};\r\n/**\r\n * Configures Firestore as part of the Firebase SDK by calling registerService.\r\n */\r\nfunction configureForFirebase(firebase$$1) {\r\n firebase$$1.INTERNAL.registerService('firestore', function (app) { return new Firestore(app); }, shallowCopy(firestoreNamespace));\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\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\nfunction registerFirestore(instance) {\r\n configureForFirebase(instance);\r\n}\r\nregisterFirestore(firebase);\n\nexport { registerFirestore };\n"],"names":["LogLevel","defaultLogLevel","INFO","defaultLogHandler","instance","logType","args","_i","arguments","length","logLevel","now","Date","toISOString","DEBUG","VERBOSE","console","log","apply","name","concat","info","WARN","warn","ERROR","error","Error","Logger","this","_logLevel","_logHandler","Object","defineProperty","prototype","get","set","val","TypeError","enumerable","configurable","debug","extendStatics","setPrototypeOf","__proto__","Array","d","b","p","hasOwnProperty","__extends","__","constructor","create","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","__generator","body","f","y","t","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","n","v","op","call","pop","push","goog","k","l","a","split","c","aa","ba","toString","splice","propertyIsEnumerable","ca","da","ea","q","Math","random","fa","ha","bind","ia","slice","unshift","r","Function","indexOf","ja","u","H","Ib","ka","captureStackTrace","stack","message","String","la","ma","w","na","pa","i","m","$","shift","qa","ra","forEach","sa","ta","charAt","ua","va","wa","xa","test","ya","trim","exec","x","za","Aa","navigator","Ba","userAgent","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","Ka","La","z","Ma","Na","Oa","toLowerCase","Pa","Ra","Qa","document","documentMode","Sa","Ta","Ua","parseFloat","Wa","Va","max","h","parseInt","Xa","compatMode","Ya","freeze","Za","Number","$a","ab","addEventListener","removeEventListener","A","type","target","bb","relatedTarget","button","screenY","screenX","clientY","clientX","key","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","nodeName","fromElement","toElement","pageX","pageY","cb","defaultPrevented","2","3","4","preventDefault","returnValue","keyCode","db","eb","fb","listener","proxy","src","capture","ga","Z","gb","hb","jb","ib","add","kb","lb","nb","once","ob","pb","qb","rb","sb","attachEvent","tb","addListener","removeListener","ub","vb","wb","detachEvent","xb","yb","parentNode","zb","handleEvent","B","N","J","Ab","Bb","replace","Cb","eval","Db","Eb","Fb","join","Boolean","Gb","valueOf","isFinite","isNaN","dispatchEvent","Hb","\"","\\","/","\b","\f","\n","\r","\t","\u000b","charCodeAt","substr","Jb","Kb","Nb","Lb","reset","Rb","Tb","Ob","Pb","Qb","setTimeout","Sb","MessageChannel","window","postMessage","createElement","style","display","documentElement","appendChild","contentWindow","open","write","close","location","protocol","host","origin","data","port1","onmessage","port2","onreadystatechange","removeChild","Ub","Vb","setImmediate","Window","Wb","Xb","Yb","O","clearTimeout","Zb","$b","ac","Y","bc","start","cc","dc","ec","fc","hc","C","ic","jc","kc","lc","mc","nc","oc","pc","qc","lastIndexOf","D","rc","E","sc","tc","F","I","X","Mb","uc","G","vc","wc","xc","JSON","parse","yc","zc","Ac","Bc","K","Cc","Dc","Ec","Fc","NO_ERROR","TIMEOUT","Gc","Hc","Ic","Jc","Kc","Lc","OPEN","Oc","Mc","Nc","Pc","Qc","ActiveXObject","XMLHttpRequest","L","T","R","Rc","S","j","U","s","o","Sc","Tc","Uc","Vc","Wc","M","Xc","Yc","Zc","$c","ad","W","V","bd","cd","dd","ed","fd","gd","hd","id","jd","mb","substring","kd","abort","ld","md","od","pd","nd","cancel","qd","rd","decodeURIComponent","Q","sd","td","ud","vd","wd","match","xd","yd","Ed","zd","Fd","Gd","floor","abs","Hd","Id","decodeURI","encodeURI","Jd","Ad","encodeURIComponent","Bd","Cd","Dd","Ld","Kd","Md","Pd","Qd","Rd","Sd","Td","Ud","Wd","Xd","Yd","Zd","$d","ae","PerformanceNavigationTiming","performance","getEntriesByType","nextHopProtocol","oa","Vd","be","ce","de","ee","fe","ge","he","ie","je","ke","le","Image","onload","me","onerror","onabort","ontimeout","headers","ne","stringify","oe","pe","se","timeout","qe","te","ue","ve","self","re","readyState","getResponseHeader","we","xe","ye","supportsCrossDomainXhr","concurrentRequestLimit","backgroundChannelTest","fastHandshake","ze","Ae","Be","sendBeacon","Ce","De","Ee","Fe","Ge","He","Je","Ie","round","min","Ke","Le","Me","Ne","hostname","port","Oe","Pe","Qe","testUrl","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","X-Client-Protocol","initMessageHeaders","messageContentType","X-WebChannel-Content-Type","X-WebChannel-Client-Profile","httpHeadersOverwriteParam","sendRawJson","httpSessionIdParam","Re","Se","__sm__","Te","status","toUpperCase","FormData","setRequestHeader","responseType","withCredentials","send","statusText","responseText","__data__","Ue","Ve","We","reverse","Xe","Ye","Ze","af","$e","bf","cf","df","ef","createWebChannel","HTTP_ERROR","COMPLETE","EventType","CLOSE","MESSAGE","listen","getObject","releaseObject","listenOnce","getLastError","getLastErrorCode","getStatus","getStatusText","getResponseJson","getResponseText","module","createWebChannelTransport","ErrorCode","WebChannel","XhrIoPool","global","SDK_VERSION","firebase","logClient","LogLevel$1","getLogLevel","SILENT","setLogLevel","newLevel","tag","msg","obj","map","argToString","platform","PlatformSupport","getPlatform","formatJSON","fail","failure","assert","assertion","LogLevel$$1","setPlatform","emptyByteString","Code","OK","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","FirestoreError","_super","code","_this","makeConstructorPrivate","cls","optionalMessage","PublicConstructor","staticProperty","contains","defaulted","defaultValue","undefined","forEachNumber","fn","num","isEmpty","shallowCopy","validateExactNumberOfArgs","functionName","numberOfArgs","formatPlural","validateAtLeastNumberOfArgs","minNumberOfArgs","validateBetweenNumberOfArgs","maxNumberOfArgs","validateNamedArrayAtLeastNumberOfElements","minNumberOfElements","validateArgType","position","argument","validateType","ordinal","validateOptionalArgType","validateNamedType","optionName","validateNamedOptionalType","validateNamedPropertyEquals","inputName","input","expected","expectedDescription","expected_1","valueDescription","actualDescription","validateNamedOptionalPropertyEquals","isPlainObject","description","getPrototypeOf","customObjectName","tryGetCustomObjectType","results","validateDefined","validateOptionNames","options","optionNames","invalidClassError","str","AutoId","newId","chars","autoId","primitiveComparator","left","right","equals","isEqual","arrayEquals","immediatePredecessor","lastIndex","fromCharCode","immediateSuccessor","assertUint8ArrayAvailable","Uint8Array","assertBase64Available","base64Available","Blob","binaryString","_binaryString","fromBase64String","base64","atob","fromUint8Array","array","char","toBase64","btoa","toUint8Array","buffer","other","_compareTo","PublicBlob","GeoPoint","latitude","longitude","_lat","_long","Timestamp","seconds","nanoseconds","fromMillis","fromDate","date","getTime","milliseconds","toDate","toMillis","DatabaseInfo","databaseId","persistenceKey","ssl","DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","compareTo","DOCUMENT_KEY_NAME","Path","segments","offset","init","len","construct","path","comparator","child","nameOrPath","limit","segment","popFirst","size","popLast","firstSegment","lastSegment","index","isPrefixOf","end","toArray","p1","p2","ResourcePath","canonicalString","fromString","filter","EMPTY_PATH","identifierRegExp","FieldPath","isValidIdentifier","isKeyField","keyField","fromServerFormat","current","addCurrentSegment","inBackticks","DocumentKey","isDocumentKey","k1","k2","fromSegments","fromPathString","EMPTY","Document","version","hasLocalMutations","field","fieldValue","compareByKey","d1","d2","compareByField","v1","v2","NoDocument","SortedMap","root","LLRBNode","insert","copy","BLACK","remove","node","cmp","prunedNodes","minKey","maxKey","inorderTraversal","action","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","nl","nr","checkMaxDepth","blackDepth","check","pow","LLRBEmptyNode","TypeOrder","ServerTimestampBehavior","FieldValueOptions","serverTimestampBehavior","timestampsInSnapshots","fromSnapshotOptions","serverTimestamps","Estimate","Previous","Default","FieldValue","defaultCompareTo","typeOrder","NullValue","internalValue","INSTANCE","BooleanValue","of","TRUE","FALSE","NumberValue","numericComparator","numericEquals","IntegerValue","DoubleValue","NAN","NaN","POSITIVE_INFINITY","Infinity","NEGATIVE_INFINITY","StringValue","TimestampValue","ServerTimestampValue","localWriteTime","previousValue","BlobValue","RefValue","GeoPointValue","ObjectValue","it1","it2","next1","next2","to","setChild","newChild","delete","pathSegment","childName","ArrayValue","minLength","NumberAsAny","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","isInteger","isNullOrUndefined","isSafeInteger","Query","explicitOrderBy","filters","startAt","endAt","memoizedCanonicalId","memoizedOrderBy","assertValidBound","atPath","inequalityField","getInequalityFilterField","firstOrderByField","getFirstOrderByField","KEY_ORDERING_ASC","OrderBy","foundKeyOrdering","_a","orderBy","lastDirection","dir","Direction","ASCENDING","KEY_ORDERING_DESC","addFilter","RelationFilter","isInequality","newFilters","addOrderBy","newOrderBy","withLimit","withStartAt","bound","withEndAt","canonicalId","_b","_c","docComparator","comparedOnKeyField","comp","compare","matches","doc","matchesAncestor","matchesOrderBy","matchesFilters","matchesBounds","hasLimit","isDocumentQuery","docPath","sortsBeforeDocument","RelationOp","LESS_THAN","LESS_THAN_OR_EQUAL","EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","refValue","comparison","matchesComparison","matchesValue","NullFilter","NanFilter","fieldFilter","DESCENDING","Bound","before","orderByComponent","component","docValue","thisPosition","otherPosition","isKeyOrderBy","SnapshotVersion","timestamp","fromMicroseconds","fromTimestamp","forDeletedDoc","MIN","toMicroseconds","toTimestamp","QueryPurpose","QueryData","query","targetId","purpose","snapshotVersion","resumeToken","update","updated","FieldMask","fields","ServerTimestampTransform","FieldTransform","transform","MutationResult","transformResults","MutationType","Precondition","updateTime","exists","isValidFor","maybeDoc","isNone","NONE","Mutation","verifyKeyMatches","getPostMutationVersion","SetMutation","precondition","Set","applyToRemoteDocument","mutationResult","applyToLocalView","baseDoc","PatchMutation","fieldMask","Patch","newData","patchDocument","patchObject","fieldPath","newValue","TransformMutation","fieldTransforms","Transform","requireDocument","transformObject","localTransformResults","fieldTransform","DeleteMutation","Delete","ExistenceFilter","count","RpcCode","isPermanentError","mapCodeFromRpcStatus","mapCodeFromRpcCode","mapRpcCodeFromCode","mapCodeFromHttpStatus","SortedSet","fromMapKeys","keys","has","elem","first","last","forEachInRange","range","iter","forEachWhile","firstAfterOrEqual","unionWith","thisIt","otherIt","thisElem","otherElem","EMPTY_MAYBE_DOCUMENT_MAP","maybeDocumentMap","EMPTY_DOCUMENT_MAP","documentMap","EMPTY_DOCUMENT_VERSION_MAP","documentVersionMap","EMPTY_DOCUMENT_KEY_SET","documentKeySet","RemoteEvent","targetChanges","documentUpdates","addDocumentUpdate","handleExistenceFilterMismatch","mapping","ResetMapping","currentStatusUpdate","CurrentStatusUpdate","MarkNotCurrent","EMPTY_KEY_SET","docs","UpdateMapping","addedDocuments","removedDocuments","applyToKeySet","DocumentWatchChange","updatedTargetIds","removedTargetIds","newDoc","ExistenceFilterChange","existenceFilter","WatchTargetChangeState","WatchTargetChange","state","targetIds","cause","WatchChangeAggregator","listenTargets","pendingTargetResponses","existenceFilters","frozen","watchChange","addDocumentChange","addTargetChange","addExistenceFilterChange","addChanges","watchChanges","change","createRemoteEvent","isActiveTarget","ensureTargetChange","None","docChange","relevant","targetChange","NoChange","applyResumeToken","Added","recordTargetResponse","Removed","Current","MarkCurrent","Reset","newCount","DIRECTIONS","dirs","OPERATORS","ISO_REG_EXP","RegExp","assertPresent","parseInt64","JsonProtoSerializer","useProto3Json","unsafeCastProtoByteString","byteString","fromRpcStatus","toInt32Value","fromInt32Value","nanos","fromIso8601String","utc","fraction","nanoStr","toBytes","bytes","fromBlob","blob","toVersion","fromVersion","toResourceName","fullyQualifiedPrefixPath","fromResourceName","resource","isValidResourceName","toName","fromName","extractLocalPathFromResourceName","toQueryPath","encodedDatabaseId","fromQueryPath","resourceName","toValue","nullValue","booleanValue","integerValue","doubleValue","stringValue","mapValue","toMapValue","arrayValue","toArrayValue","timestampValue","geoPointValue","bytesValue","referenceValue","fromValue","hasTag","fromFields","values","dbId","toMutationDocument","toFields","toDocument","fromDocument","object","fromFound","found","fromMissing","missing","readTime","fromMaybeDocument","toWatchTargetChangeState","toTestWatchChange","documentChange","documentDelete","documentRemove","targetChangeType","fromWatchChange","fromWatchTargetChangeState","causeProto","entityChange","docDelete","docRemove","versionFromListenResponse","toMutation","mutation","updateMask","toDocumentMask","toFieldTransform","currentDocument","toPrecondition","fromMutation","proto","fromPrecondition","fromDocumentMask","fromFieldTransform","fromWriteResult","fromWriteResults","protos","setToServerValue","toDocumentsTarget","documents","fromDocumentsTarget","documentsTarget","toQueryTarget","structuredQuery","parent","from","collectionId","where","toFilter","toOrder","toCursor","fromQueryTarget","fromCount","filterBy","fromFilter","fromOrder","fromCursor","toListenRequestLabels","queryData","toLabel","goog-listen-tags","Listen","ExistenceFilterMismatch","LimboResolution","toTarget","toRelationFilter","toUnaryFilter","compositeFilter","unaryFilter","fromUnaryFilter","fromRelationFilter","reduce","accum","orderBys","order","toPropertyOrder","fromPropertyOrder","cursor","toDirection","fromDirection","toOperatorName","fromOperatorName","toFieldPathReference","fromFieldPathReference","fieldReference","direction","nanField","nullField","fieldPaths","StreamBridge","sendFn","closeFn","onOpen","callback","wrappedOnOpen","onClose","wrappedOnClose","onMessage","wrappedOnMessage","callOnOpen","callOnClose","err","callOnMessage","LOG_TAG","RPC_STREAM_SERVICE","RPC_URL_VERSION","RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","X_GOOG_API_CLIENT_VALUE","XHR_TIMEOUT_SECS","WebChannelConnection","pool","baseUrl","modifyHeadersForRequest","token","header","authHeaders","invokeRPC","rpcName","request","url","makeUrl","xhr","json","status_1","requestString","Content-Type","invokeStreamingRPC","openStream","urlParts","webchannelTransport","channel","opened","closed","streamBridge","unguardedEventListen","param","msgData","error$$1","status_2","urlRpcName","BrowserPlatform","loadConnection","databaseInfo","newSerializer","encoded","raw","FieldPath$1","FieldPath$$1","fieldNames","_internalPath","documentId","_DOCUMENT_ID","RESERVED","OnlineState","ChangeType","SyncState","fromDotSeparatedString","search","DocumentChangeSet","changeMap","track","oldChange","Metadata","Modified","getChanges","changes","ViewSnapshot","oldDocs","docChanges","fromCache","hasPendingWrites","syncStateChanged","otherChanges","DocumentSet","keyedMap","sortedSet","emptySet","oldSet","thisDoc","otherDoc","docStrings","newSet","ObjectMap","mapKeyFn","inner","matches_1","otherKey","entries","entries_1","QueryListenersInfo","listeners","EventManager","syncEngine","queries","onlineState","Unknown","subscribe","onChange","onError","firstListen","queryInfo","applyOnlineStateChange","viewSnap","onViewSnapshot","unlisten","lastListen","viewSnaps","viewSnaps_1","QueryListener","queryObserver","raisedInitialEvent","snap","includeDocumentMetadataChanges","shouldRaiseEvent","shouldRaiseInitialEvent","raiseInitialEvent","maybeOnline","Offline","waitForSyncWhenOnline","hasPendingWritesChanged","includeQueryMetadataChanges","getInitialViewChanges","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","catch","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","all","promise","nextPromise","idx","initial","EagerGarbageCollector","isEager","sources","potentialGarbage","addGarbageSource","garbageSource","setGarbageCollector","removeGarbageSource","addPotentialGarbageKey","collectGarbage","txn","promises","garbageKeys","hasRefsPromise","documentHasAnyReferences","hasRefs","source","containsKey","LocalViewChanges","addedKeys","removedKeys","fromSnapshot","viewSnapshot","ReferenceSet","refsByKey","DocReference","refsByTarget","compareByTargetId","garbageCollector","addReference","ref","addReferences","removeReference","removeRef","removeReferences","removeReferencesForId","emptyKey","startRef","endRef","removeAllReferences","referencesForId","firstRef","targetOrBatchId","RESERVED_BITS","GeneratorIds","TargetIdGenerator","generatorId","initAfter","afterWithoutGenerator","afterGenerator","previousId","forLocalStore","LocalStore","forSyncEngine","SyncEngine","AddedLimboDocument","RemovedLimboDocument","View","syncedDocuments","syncState","limboDocuments","mutatedKeys","documentSet","computeDocChanges","previousChanges","changeSet","oldDocumentSet","newMutatedKeys","newDocumentSet","needsRefill","lastDocInLimit","newMaybeDoc","oldDoc","docsEqual","applyChanges","sort","c1","c2","compareChangeType","applyTargetChange","limboChanges","updateLimboDocuments","newSyncState","Synced","Local","snapshot","shouldBeInLimbo","targetMapping","oldLimboDocuments","LOG_TAG$1","QueryView","view","localStore","remoteStore","currentUser","viewHandler","errorHandler","queryViewsByQuery","queryViewsByTarget","limboTargetsByKey","limboKeysByTarget","limboDocumentRefs","limboCollector","mutationUserCallbacks","targetIdGenerator","assertSubscribed","allocateQuery","executeQuery","remoteDocumentKeys","remoteKeys","viewDocChanges","viewChange","queryView","releaseQuery","removeAndCleanupQuery","batch","userCallback","localWrite","addMutationCallback","batchId","emitNewSnapsAndNotifyLocalStore","fillWritePipeline","wrapUpdateFunctionError","runTransaction","updateFunction","retries","transaction","createTransaction","userPromise","wrappedUpdateFunction","commit","applyRemoteEvent","remoteEvent","limboKey","newViewSnapshots","rejectListen","docMap","event_1","queryView_1","applySuccessfulWrite","mutationBatchResult","processUserCallback","acknowledgeBatch","rejectFailedWrite","rejectBatch","newCallbacks","toKey","gcLimboDocuments","updateTrackedLimbos","limboChanges_1","limboChange","trackLimboChange","limboTargetId","currentLimboDocs","newSnaps","docChangesInAllViews","queriesProcessed","notifyLocalViewChanges","fnName","handleUserChange","user","BATCHID_UNKNOWN","MutationBatch","mutations","docKey","batchResult","mutationResults","keySet","isTombstone","toTombstone","MutationBatchResult","commitVersion","streamToken","docVersions","versionMap","escapeChar","encodedSeparatorChar","encodedNul","encodedEscape","encode","encodeSeparator","encodeSegment","resultBuf","decode","lastReasonableEscapeIndex","segmentBuilder","currentPiece","SCHEMA_VERSION","createOrUpgradeDb","createOwnerStore","createMutationQueue","createQueryCache","createRemoteDocumentCache","ensureTargetGlobalExists","targetGlobal","saveTargetCount","DbTimestamp","DbOwner","ownerId","leaseTimestampMs","store","createObjectStore","DbMutationQueue","userId","lastAcknowledgedBatchId","lastStreamToken","keyPath","DbMutationBatch","localWriteTimeMs","DbDocumentMutation","prefixForUser","prefixForPath","PLACEHOLDER","DbRemoteDocument","DbNoDocument","noDocument","DbTarget","lastListenSequenceNumber","queryTargetsIndexName","queryTargetsKeyPath","DbTargetDocument","documentTargetsIndex","documentTargetsKeyPath","DbTargetGlobal","highestTargetId","highestListenSequenceNumber","lastRemoteSnapshotVersion","targetCount","createIndex","unique","metadata","globalStore","put","ALL_STORES","LOG_TAG$2","SimpleDb","openOrCreate","runUpgrade","isAvailable","indexedDB","onsuccess","event","onupgradeneeded","oldVersion","SimpleDbTransaction","wrapRequest","deleteDatabase","mode","objectStores","transactionFn","transactionFnResult","completionPromise","IterationController","dbCursor","shouldStop","nextKey","skip","aborted","oncomplete","objectStoreNames","storeName","objectStore","SimpleDbStore","keyOrValue","loadAll","indexOrRange","iterateCursor","deleteAll","keysOnly","control","iterate","optionsOrCallback","cursorRequest","controller","userResult","primaryKey","skipToKey","continue","indexName","openKeyCursor","openCursor","IndexedDbMutationQueue","serializer","forUser","uid","isAuthenticated","loadNextBatchIdFromDb","nextBatchId","mutationQueuesStore","checkEmpty","empty","maxBatchId","mutationsStore","nextUser","IDBKeyRange","keyForBatchId","getNextBatchId","getHighestAcknowledgedBatchId","validateStreamToken","getLastStreamToken","setLastStreamToken","addMutationBatch","dbBatch","toDbMutationBatch","mutations_1","indexKey","documentMutationsStore","lookupMutationBatch","fromDbMutationBatch","getNextMutationBatchAfterBatchId","lowerBound","foundBatch","getAllMutationBatches","dbBatches","getAllMutationBatchesThroughBatchId","getAllMutationBatchesAffectingDocumentKey","documentKey","indexPrefix","indexStart","userID","encodedPath","batchID","mutationKey","getAllMutationBatchesAffectingQuery","queryPath","immediateChildrenLength","uniqueBatchIDs","removeMutationBatches","batches","indexTxn","_loop_1","only","this_1","numDeleted","removePromise","batches_1","performConsistencyCheck","startRange","danglingMutationReferences","gc","getStore","IndexedDbQueryCache","globalTargetStore","lastSavedVersion","getHighestTargetId","getLastRemoteSnapshotVersion","setLastRemoteSnapshotVersion","addQueryData","saveQueryData","updateMetadataFromQueryData","saveMetadata","updateQueryData","removeQueryData","removeMatchingKeysForTargetId","targetsStore","toDbTarget","needsUpdate","getQueryData","fromDbTarget","addMatchingKeys","documentTargetStore","removeMatchingKeys","notifyGCForRemovedKeys","getMatchingKeysForTargetId","getStore$1","IndexedDbRemoteDocumentCache","addEntry","maybeDocument","remoteDocumentsStore","dbKey","toDbRemoteDocument","removeEntry","getEntry","dbRemoteDoc","fromDbRemoteDocument","getDocumentsMatchingQuery","LocalSerializer","remoteSerializer","remoteDoc","serializedMutations","dbTarget","queryProto","dbTimestamp","dbQuery","LOG_TAG$3","OWNER_LEASE_MAX_AGE_MS","OWNER_LEASE_REFRESH_INTERVAL_MS","ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX","EXISTING_OWNER_ERROR_MSG","UNSUPPORTED_PLATFORM_ERROR_MSG","IndexedDbPersistence","prefix","generateOwnerId","dbName","MAIN_DATABASE","localStoragePrefix","started","simpleDb","tryAcquireOwnerLease","scheduleOwnerLeaseRefreshes","attachWindowUnloadHook","persistenceError","shutdown","detachWindowUnloadHook","stopOwnerLeaseRefreshes","releaseOwnerLease","getMutationQueue","getQueryCache","getRemoteDocumentCache","operation","ensureOwnerLease","buildStoragePrefix","isDefaultDatabase","dbOwner","validOwner","newDbOwner","minAcceptable","maxAcceptable","getZombiedOwnerId","ownerLeaseRefreshHandle","setInterval","reason","clearInterval","windowUnloadHandler","setZombiedOwnerId","zombiedOwnerId","localStorage","getItem","zombiedOwnerLocalStorageKey","zombieOwnerId","removeItem","setItem","LocalDocumentsView","remoteDocumentCache","mutationQueue","getDocument","computeLocalDocument","getDocuments","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionQuery","queryResults","computeLocalDocuments","promisedResults","matchingMutationBatches","matchingKeys","matchingMutationBatches_1","mutatedDoc","RemoteDocumentChangeBuffer","assertChanges","bufferedEntry","LOG_TAG$4","persistence","initialUser","localViewReferences","heldBatchResults","remoteDocuments","queryCache","localDocuments","startMutationQueue","startQueryCache","oldBatches","promisedOldBatches","newBatches","changedKeys","_d","highestAck","ackedBatches","promisedBatch","changedDocuments","affected","shouldHoldBatchResult","documentBuffer_1","releaseBatchResults","promisedAffectedKeys","toReject","affectedKeys","promisedToReject","lastAcked","removeMutationBatch","documentBuffer","changedDocKeys","existingDoc","releasedWriteKeys","lastRemoteVersion","remoteVersion","releaseHeldBatchResults","promisedReleasedWriteKeys","viewChanges","viewChanges_1","nextMutationBatch","afterBatchId","readDocument","cached","documentBuffer_2","garbage","toRelease","isRemoteUpToVersion","batchResults","promiseChain","_loop_2","applyWriteToRemoteDocuments","batchResults_1","affectedDocs","batches_2","docKeys","ackVersion","MemoryMutationQueue","highestAcknowledgedBatchId","batchesByDocumentKey","batchIndex","indexOfExistingBatchId","findMutationBatch","rawIndex","indexOfBatchId","getAllLiveMutationBatchesBeforeIndex","endIndex","immediateChildrenPathLength","startPath","rowKeyPath","batchCount","firstBatchId","queueCount","startIndex","queueIndex","length_1","references","MemoryQueryCache","MemoryRemoteDocumentCache","LOG_TAG$5","MemoryPersistence","mutationQueues","queue","MemoryPersistenceTransaction","NoOpGarbageCollector","Deferred","TimerId","DelayedOperation","asyncQueue","timerId","targetTimeMs","removalCallback","deferred","createAndSchedule","delayMs","delayedOp","timerHandle","handleDelayElapsed","skipDelay","enqueue","AsyncQueue","tail","delayedOperations","operationInProgress","verifyNotFailed","newTail","enqueueAfterDelay","containsDelayedOperation","removeDelayedOperation","verifyOperationInProgress","drain","findIndex","runDelayedOperationsEarly","lastTimerId","All","LOG_TAG$6","ExponentialBackoff","initialDelayMs","backoffFactor","maxDelayMs","timerPromise","currentBaseMs","resetToMax","backoffAndRun","delayWithJitterMs","jitterDelayMs","LOG_TAG$7","PersistentStreamState","BACKOFF_INITIAL_DELAY_MS","BACKOFF_MAX_DELAY_MS","BACKOFF_FACTOR","IDLE_TIMEOUT_MS","PersistentStream","connectionTimerId","idleTimerId","connection","credentialsProvider","inactivityTimerPromise","stream","backoff","Initial","isStarted","Backoff","Auth","Open","isOpen","auth","performBackoff","stop","Stopped","inhibitBackoff","markIdle","handleIdleCloseTimer","sendRequest","cancelIdleCheck","finalState","tearDown","getToken","startStream","rpcError","handleStreamClose","dispatchIfStillActive","currentStream_1","startRpc","PersistentListenStream","credentials","ListenStreamConnectionBackoff","ListenStreamIdle","watchChangeProto","onWatchChange","watch","addTarget","labels","unwatch","removeTarget","PersistentWriteStream","WriteStreamConnectionBackoff","WriteStreamIdle","handshakeComplete_","writeMutations","responseProto","writeResults","commitTime","onMutationResult","onHandshakeComplete","writeHandshake","writes","Datastore","newPersistentWriteStream","newPersistentWatchStream","params","response","lookup","Transaction","datastore","readVersions","committed","recordVersion","docVersion","existingVersion","preconditionForUpdate","toMutations","unwritten","LOG_TAG$8","MAX_WATCH_STREAM_FAILURES","ONLINE_STATE_TIMEOUT_MS","OnlineStateTracker","onlineStateHandler","watchStreamFailures","onlineStateTimer","shouldWarnClientIsOffline","handleWatchStreamStart","setAndBroadcast","OnlineStateTimeout","logClientOfflineWarningIfNecessary","handleWatchStreamFailure","Online","clearOnlineStateTimer","newState","LOG_TAG$9","MAX_PENDING_WRITES","RemoteStore","pendingWrites","lastBatchSeen","accumulatedWatchChanges","watchStream","writeStream","onlineStateTracker","enableNetwork","isNetworkEnabled","shouldStartWatchStream","startWatchStream","disableNetwork","disableNetworkInternal","cleanUpWatchStreamState","cleanUpWriteStreamState","sendWatchRequest","sendUnwatchRequest","recordPendingTargetRequest","onWatchStreamOpen","onWatchStreamClose","onWatchStreamChange","handleTargetError","handleWatchChangeBatch","aggregator","deletedDoc","trackedRemote","newQueryData","requestQueryData","canWriteMutations","outstandingWrites","shouldStartWriteStream","startWriteStream","handshakeComplete","onWriteStreamOpen","onWriteStreamClose","onWriteHandshakeComplete","success","handleWriteError","handleHandshakeError","LOG_TAG$10","FirestoreClient","usePersistence","initializationDone","persistenceResult","initialized","setUserChangeListener","initializePersistence","initializeRest","startIndexedDbPersistence","canFallback","startMemoryPersistence","storagePrefix","eventMgr","removeUserChangeListener","observer","getDocumentFromLocalCache","getDocumentsFromLocalCache","AsyncObserver","muted","scheduleEvent","mute","eventHandler","User","otherUser","GOOGLE_CREDENTIALS","FIRST_PARTY","OAuthToken","Authorization","EmptyCredentialsProvider","userListener","forceRefresh","FirebaseCredentialsProvider","app","tokenListener","userCounter","newUser","getUser","addAuthTokenListener","initialUserCounter","tokenData","accessToken","removeAuthTokenListener","getUid","currentUid","FirstPartyToken","gapi","sessionIndex","X-Goog-AuthUser","FirstPartyCredentialsProvider","makeCredentialsProvider","client","isPartialObserver","implementsAnyMethods","methods","methods_1","method","FieldValueImpl","methodName","DeleteFieldValueImpl","serverTimestamp","ServerTimestampFieldValueImpl","PublicFieldValue","RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","UserDataSource","isWrite","dataSource","MergeSet","Update","QueryValue","ParseContext","arrayElement","validatePath","childContextForField","childPath","context","validatePathSegment","childContextForFieldPath","childContextForArray","createError","fieldDescription","DocumentKeyReference","UserDataConverter","preConverter","parseSetData","validatePlainObject","updateData","parseData","parseMergeData","parseUpdateData","fieldMaskPaths","fieldPathFromDotSeparatedString","childContext","runPreConverter","parsedValue","mask","parseUpdateVarargs","moreFieldsAndValues","fieldPathFromArgument","value_1","parseQueryValue","parsed","errorMessage","looksLikeJsonObject","parseObject","parseArray","parseSentinelFieldValue","parseScalarValue","entryIndex","array_1","entry","parsedEntry","DEFAULT_HOST","DEFAULT_SSL","DEFAULT_TIMESTAMPS_IN_SNAPSHOTS","FirestoreSettings","settings","FirestoreConfig","Firestore","databaseIdOrApp","_queue","_firestoreClient","config","firebaseApp","databaseIdFromApp","external_1","_config","_databaseId","settingsLiteral","newSettings","ensureClientConfigured","enablePersistence","configureClient","_dataConverter","DocumentReference","thisDb","otherDb","firestore","_key","collection","pathString","CollectionReference","forPath","Transaction$1","WriteBatch","level","_areTimestampsInSnapshotsEnabled","_firestore","_transaction","documentRef","validateReference","DocumentSnapshot","validateSetOptions","merge","fieldOrUpdateData","_mutations","_committed","verifyNotCommitted","onSnapshot","includeMetadataChanges","currArg","internalOptions","complete","onSnapshotInternal","errHandler","asyncObserver","internalListener","getViaSnapshotListener","SnapshotMetadata","_document","_fromCache","validateSnapshotOptions","convertObject","convertValue","convertArray","QueryDocumentSnapshot","Query$1","Query$$1","_query","opStr","validateNewFilter","directionStr","validateNewOrderBy","docOrField","boundFromDocOrFields","startAfter","endBefore","boundFromDocument","allFields","boundFromFields","components","rawValue","wrapped","QuerySnapshot","firestoreClient","existingField","validateOrderByAndInequalityMatch","inequality","_originalQuery","_snapshot","_cachedChanges","convertToDocumentImpl","changesFromSnapshot","parentPath","docRef","lastDoc_1","index_1","oldIndex","newIndex","indexTracker_1","resultChangeType","PublicFirestore","PublicTransaction","PublicWriteBatch","PublicDocumentReference","PublicDocumentSnapshot","PublicQueryDocumentSnapshot","PublicQuery","PublicQuerySnapshot","PublicCollectionReference","firestoreNamespace","configureForFirebase","firebase$$1","registerService","registerFirestore"],"mappings":"6CA8BA,IAAIA,yFACJ,SAAWA,GACPA,EAASA,EAAgB,MAAI,GAAK,QAClCA,EAASA,EAAkB,QAAI,GAAK,UACpCA,EAASA,EAAe,KAAI,GAAK,OACjCA,EAASA,EAAe,KAAI,GAAK,OACjCA,EAASA,EAAgB,MAAI,GAAK,QAClCA,EAASA,EAAiB,OAAI,GAAK,SANvC,CAOGA,WAAaA,cAIhB,IAAIC,gBAAkBD,SAASE,KAM3BC,kBAAoB,SAAUC,EAAUC,GAExC,IADA,IAAIC,KACKC,EAAK,EAAGA,EAAKC,UAAUC,OAAQF,IACpCD,EAAKC,EAAK,GAAKC,UAAUD,GAE7B,KAAIF,EAAUD,EAASM,UAAvB,CAEA,IAAIC,GAAM,IAAIC,MA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