/*! For license information please see LICENSES */ (window.webpackJsonp=window.webpackJsonp||[]).push([[10],{0:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(32),c=n(87),h=n(88),l=((r={})["no-app"]="No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()",r["bad-app-name"]="Illegal App name: '{$appName}",r["duplicate-app"]="Firebase App named '{$appName}' already exists",r["app-deleted"]="Firebase App named '{$appName}' already deleted",r["invalid-app-argument"]="firebase.{$appName}() takes either no argument or a Firebase App instance.",r),f=new c.ErrorFactory("app","Firebase",l),d="[DEFAULT]",y=[],m=function(){function t(t,e,n){this.firebase_=n,this.isDeleted_=!1,this.services_={},this.name_=e.name,this.automaticDataCollectionEnabled_=e.automaticDataCollectionEnabled||!1,this.options_=c.deepCopy(t),this.INTERNAL={getUid:function(){return null},getToken:function(){return Promise.resolve(null)},addAuthTokenListener:function(t){y.push(t),setTimeout((function(){return t(null)}),0)},removeAuthTokenListener:function(t){y=y.filter((function(e){return e!==t}))}}}return Object.defineProperty(t.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this.automaticDataCollectionEnabled_},set:function(t){this.checkDestroyed_(),this.automaticDataCollectionEnabled_=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!0,configurable:!0}),t.prototype.delete=function(){var t=this;return new Promise((function(e){t.checkDestroyed_(),e()})).then((function(){t.firebase_.INTERNAL.removeApp(t.name_);for(var e=[],n=0,r=Object.keys(t.services_);n=0&&_.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n ")}var E=function t(){var e=function(t){var e={},n={},r={},o={__esModule:!0,initializeApp:function(n,r){void 0===r&&(r={});if("object"!=typeof r||null===r){r={name:r}}var h=r;void 0===h.name&&(h.name=d);var l=h.name;if("string"!=typeof l||!l)throw f.create("bad-app-name",{appName:String(l)});if(c.contains(e,l))throw f.create("duplicate-app",{appName:l});var m=new t(n,h,o);return e[l]=m,y(m,"create"),m},app:h,apps:null,SDK_VERSION:v,INTERNAL:{registerService:function(e,d,y,m,v){void 0===v&&(v=!1);if(n[e])return _.debug("There were multiple attempts to register service "+e+"."),o[e];n[e]=d,m&&(r[e]=m,l().forEach((function(t){m("create",t)})));function w(t){if(void 0===t&&(t=h()),"function"!=typeof t[e])throw f.create("invalid-app-argument",{appName:e});return t[e]()}void 0!==y&&c.deepExtend(w,y);return o[e]=w,t.prototype[e]=function(){for(var t=[],n=0;n=0}},parentH:{type:Number,default:0,validator:function(t){return t>=0}},w:{type:Number,default:100,validator:function(t){return t>0}},h:{type:Number,default:100,validator:function(t){return t>0}},minw:{type:Number,default:50,validator:function(t){return t>0}},minh:{type:Number,default:50,validator:function(t){return t>0}},x:{type:Number,default:0,validator:function(t){return"number"==typeof t}},y:{type:Number,default:0,validator:function(t){return"number"==typeof t}},z:{type:[String,Number],default:"auto",validator:function(t){return"string"==typeof t?"auto"===t:t>=0}},dragHandle:{type:String,default:null},dragCancel:{type:String,default:null},sticks:{type:Array,default:function(){return["tl","tm","tr","mr","br","bm","bl","ml"]}},axis:{type:String,default:"both",validator:function(t){return-1!==["x","y","both","none"].indexOf(t)}}},data:function(){return{active:this.isActive,rawWidth:this.w,rawHeight:this.h,rawLeft:this.x,rawTop:this.y,rawRight:null,rawBottom:null,zIndex:this.z,aspectFactor:this.w/this.h,parentWidth:null,parentHeight:null,left:this.x,top:this.y,right:null,bottom:null,minWidth:this.minw,minHeight:this.minh}},created:function(){this.stickDrag=!1,this.bodyDrag=!1,this.stickAxis=null,this.stickStartPos={mouseX:0,mouseY:0,x:0,y:0,w:0,h:0},this.limits={minLeft:null,maxLeft:null,minRight:null,maxRight:null,minTop:null,maxTop:null,minBottom:null,maxBottom:null},this.currentStick=[]},mounted:function(){if(this.parentElement=this.$el.parentNode,this.parentWidth=this.parentW?this.parentW:this.parentElement.clientWidth,this.parentHeight=this.parentH?this.parentH:this.parentElement.clientHeight,this.rawRight=this.parentWidth-this.rawWidth-this.rawLeft,this.rawBottom=this.parentHeight-this.rawHeight-this.rawTop,document.documentElement.addEventListener("mousemove",this.move),document.documentElement.addEventListener("mouseup",this.up),document.documentElement.addEventListener("mouseleave",this.up),document.documentElement.addEventListener("mousedown",this.deselect),document.documentElement.addEventListener("touchmove",this.move,!0),document.documentElement.addEventListener("touchend touchcancel",this.up,!0),document.documentElement.addEventListener("touchstart",this.up,!0),this.dragHandle){var t=Array.prototype.slice.call(this.$el.querySelectorAll(this.dragHandle));for(var i in t)t[i].setAttribute("data-drag-handle",this._uid)}if(this.dragCancel){var e=Array.prototype.slice.call(this.$el.querySelectorAll(this.dragCancel));for(var n in e)e[n].setAttribute("data-drag-cancel",this._uid)}},beforeDestroy:function(){document.documentElement.removeEventListener("mousemove",this.move),document.documentElement.removeEventListener("mouseup",this.up),document.documentElement.removeEventListener("mouseleave",this.up),document.documentElement.removeEventListener("mousedown",this.deselect),document.documentElement.removeEventListener("touchmove",this.move,!0),document.documentElement.removeEventListener("touchend touchcancel",this.up,!0),document.documentElement.removeEventListener("touchstart",this.up,!0)},methods:{deselect:function(){this.preventActiveBehavior||(this.active=!1)},move:function(t){(this.stickDrag||this.bodyDrag)&&(t.stopPropagation(),this.stickDrag&&this.stickMove(t),this.bodyDrag&&this.bodyMove(t))},up:function(t){this.stickDrag&&this.stickUp(t),this.bodyDrag&&this.bodyUp(t)},bodyDown:function(t){var i=t.target||t.srcElement;this.preventActiveBehavior||(this.active=!0),t.button&&0!==t.button||(this.$emit("clicked",t),this.isDraggable&&this.active&&(this.dragHandle&&i.getAttribute("data-drag-handle")!==this._uid.toString()||this.dragCancel&&i.getAttribute("data-drag-cancel")===this._uid.toString()||(this.bodyDrag=!0,this.stickStartPos.mouseX=t.pageX||t.touches[0].pageX,this.stickStartPos.mouseY=t.pageY||t.touches[0].pageY,this.stickStartPos.left=this.left,this.stickStartPos.right=this.right,this.stickStartPos.top=this.top,this.stickStartPos.bottom=this.bottom,this.parentLimitation&&(this.limits=this.calcDragLimitation()))))},calcDragLimitation:function(){var t=this.parentWidth,i=this.parentHeight;return{minLeft:0,maxLeft:t-this.width,minRight:0,maxRight:t-this.width,minTop:0,maxTop:i-this.height,minBottom:0,maxBottom:i-this.height}},bodyMove:function(t){var i=this.stickStartPos,e=("y"!==this.axis&&"none"!==this.axis?i.mouseX-(t.pageX||t.touches[0].pageX):0)/this.parentScaleX,n=("x"!==this.axis&&"none"!==this.axis?i.mouseY-(t.pageY||t.touches[0].pageY):0)/this.parentScaleY;this.rawTop=i.top-n,this.rawBottom=i.bottom+n,this.rawLeft=i.left-e,this.rawRight=i.right+e,this.$emit("dragging",this.rect)},bodyUp:function(){this.bodyDrag=!1,this.$emit("dragging",this.rect),this.$emit("dragstop",this.rect),this.stickStartPos={mouseX:0,mouseY:0,x:0,y:0,w:0,h:0},this.limits={minLeft:null,maxLeft:null,minRight:null,maxRight:null,minTop:null,maxTop:null,minBottom:null,maxBottom:null}},stickDown:function(t,i){if(this.isResizable&&this.active){switch(this.stickDrag=!0,this.stickStartPos.mouseX=i.pageX||i.touches[0].pageX,this.stickStartPos.mouseY=i.pageY||i.touches[0].pageY,this.stickStartPos.left=this.left,this.stickStartPos.right=this.right,this.stickStartPos.top=this.top,this.stickStartPos.bottom=this.bottom,this.currentStick=t.split(""),this.stickAxis=null,this.currentStick[0]){case"b":case"t":this.stickAxis="y"}switch(this.currentStick[1]){case"r":case"l":this.stickAxis="y"===this.stickAxis?"xy":"x"}this.limits=this.calcResizeLimitation()}},calcResizeLimitation:function(){var t=this.minWidth,i=this.minHeight,e=this.aspectFactor,n=this.width,r=this.height,s=this.bottom,o=this.top,a=this.left,c=this.right,h=this.stickAxis,u=this.parentLimitation?0:null;this.aspectRatio&&(t/i>e?i=t/e:t=e*i);var l={minLeft:u,maxLeft:a+(n-t),minRight:u,maxRight:c+(n-t),minTop:u,maxTop:o+(r-i),minBottom:u,maxBottom:s+(r-i)};if(this.aspectRatio){var f={minLeft:a-Math.min(o,s)*e*2,maxLeft:a+(r-i)/2*e*2,minRight:c-Math.min(o,s)*e*2,maxRight:c+(r-i)/2*e*2,minTop:o-Math.min(a,c)/e*2,maxTop:o+(n-t)/2/e*2,minBottom:s-Math.min(a,c)/e*2,maxBottom:s+(n-t)/2/e*2};"x"===h?l={minLeft:Math.max(l.minLeft,f.minLeft),maxLeft:Math.min(l.maxLeft,f.maxLeft),minRight:Math.max(l.minRight,f.minRight),maxRight:Math.min(l.maxRight,f.maxRight)}:"y"===h&&(l={minTop:Math.max(l.minTop,f.minTop),maxTop:Math.min(l.maxTop,f.maxTop),minBottom:Math.max(l.minBottom,f.minBottom),maxBottom:Math.min(l.maxBottom,f.maxBottom)})}return l},stickMove:function(t){var i=this.stickStartPos,e=(i.mouseX-(t.pageX||t.touches[0].pageX))/this.parentScaleX,n=(i.mouseY-(t.pageY||t.touches[0].pageY))/this.parentScaleY;switch(this.currentStick[0]){case"b":this.rawBottom=i.bottom+n;break;case"t":this.rawTop=i.top-n}switch(this.currentStick[1]){case"r":this.rawRight=i.right+e;break;case"l":this.rawLeft=i.left-e}this.$emit("resizing",this.rect)},stickUp:function(){this.stickDrag=!1,this.stickStartPos={mouseX:0,mouseY:0,x:0,y:0,w:0,h:0},this.limits={minLeft:null,maxLeft:null,minRight:null,maxRight:null,minTop:null,maxTop:null,minBottom:null,maxBottom:null},this.rawTop=this.top,this.rawBottom=this.bottom,this.rawLeft=this.left,this.rawRight=this.right,this.stickAxis=null,this.$emit("resizing",this.rect),this.$emit("resizestop",this.rect)},aspectRatioCorrection:function(){if(this.aspectRatio){var t=this.bottom,i=this.top,e=this.left,n=this.right,r=this.width,s=this.height,o=this.aspectFactor,a=this.currentStick;if(r/s>o){var c=o*s;"l"===a[1]?this.left=e+r-c:this.right=n+r-c}else{var h=r/o;"t"===a[0]?this.top=i+s-h:this.bottom=t+s-h}}}},computed:{style:function(){return{top:this.top+"px",left:this.left+"px",width:this.width+"px",height:this.height+"px",zIndex:this.zIndex}},vdrStick:function(){var t=this;return function(i){var e={width:8/t.parentScaleX+"px",height:8/t.parentScaleY+"px"};return e[n[i[0]]]=8/t.parentScaleX/-2+"px",e[r[i[1]]]=8/t.parentScaleX/-2+"px",e}},width:function(){return this.parentWidth-this.left-this.right},height:function(){return this.parentHeight-this.top-this.bottom},rect:function(){return{left:Math.round(this.left),top:Math.round(this.top),width:Math.round(this.width),height:Math.round(this.height)}}},watch:{rawLeft:function(t){var i=this.limits,e=this.stickAxis,n=this.aspectFactor,r=this.aspectRatio,s=this.left,o=this.bottom,a=this.top;if(null!==i.minLeft&&t=0||"auto"===t)&&(this.zIndex=t)},aspectRatio:function(t){t&&(this.aspectFactor=this.width/this.height)},minw:function(t){t>0&&t<=this.width&&(this.minWidth=t)},minh:function(t){t>0&&t<=this.height&&(this.minHeight=t)},x:function(){if(!this.stickDrag&&!this.bodyDrag){this.parentLimitation&&(this.limits=this.calcDragLimitation());var t=this.x-this.left;this.rawLeft=this.x,this.rawRight=this.right-t}},y:function(){if(!this.stickDrag&&!this.bodyDrag){this.parentLimitation&&(this.limits=this.calcDragLimitation());var t=this.y-this.top;this.rawTop=this.y,this.rawBottom=this.bottom-t}},w:function(){if(!this.stickDrag&&!this.bodyDrag){this.currentStick=["m","r"],this.stickAxis="x",this.parentLimitation&&(this.limits=this.calcResizeLimitation());var t=this.width-this.w;this.rawRight=this.right+t}},h:function(){if(!this.stickDrag&&!this.bodyDrag){this.currentStick=["b","m"],this.stickAxis="y",this.parentLimitation&&(this.limits=this.calcResizeLimitation());var t=this.height-this.h;this.rawBottom=this.bottom+t}},parentW:function(t){this.right=t-this.width-this.left,this.parentWidth=t},parentH:function(t){this.bottom=t-this.height-this.top,this.parentHeight=t}}}},15:function(t,i){t.exports=function(t){var i="undefined"!=typeof window&&window.location;if(!i)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var e=i.protocol+"//"+i.host,n=e+i.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,(function(t,i){var s,r=i.trim().replace(/^"(.*)"$/,(function(t,i){return i})).replace(/^'(.*)'$/,(function(t,i){return i}));return/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(r)?t:(s=0===r.indexOf("//")?r:0===r.indexOf("/")?e+r:n+r.replace(/^\.\//,""),"url("+JSON.stringify(s)+")")}))}},16:function(t,i,e){(t.exports=e(6)(!1)).push([t.i,'\n.vdr,.vdr.active:before{position:absolute;-webkit-box-sizing:border-box;box-sizing:border-box\n}\n.vdr.active:before{content:"";width:100%;height:100%;top:0;left:0;outline:1px dashed #d6d6d6\n}\n.vdr-stick{-webkit-box-sizing:border-box;box-sizing:border-box;position:absolute;font-size:1px;background:#fff;border:1px solid #6c6c6c;-webkit-box-shadow:0 0 2px #bbb;box-shadow:0 0 2px #bbb\n}\n.inactive .vdr-stick{display:none\n}\n.vdr-stick-br,.vdr-stick-tl{cursor:nwse-resize\n}\n.vdr-stick-bm,.vdr-stick-tm{left:50%;cursor:ns-resize\n}\n.vdr-stick-bl,.vdr-stick-tr{cursor:nesw-resize\n}\n.vdr-stick-ml,.vdr-stick-mr{top:50%;cursor:ew-resize\n}\n.vdr-stick.not-resizable{display:none\n}',""])},17:function(t,i,e){"use strict";var n=e(0);e.n(n).a},18:function(t,i,e){"use strict";e.r(i);var n=e(4),r=e(2);for(var s in r)"default"!==s&&function(t){e.d(i,t,(function(){return r[t]}))}(s);var o=(e(17),e(3)),a=Object(o.a)(r.default,n.a,n.b,!1,null,null,null);a.options.__file="src/components/vue-drag-resize.vue",i.default=a.exports},2:function(t,i,e){"use strict";e.r(i);var n=e(1),r=e.n(n);for(var s in n)"default"!==s&&function(t){e.d(i,t,(function(){return n[t]}))}(s);i.default=r.a},3:function(t,i,e){"use strict";function n(t,i,e,n,r,s,o,a){var c,h="function"==typeof t?t.options:t;if(i&&(h.render=i,h.staticRenderFns=e,h._compiled=!0),n&&(h.functional=!0),s&&(h._scopeId="data-v-"+s),o?(c=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(o)},h._ssrRegister=c):r&&(c=a?function(){r.call(this,this.$root.$options.shadowRoot)}:r),c)if(h.functional){h._injectStyles=c;var u=h.render;h.render=function(t,i){return c.call(i),u(t,i)}}else{var l=h.beforeCreate;h.beforeCreate=l?[].concat(l,c):[c]}return{exports:t,options:h}}e.d(i,"a",(function(){return n}))},4:function(t,i,e){"use strict";var n=function(){var t=this,i=t.$createElement,e=t._self._c||i;return e("div",{staticClass:"vdr",class:t.active||t.isActive?"active":"inactive",style:t.style,on:{mousedown:function(i){i.stopPropagation(),i.preventDefault(),t.bodyDown(i)},touchstart:function(i){i.stopPropagation(),i.preventDefault(),t.bodyDown(i)}}},[t._t("default"),t._v(" "),t._l(t.sticks,(function(i){return e("div",{staticClass:"vdr-stick",class:["vdr-stick-"+i,t.isResizable?"":"not-resizable"],style:t.vdrStick(i),on:{mousedown:function(e){e.stopPropagation(),e.preventDefault(),t.stickDown(i,e)},touchstart:function(e){e.stopPropagation(),e.preventDefault(),t.stickDown(i,e)}}})}))],2)},r=[];n._withStripped=!0,e.d(i,"a",(function(){return n})),e.d(i,"b",(function(){return r}))},44:function(t,i,e){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=e(18);Object.defineProperty(i,"default",{enumerable:!0,get:function(){return function(t){return t&&t.__esModule?t:{default:t}}(n).default}})},5:function(t,i,e){function n(t,i){for(var e=0;e=0&&v.splice(i,1)}function a(t){var i=document.createElement("style");return t.attrs.type="text/css",h(i,t.attrs),s(t,i),i}function c(t){var i=document.createElement("link");return t.attrs.type="text/css",t.attrs.rel="stylesheet",h(i,t.attrs),s(t,i),i}function h(t,i){Object.keys(i).forEach((function(e){t.setAttribute(e,i[e])}))}function u(t,i){var e,n,r,s;if(i.transform&&t.css){if(!(s=i.transform(t.css)))return function(){};t.css=s}if(i.singleton){var h=b++;e=g||(g=a(i)),n=l.bind(null,e,h,!1),r=l.bind(null,e,h,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(e=c(i),n=d.bind(null,e,i),r=function(){o(e),e.href&&URL.revokeObjectURL(e.href)}):(e=a(i),n=f.bind(null,e),r=function(){o(e)});return n(t),function(i){if(i){if(i.css===t.css&&i.media===t.media&&i.sourceMap===t.sourceMap)return;n(t=i)}else r()}}function l(t,i,e,n){var r=e?"":n.css;if(t.styleSheet)t.styleSheet.cssText=w(i,r);else{var s=document.createTextNode(r),o=t.childNodes;o[i]&&t.removeChild(o[i]),o.length?t.insertBefore(s,o[i]):t.appendChild(s)}}function f(t,i){var e=i.css,n=i.media;if(n&&t.setAttribute("media",n),t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}function d(t,i,e){var n=e.css,r=e.sourceMap,s=void 0===i.convertToAbsoluteUrls&&r;(i.convertToAbsoluteUrls||s)&&(n=_(n)),r&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var o=new Blob([n],{type:"text/css"}),a=t.href;t.href=URL.createObjectURL(o),a&&URL.revokeObjectURL(a)}var p={},y=function(t){var i;return function(){return void 0===i&&(i=t.apply(this,arguments)),i}}((function(){return window&&document&&document.all&&!window.atob})),m=function(t){var i={};return function(e){return void 0===i[e]&&(i[e]=t.call(this,e)),i[e]}}((function(t){return document.querySelector(t)})),g=null,b=0,v=[],_=e(15);t.exports=function(t,i){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");(i=i||{}).attrs="object"==typeof i.attrs?i.attrs:{},i.singleton||(i.singleton=y()),i.insertInto||(i.insertInto="head"),i.insertAt||(i.insertAt="bottom");var e=r(t,i);return n(e,i),function(t){for(var s=[],o=0;o=0||(n[e]=source[e]);return n}(source,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,e)&&(n[e]=source[e])}return n}n.d(e,"a",(function(){return r}))},16:function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t){return(o="function"==typeof Symbol&&"symbol"===r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)})(t)}n.d(e,"a",(function(){return o}))},163:function(t,e,n){"use strict";t.exports=function(t,e){return"string"!=typeof(t=t.__esModule?t.default:t)?t:(/^['"].*['"]$/.test(t)&&(t=t.slice(1,-1)),/["'() \t\n]/.test(t)||e?'"'.concat(t.replace(/"/g,'\\"').replace(/\n/g,"\\n"),'"'):t)}},190:function(t,e,n){"use strict";n(191)},191:function(t,e,n){"use strict";(function(t){Object.defineProperty(e,"__esModule",{value:!0});var r,o,c=(r=n(0))&&"object"==typeof r&&"default"in r?r.default:r,h=n(88),l=n(32),f=n(87),d=n(192),y=c.SDK_VERSION,m=new h.Logger("@firebase/firestore");function v(){return m.logLevel===h.LogLevel.DEBUG?o.DEBUG:m.logLevel===h.LogLevel.SILENT?o.SILENT:o.ERROR}function _(t){switch(t){case o.DEBUG:m.logLevel=h.LogLevel.DEBUG;break;case o.ERROR:m.logLevel=h.LogLevel.ERROR;break;case o.SILENT:m.logLevel=h.LogLevel.SILENT;break;default:m.error("Firestore ("+y+"): Invalid value passed to `setLogLevel`")}}function w(t,e){for(var n=[],r=2;rr)throw new D(A.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+et(e.length,"argument")+".")}function B(t,e,n,r){z(t,e,tt(n)+" argument",r)}function j(t,e,n,r){void 0!==r&&B(t,e,n,r)}function W(t,e,n,r){z(t,e,n+" option",r)}function Q(t,e,n,r){void 0!==r&&W(t,e,n,r)}function K(t,e,n,r,o){void 0!==r&&function(t,e,n,r,o){if(!(r instanceof Array))throw new D(A.INVALID_ARGUMENT,"Function "+t+"() requires its "+e+" option to be an array, but it was: "+X(r));for(var i=0;i20&&(input=input.substring(0,20)+"..."),JSON.stringify(input);if("number"==typeof input||"boolean"==typeof input)return""+input;if("object"==typeof input){if(input instanceof Array)return"an array";var t=function(input){if(input.constructor){var t=/function\s+([^\s(]+)\s*\(/.exec(input.constructor.toString());if(t&&t.length>1)return t[1]}return null}(input);return t?"a custom "+t+" object":"an object"}return"function"==typeof input?"a function":S("Unknown wrong type: "+typeof input)}function J(t,e,n){if(void 0===n)throw new D(A.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+tt(e)+" argument, but it was undefined.")}function $(t,e,n){x(e,(function(e,r){if(n.indexOf(e)<0)throw new D(A.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))}))}function Z(t,e,n,r){var o=X(r);return new D(A.INVALID_ARGUMENT,"Function "+t+"() requires its "+tt(n)+" argument to be a "+e+", but it was: "+o)}function tt(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function et(t,e){return t+" "+e+(1===t?"":"s")}var nt=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",i=0;i<20;i++)e+=t.charAt(Math.floor(Math.random()*t.length));return C(20===e.length,"Invalid auto ID: "+e),e},t}();function it(t,e){return te?1:0}function ot(t,e){if(t.length!==e.length)return!1;for(var i=0;it.length&&S("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&S("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n}return Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach((function(t){n.push(t)})):n.push(e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,C(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return C(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return C(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return this.get(this.length-1)},t.prototype.get=function(t){return C(to)return 1}return t.lengthe.length?1:0},t}(),vt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.construct=function(t,n,r){return new e(t,n,r)},e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(path){if(path.indexOf("//")>=0)throw new D(A.INVALID_ARGUMENT,"Invalid path ("+path+"). Paths must not contain // in them.");return new e(path.split("/").filter((function(t){return t.length>0})))},e.EMPTY_PATH=new e([]),e}(gt),bt=/^[_a-zA-Z][_a-zA-Z0-9]*$/,_t=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.construct=function(t,n,r){return new e(t,n,r)},e.isValidIdentifier=function(t){return bt.test(t)},e.prototype.canonicalString=function(){return this.toArray().map((function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t})).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(path){for(var t=[],n="",i=0,r=function(){if(0===n.length)throw new D(A.INVALID_ARGUMENT,"Invalid field path ("+path+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");t.push(n),n=""},o=!1;i=2&&this.path.get(this.path.length-2)===t},t.prototype.isEqual=function(t){return null!==t&&0===vt.comparator(this.path,t.path)},t.prototype.toString=function(){return this.path.toString()},t.comparator=function(t,e){return vt.comparator(t.path,e.path)},t.isDocumentKey=function(path){return path.length%2==0},t.fromSegments=function(e){return new t(new vt(e.slice()))},t.fromPathString=function(path){return new t(vt.fromString(path))},t.EMPTY=new t(new vt([])),t}(),Et=function(){var t=this;this.promise=new Promise((function(e,n){t.resolve=e,t.reject=n}))};!function(t){t.All="all",t.ListenStreamIdle="listen_stream_idle",t.ListenStreamConnectionBackoff="listen_stream_connection_backoff",t.WriteStreamIdle="write_stream_idle",t.WriteStreamConnectionBackoff="write_stream_connection_backoff",t.OnlineStateTimeout="online_state_timeout",t.ClientMetadataRefresh="client_metadata_refresh",t.LruGarbageCollection="lru_garbage_collection",t.RetryTransaction="retry_transaction"}(ct||(ct={}));var Tt=function(){function t(t,e,n,r,o){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=r,this.removalCallback=o,this.deferred=new Et,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.catch=this.deferred.promise.catch.bind(this.deferred.promise),this.deferred.promise.catch((function(t){}))}return t.createAndSchedule=function(e,n,r,o,c){var h=new t(e,n,Date.now()+r,o,c);return h.start(r),h},t.prototype.start=function(t){var e=this;this.timerHandle=setTimeout((function(){return e.handleDelayElapsed()}),t)},t.prototype.skipDelay=function(){return this.handleDelayElapsed()},t.prototype.cancel=function(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new D(A.CANCELLED,"Operation cancelled"+(t?": "+t:""))))},t.prototype.handleDelayElapsed=function(){var t=this;this.asyncQueue.enqueueAndForget((function(){return null!==t.timerHandle?(t.clearTimeout(),t.op().then((function(e){return t.deferred.resolve(e)}))):Promise.resolve()}))},t.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},t}(),St=function(){function t(){this.tail=Promise.resolve(),this._isShuttingDown=!1,this.delayedOperations=[],this.failure=null,this.operationInProgress=!1,this.timerIdsToSkip=[]}return Object.defineProperty(t.prototype,"isShuttingDown",{get:function(){return this._isShuttingDown},enumerable:!0,configurable:!0}),t.prototype.enqueueAndForget=function(t){this.enqueue(t)},t.prototype.enqueueAndForgetEvenAfterShutdown=function(t){this.verifyNotFailed(),this.enqueueInternal(t)},t.prototype.enqueueEvenAfterShutdown=function(t){return this.verifyNotFailed(),this.enqueueInternal(t)},t.prototype.enqueueAndInitiateShutdown=function(t){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(e){switch(e.label){case 0:return this.verifyNotFailed(),this._isShuttingDown?[3,2]:(this._isShuttingDown=!0,[4,this.enqueueEvenAfterShutdown(t)]);case 1:e.sent(),e.label=2;case 2:return[2]}}))}))},t.prototype.enqueue=function(t){return this.verifyNotFailed(),this._isShuttingDown?new Promise((function(t){})):this.enqueueInternal(t)},t.prototype.enqueueInternal=function(t){var e=this,n=this.tail.then((function(){return e.operationInProgress=!0,t().catch((function(t){e.failure=t,e.operationInProgress=!1;var n=t.stack||t.message||"";throw E("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout((function(){throw t}),0),t})).then((function(t){return e.operationInProgress=!1,t}))}));return this.tail=n,n},t.prototype.enqueueAfterDelay=function(t,e,n){var r=this;this.verifyNotFailed(),C(e>=0,"Attempted to schedule an operation with a negative delay of "+e),this.timerIdsToSkip.indexOf(t)>-1&&(e=0);var o=Tt.createAndSchedule(this,t,e,n,(function(t){return r.removeDelayedOperation(t)}));return this.delayedOperations.push(o),o},t.prototype.verifyNotFailed=function(){this.failure&&S("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},t.prototype.verifyOperationInProgress=function(){C(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return this.enqueueEvenAfterShutdown((function(){return Promise.resolve()}))},t.prototype.containsDelayedOperation=function(t){for(var e=0,n=this.delayedOperations;e=0,"Delayed operation not found."),this.delayedOperations.splice(e,1)},t}(),Ct="",It="",Nt="",At="";function Dt(path){for(var t="",i=0;i0&&(t=Rt(t)),t=kt(path.get(i),t);return Rt(t)}function kt(t,e){for(var n=e,r=t.length,i=0;i=2,"Invalid path "+path),2===t)return C(path.charAt(0)===Ct&&path.charAt(1)===It,"Non-empty path "+path+" had length 2"),vt.EMPTY_PATH;for(var e=t-2,n=[],r="",o=0;oe)&&S('Invalid encoded resource path: "'+path+'"'),path.charAt(c+1)){case It:var h=path.substring(o,c),l=void 0;0===r.length?l=h:(l=r+=h,r=""),n.push(l);break;case Nt:r+=path.substring(o,c),r+="\0";break;case At:r+=path.substring(o,c+1);break;default:S('Invalid encoded resource path: "'+path+'"')}o=c+2}return new vt(n)}var Pt=function(){function t(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new D(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new D(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new D(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new D(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}return t.now=function(){return t.fromMillis(Date.now())},t.fromDate=function(e){return t.fromMillis(e.getTime())},t.fromMillis=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.prototype.toDate=function(){return new Date(this.toMillis())},t.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6},t.prototype._compareTo=function(t){return this.seconds===t.seconds?it(this.nanoseconds,t.nanoseconds):it(this.seconds,t.seconds)},t.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"},t}(),xt=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new Pt(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp._compareTo(t.timestamp)},t.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp.toString()+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new Pt(0,0)),t}(),Lt=function(){function t(t,e){this.comparator=t,this.root=e||Ft.EMPTY}return t.prototype.insert=function(e,n){return new t(this.comparator,this.root.insert(e,n,this.comparator).copy(null,null,Ft.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Ft.BLACK,null,null))},t.prototype.get=function(t){for(var e=this.root;!e.isEmpty();){var n=this.comparator(t,e.key);if(0===n)return e.value;n<0?e=e.left:n>0&&(e=e.right)}return null},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal((function(e,n){return t(e,n),!1}))},t.prototype.toString=function(){var t=[];return this.inorderTraversal((function(e,n){return t.push(e+":"+n),!1})),"{"+t.join(", ")+"}"},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(){return new Mt(this.root,null,this.comparator,!1)},t.prototype.getIteratorFrom=function(t){return new Mt(this.root,t,this.comparator,!1)},t.prototype.getReverseIterator=function(){return new Mt(this.root,null,this.comparator,!0)},t.prototype.getReverseIteratorFrom=function(t){return new Mt(this.root,t,this.comparator,!0)},t}(),Mt=function(){function t(t,e,n,r){this.isReverse=r,this.nodeStack=[];for(var o=1;!t.isEmpty();)if(o=e?n(t.key,e):1,r&&(o*=-1),o<0)t=this.isReverse?t.left:t.right;else{if(0===o){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){C(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t=this.nodeStack.pop(),e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}},t}(),Ft=function(){function t(e,n,r,o,c){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=o?o:t.EMPTY,this.right=null!=c?c:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,o,c){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=o?o:this.left,null!=c?c:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,o=n(t,r.key);return(r=o<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===o?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n))).fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()},t.prototype.remove=function(e,n){var r,o=this;if(n(e,o.key)<0)o.left.isEmpty()||o.left.isRed()||o.left.left.isRed()||(o=o.moveRedLeft()),o=o.copy(null,null,null,o.left.remove(e,n),null);else{if(o.left.isRed()&&(o=o.rotateRight()),o.right.isEmpty()||o.right.isRed()||o.right.left.isRed()||(o=o.moveRedRight()),0===n(e,o.key)){if(o.right.isEmpty())return t.EMPTY;r=o.right.min(),o=o.copy(r.key,r.value,null,null,o.right.removeMin())}o=o.copy(null,null,null,null,o.right.remove(e,n))}return o.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight())).rotateLeft()).colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=(t=t.rotateRight()).colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw S("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw S("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw S("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),Ut=function(){function t(){this.size=0}return Object.defineProperty(t.prototype,"key",{get:function(){throw S("LLRBEmptyNode has no key.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){throw S("LLRBEmptyNode has no value.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){throw S("LLRBEmptyNode has no color.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"left",{get:function(){throw S("LLRBEmptyNode has no left child.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){throw S("LLRBEmptyNode has no right child.")},enumerable:!0,configurable:!0}),t.prototype.copy=function(t,e,n,r,o){return this},t.prototype.insert=function(t,e,n){return new Ft(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();Ft.EMPTY=new Ut;var qt=function(){function t(t){this.comparator=t,this.data=new Lt(this.comparator)}return t.fromMapKeys=function(map){var e=new t(map.comparator);return map.forEach((function(t){e=e.add(t)})),e},t.prototype.has=function(t){return null!==this.data.get(t)},t.prototype.first=function(){return this.data.minKey()},t.prototype.last=function(){return this.data.maxKey()},Object.defineProperty(t.prototype,"size",{get:function(){return this.data.size},enumerable:!0,configurable:!0}),t.prototype.indexOf=function(t){return this.data.indexOf(t)},t.prototype.forEach=function(t){this.data.inorderTraversal((function(e,n){return t(e),!1}))},t.prototype.forEachInRange=function(t,e){for(var n=this.data.getIteratorFrom(t[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,t[1])>=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();){if(!t(n.getNext().key))return}},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.getIterator=function(){return new Vt(this.data.getIterator())},t.prototype.getIteratorFrom=function(t){return new Vt(this.data.getIteratorFrom(t))},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach((function(t){e=e.add(t)})),e},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var o=n.getNext().key,c=r.getNext().key;if(0!==this.comparator(o,c))return!1}return!0},t.prototype.toArray=function(){var t=[];return this.forEach((function(e){t.push(e)})),t},t.prototype.toString=function(){var t=[];return this.forEach((function(e){return t.push(e)})),"SortedSet("+t.toString()+")"},t.prototype.copy=function(data){var e=new t(this.comparator);return e.data=data,e},t}(),Vt=function(){function t(t){this.iter=t}return t.prototype.getNext=function(){return this.iter.getNext().key},t.prototype.hasNext=function(){return this.iter.hasNext()},t}(),Bt=new Lt(wt.comparator);function jt(){return Bt}function Wt(){return jt()}var Qt=new Lt(wt.comparator);function Kt(){return Qt}var Ht=new Lt(wt.comparator);function Gt(){return Ht}var zt=new qt(wt.comparator);function Yt(){for(var t=[],e=0;e0,"Cannot create an empty mutation batch")}return t.prototype.applyToRemoteDocument=function(t,e,n){e&&C(e.key.isEqual(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n "+e.key);var r=n.mutationResults;C(r.length===this.mutations.length,"Mismatch between mutations length\n ("+this.mutations.length+") and mutation results length\n ("+r.length+").");for(var i=0;i=r,"Should have found mutation after "+r),c=n.serializer.fromDbMutationBatch(e)),o.done()})).next((function(){return c}))},t.prototype.getHighestUnacknowledgedBatchId=function(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=-1;return oe(t).iterate({index:bn.userMutationsIndex,range:e,reverse:!0},(function(t,e,r){n=e.batchId,r.done()})).next((function(){return n}))},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return oe(t).loadAll(bn.userMutationsIndex,n).next((function(t){return t.map((function(t){return e.serializer.fromDbMutationBatch(t)}))}))},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=_n.prefixForPath(this.userId,e.path),o=IDBKeyRange.lowerBound(r),c=[];return ae(t).iterate({range:o},(function(r,o,h){var l=r[0],f=r[1],d=r[2],path=Ot(f);if(l===n.userId&&e.path.isEqual(path))return oe(t).get(d).next((function(t){if(!t)throw S("Dangling document-mutation reference found: "+r+" which points to "+d);C(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+d),c.push(n.serializer.fromDbMutationBatch(t))}));h.done()})).next((function(){return c}))},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new qt(it),o=[];return e.forEach((function(e){var c=_n.prefixForPath(n.userId,e.path),h=IDBKeyRange.lowerBound(c),l=ae(t).iterate({range:h},(function(t,o,c){var h=t[0],l=t[1],f=t[2],path=Ot(l);h===n.userId&&e.path.isEqual(path)?r=r.add(f):c.done()}));o.push(l)})),te.waitFor(o).next((function(){return n.lookupMutationBatches(t,r)}))},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;C(!e.isDocumentQuery(),"Document queries shouldn't go down this path"),C(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var r=e.path,o=r.length+1,c=_n.prefixForPath(this.userId,r),h=IDBKeyRange.lowerBound(c),l=new qt(it);return ae(t).iterate({range:h},(function(t,e,c){var h=t[0],f=t[1],d=t[2],path=Ot(f);h===n.userId&&r.isPrefixOf(path)?path.length===o&&(l=l.add(d)):c.done()})).next((function(){return n.lookupMutationBatches(t,l)}))},t.prototype.lookupMutationBatches=function(t,e){var n=this,r=[],o=[];return e.forEach((function(e){o.push(oe(t).get(e).next((function(t){if(null===t)throw S("Dangling document-mutation reference found, which points to "+e);C(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.fromDbMutationBatch(t))})))})),te.waitFor(o).next((function(){return r}))},t.prototype.removeMutationBatch=function(t,e){var n=this;return re(t.simpleDbTransaction,this.userId,e).next((function(r){return n.removeCachedMutationKeys(e.batchId),te.forEach(r,(function(e){return n.referenceDelegate.removeMutationReference(t,e)}))}))},t.prototype.removeCachedMutationKeys=function(t){delete this.documentKeysByBatchId[t]},t.prototype.performConsistencyCheck=function(t){var e=this;return this.checkEmpty(t).next((function(n){if(!n)return te.resolve();var r=IDBKeyRange.lowerBound(_n.prefixForUser(e.userId)),o=[];return ae(t).iterate({range:r},(function(t,n,r){if(t[0]===e.userId){var path=Ot(t[1]);o.push(path)}else r.done()})).next((function(){C(0===o.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+o.map((function(p){return p.canonicalString()})))}))}))},t.prototype.containsKey=function(t,e){return ne(t,this.userId,e)},t.prototype.getMutationQueueMetadata=function(t){var e=this;return se(t).get(this.userId).next((function(t){return t||new vn(e.userId,-1,"")}))},t}();function ne(t,e,n){var r=_n.prefixForPath(e,n.path),o=r[1],c=IDBKeyRange.lowerBound(r),h=!1;return ae(t).iterate({range:c,keysOnly:!0},(function(t,n,r){var c=t[0],l=t[1];t[2];c===e&&l===o&&(h=!0),r.done()})).next((function(){return h}))}function re(t,e,n){var r=t.store(bn.store),o=t.store(_n.store),c=[],h=IDBKeyRange.only(n.batchId),l=0,f=r.iterate({range:h},(function(t,e,n){return l++,n.delete()}));c.push(f.next((function(){C(1===l,"Dangling document-mutation reference found: Missing batch "+n.batchId)})));for(var d=[],y=0,m=n.mutations;y0||n.indexOf("Trident/")>0||n.indexOf("Edge/")>0||o||h)},e.getStore=function(t,e){return t.store(e)},e.getIOSVersion=function(t){var e=t.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=e?e[1].split("_").slice(0,2).join("."):"-1";return Number(n)},e.getAndroidVersion=function(t){var e=t.match(/Android ([\d.]+)/i),n=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(n)},e.prototype.setVersionChangeListener=function(t){this.db.onversionchange=function(e){return t(e)}},e.prototype.runTransaction=function(t,e,n){var r=de.open(this.db,t,e),o=n(r).catch((function(t){return r.abort(t),te.reject(t)})).toPromise();return o.catch((function(){})),r.completionPromise.then((function(){return o}))},e.prototype.close=function(){this.db.close()},e}(),pe=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return me(this.dbCursor.delete())},t}(),de=function(){function t(t){var e=this;this.transaction=t,this.aborted=!1,this.completionDeferred=new Et,this.transaction.oncomplete=function(){e.completionDeferred.resolve()},this.transaction.onabort=function(){t.error?e.completionDeferred.reject(t.error):e.completionDeferred.resolve()},this.transaction.onerror=function(t){var n=ve(t.target.error);e.completionDeferred.reject(n)}}return t.open=function(e,n,r){return new t(e.transaction(r,n))},Object.defineProperty(t.prototype,"completionPromise",{get:function(){return this.completionDeferred.promise},enumerable:!0,configurable:!0}),t.prototype.abort=function(t){t&&this.completionDeferred.reject(t),this.aborted||(w(le,"Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return C(!!e,"Object store not part of transaction: "+t),new ye(e)},t}(),ye=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(w(le,"PUT",this.store.name,t,e),n=this.store.put(e,t)):(w(le,"PUT",this.store.name,"",t),n=this.store.put(t)),me(n)},t.prototype.add=function(t){return w(le,"ADD",this.store.name,t,t),me(this.store.add(t))},t.prototype.get=function(t){var e=this;return me(this.store.get(t)).next((function(n){return void 0===n&&(n=null),w(le,"GET",e.store.name,t,n),n}))},t.prototype.delete=function(t){return w(le,"DELETE",this.store.name,t),me(this.store.delete(t))},t.prototype.count=function(){return w(le,"COUNT",this.store.name),me(this.store.count())},t.prototype.loadAll=function(t,e){var cursor=this.cursor(this.options(t,e)),n=[];return this.iterateCursor(cursor,(function(t,e){n.push(e)})).next((function(){return n}))},t.prototype.deleteAll=function(t,e){w(le,"DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var cursor=this.cursor(n);return this.iterateCursor(cursor,(function(t,e,n){return n.delete()}))},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var cursor=this.cursor(n);return this.iterateCursor(cursor,e)},t.prototype.iterateSerial=function(t){var e=this.cursor({});return new te((function(n,r){e.onerror=function(t){var e=ve(t.target.error);r(e)},e.onsuccess=function(e){var cursor=e.target.result;cursor?t(cursor.primaryKey,cursor.value).next((function(t){t?cursor.continue():n()})):n()}}))},t.prototype.iterateCursor=function(t,e){var n=[];return new te((function(r,o){t.onerror=function(t){o(t.target.error)},t.onsuccess=function(t){var cursor=t.target.result;if(cursor){var o=new pe(cursor),c=e(cursor.primaryKey,cursor.value,o);if(c instanceof te){var h=c.catch((function(t){return o.done(),te.reject(t)}));n.push(h)}o.isDone?r():null===o.skipToKey?cursor.continue():cursor.continue(o.skipToKey)}else r()}})).next((function(){return te.waitFor(n)}))},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(C(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}();function me(t){return new te((function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){var e=ve(t.target.error);n(e)}}))}var ge=!1;function ve(t){var e=fe.getIOSVersion(f.getUA());if(e>=12.2&&e<13){var n="An internal error was encountered in the Indexed Database server";if(t.message.indexOf(n)>=0){var r=new D("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '"+n+"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return ge||(ge=!0,setTimeout((function(){throw r}),0)),r}}return t}var be=function(){function t(t,e){this.referenceDelegate=t,this.serializer=e,this.targetIdGenerator=he.forQueryCache()}return t.prototype.allocateTargetId=function(t){var e=this;return this.retrieveMetadata(t).next((function(n){return n.highestTargetId=e.targetIdGenerator.after(n.highestTargetId),e.saveMetadata(t,n).next((function(){return n.highestTargetId}))}))},t.prototype.getLastRemoteSnapshotVersion=function(t){return this.retrieveMetadata(t).next((function(t){return xt.fromTimestamp(new Pt(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))}))},t.prototype.getHighestSequenceNumber=function(t){return Ee(t.simpleDbTransaction)},t.prototype.setTargetsMetadata=function(t,e,n){var r=this;return this.retrieveMetadata(t).next((function(o){return o.highestListenSequenceNumber=e,n&&(o.lastRemoteSnapshotVersion=n.toTimestamp()),e>o.highestListenSequenceNumber&&(o.highestListenSequenceNumber=e),r.saveMetadata(t,o)}))},t.prototype.addQueryData=function(t,e){var n=this;return this.saveQueryData(t,e).next((function(){return n.retrieveMetadata(t).next((function(r){return r.targetCount+=1,n.updateMetadataFromQueryData(e,r),n.saveMetadata(t,r)}))}))},t.prototype.updateQueryData=function(t,e){return this.saveQueryData(t,e)},t.prototype.removeQueryData=function(t,e){var n=this;return this.removeMatchingKeysForTargetId(t,e.targetId).next((function(){return _e(t).delete(e.targetId)})).next((function(){return n.retrieveMetadata(t)})).next((function(e){return C(e.targetCount>0,"Removing from an empty query cache"),e.targetCount-=1,n.saveMetadata(t,e)}))},t.prototype.removeTargets=function(t,e,n){var r=this,o=0,c=[];return _e(t).iterate((function(h,l){var f=r.serializer.fromDbTarget(l);f.sequenceNumber<=e&&void 0===n[f.targetId]&&(o++,c.push(r.removeQueryData(t,f)))})).next((function(){return te.waitFor(c)})).next((function(){return o}))},t.prototype.forEachTarget=function(t,e){var n=this;return _e(t).iterate((function(t,r){var o=n.serializer.fromDbTarget(r);e(o)}))},t.prototype.retrieveMetadata=function(t){return we(t.simpleDbTransaction)},t.prototype.saveMetadata=function(t,e){return(n=t,zn.getStore(n,Nn.store)).put(Nn.key,e);var n},t.prototype.saveQueryData=function(t,e){return _e(t).put(this.serializer.toDbTarget(e))},t.prototype.updateMetadataFromQueryData=function(t,e){var n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n},t.prototype.getQueryCount=function(t){return this.retrieveMetadata(t).next((function(t){return t.targetCount}))},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),o=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),c=null;return _e(t).iterate({range:o,index:Cn.queryTargetsIndexName},(function(t,r,o){var h=n.serializer.fromDbTarget(r);e.isEqual(h.query)&&(c=h,o.done())})).next((function(){return c}))},t.prototype.addMatchingKeys=function(t,e,n){var r=this,o=[],c=Te(t);return e.forEach((function(e){var path=Dt(e.path);o.push(c.put(new In(n,path))),o.push(r.referenceDelegate.addReference(t,e))})),te.waitFor(o)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,o=Te(t);return te.forEach(e,(function(e){var path=Dt(e.path);return te.waitFor([o.delete([n,path]),r.referenceDelegate.removeReference(t,e)])}))},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=Te(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=Te(t),o=Yt();return r.iterate({range:n,keysOnly:!0},(function(t,e,n){var path=Ot(t[1]),r=new wt(path);o=o.add(r)})).next((function(){return o}))},t.prototype.containsKey=function(t,e){var path=Dt(e.path),n=IDBKeyRange.bound([path],[at(path)],!1,!0),r=0;return Te(t).iterate({index:In.documentTargetsIndex,keysOnly:!0,range:n},(function(t,e,n){var o=t[0];t[1];0!==o&&(r++,n.done())})).next((function(){return r>0}))},t.prototype.getQueryDataForTarget=function(t,e){var n=this;return _e(t).get(e).next((function(t){return t?n.serializer.fromDbTarget(t):null}))},t}();function _e(t){return zn.getStore(t,Cn.store)}function we(t){return fe.getStore(t,Nn.store).get(Nn.key).next((function(t){return C(null!==t,"Missing metadata row."),t}))}function Ee(t){return we(t).next((function(t){return t.highestListenSequenceNumber}))}function Te(t){return zn.getStore(t,In.store)}var Se,Ce=function(){function t(t){this.fields=t}return t.fromSet=function(e){return new t(e)},t.fromArray=function(e){var n=new qt(_t.comparator);return e.forEach((function(t){return n=n.add(t)})),new t(n)},t.prototype.covers=function(t){var e=!1;return this.fields.forEach((function(n){n.isPrefixOf(t)&&(e=!0)})),e},t.prototype.isEqual=function(t){return this.fields.isEqual(t.fields)},t}(),Ie=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.isEqual=function(t){return this.field.isEqual(t.field)&&this.transform.isEqual(t.transform)},t}(),Ne=function(t,e){this.version=t,this.transformResults=e};!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(Se||(Se={}));var Ae,De,ke=function(){function t(t,e){this.updateTime=t,this.exists=e,C(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof Ze&&t.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===t instanceof Ze:(C(this.isNone,"Precondition should be empty"),!0)},t.prototype.isEqual=function(t){return e=this.updateTime,n=t.updateTime,(null!=e?!(!n||!e.isEqual(n)):e===n)&&this.exists===t.exists;var e,n},t.NONE=new t,t}(),Re=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&C(t.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof Ze?t.version:xt.MIN},t}(),Oe=function(t){function e(e,n,r){var o=t.call(this)||this;return o.key=e,o.value=n,o.precondition=r,o.type=Se.Set,o}return l.__extends(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),C(null==e.transformResults,"Transform results received by SetMutation.");var n=e.version;return new Ze(this.key,n,{hasCommittedMutations:!0},this.value)},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Re.getPostMutationVersion(t);return new Ze(this.key,r,{hasLocalMutations:!0},this.value)},e.prototype.extractBaseValue=function(t){return null},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.value.isEqual(t.value)&&this.precondition.isEqual(t.precondition)},e}(Re),Pe=function(t){function e(e,data,n,r){var o=t.call(this)||this;return o.key=e,o.data=data,o.fieldMask=n,o.precondition=r,o.type=Se.Patch,o}return l.__extends(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),C(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return new en(this.key,e.version);var n=this.patchDocument(t);return new Ze(this.key,e.version,{hasCommittedMutations:!0},n)},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Re.getPostMutationVersion(t),o=this.patchDocument(t);return new Ze(this.key,r,{hasLocalMutations:!0},o)},e.prototype.extractBaseValue=function(t){return null},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.fieldMask.isEqual(t.fieldMask)&&this.precondition.isEqual(t.precondition)},e.prototype.patchDocument=function(t){var data;return data=t instanceof Ze?t.data():Xe.EMPTY,this.patchObject(data)},e.prototype.patchObject=function(data){var t=this;return this.fieldMask.fields.forEach((function(e){if(!e.isEmpty()){var n=t.data.field(e);data=null!==n?data.set(e,n):data.delete(e)}})),data},e}(Re),xe=function(t){function e(e,n){var r=t.call(this)||this;return r.key=e,r.fieldTransforms=n,r.type=Se.Transform,r.precondition=ke.exists(!0),r}return l.__extends(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),C(null!=e.transformResults,"Transform results missing for TransformMutation."),!this.precondition.isValidFor(t))return new en(this.key,e.version);var n=this.requireDocument(t),r=this.serverTransformResults(t,e.transformResults),o=e.version,c=this.transformObject(n.data(),r);return new Ze(this.key,o,{hasCommittedMutations:!0},c)},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=this.requireDocument(t),o=this.localTransformResults(n,t,e),c=this.transformObject(r.data(),o);return new Ze(this.key,r.version,{hasLocalMutations:!0},c)},e.prototype.extractBaseValue=function(t){for(var e=null,n=0,r=this.fieldTransforms;nr?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1):this.defaultCompareTo(t);var n,r},e}(Fe);function Be(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}var je=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&Be(this.internalValue,t.internalValue)},e}(Ve),We=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&Be(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(Ve),Qe=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ae.StringValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?it(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(Fe),Ke=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ae.TimestampValue,n}return l.__extends(e,t),e.prototype.value=function(t){return!t||t.timestampsInSnapshots?this.internalValue:this.internalValue.toDate()},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):t instanceof He?-1:this.defaultCompareTo(t)},e}(Fe),He=function(t){function e(e,n){var r=t.call(this)||this;return r.localWriteTime=e,r.previousValue=n,r.typeOrder=Ae.TimestampValue,r}return l.__extends(e,t),e.prototype.value=function(t){return t&&t.serverTimestampBehavior===De.Estimate?new Ke(this.localWriteTime).value(t):t&&t.serverTimestampBehavior===De.Previous&&this.previousValue?this.previousValue.value(t):null},e.prototype.isEqual=function(t){return t instanceof e&&this.localWriteTime.isEqual(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime._compareTo(t.localWriteTime):t instanceof Ke?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(Fe),Ge=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ae.BlobValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(Fe),ze=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=Ae.RefValue,r}return l.__extends(e,t),e.prototype.value=function(t){return this.key},e.prototype.isEqual=function(t){return t instanceof e&&(this.key.isEqual(t.key)&&this.databaseId.isEqual(t.databaseId))},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:wt.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(Fe),Ye=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ae.GeoPointValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(Fe),Xe=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ae.ObjectValue,n}return l.__extends(e,t),e.prototype.value=function(t){var e={};return this.internalValue.inorderTraversal((function(n,r){e[n]=r.value(t)})),e},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.isEqual=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),c=r.getNext();if(o.key!==c.key||!o.value.isEqual(c.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),c=r.getNext(),h=it(o.key,c.key)||o.value.compareTo(c.value);if(h)return h}return it(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(path,t){if(C(!path.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===path.length)return this.setChild(path.firstSegment(),t);var n=this.child(path.firstSegment());n instanceof e||(n=e.EMPTY);var r=n.set(path.popFirst(),t);return this.setChild(path.firstSegment(),r)},e.prototype.delete=function(path){if(C(!path.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===path.length)return new e(this.internalValue.remove(path.firstSegment()));var t=this.child(path.firstSegment());if(t instanceof e){var n=t.delete(path.popFirst());return new e(this.internalValue.insert(path.firstSegment(),n))}return this},e.prototype.contains=function(path){return null!==this.field(path)},e.prototype.field=function(path){C(!path.isEmpty(),"Can't get field of empty path");var t=this;return path.forEach((function(n){t=t instanceof e?t.internalValue.get(n):null})),t},e.prototype.fieldMask=function(){var t=new qt(_t.comparator);return this.internalValue.forEach((function(n,r){var o=new _t([n]);if(r instanceof e){var c=r.fieldMask().fields;c.isEmpty()?t=t.add(o):c.forEach((function(e){t=t.add(o.child(e))}))}else t=t.add(o)})),Ce.fromSet(t)},e.prototype.toString=function(){return this.internalValue.toString()},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new Lt(it)),e}(Fe),Je=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ae.ArrayValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue.map((function(e){return e.value(t)}))},e.prototype.contains=function(t){for(var e=0,n=this.internalValue;e=0&&r<=dn,"Unexpected schema upgrade from v"+n+" to v{toVersion}."),n<1&&r>=1&&(function(t){t.createObjectStore(gn.store)}(t),function(t){t.createObjectStore(vn.store,{keyPath:vn.keyPath}),t.createObjectStore(bn.store,{keyPath:bn.keyPath,autoIncrement:!0}).createIndex(bn.userMutationsIndex,bn.userMutationsKeyPath,{unique:!0}),t.createObjectStore(_n.store)}(t),Dn(t),function(t){t.createObjectStore(Tn.store)}(t));var p=te.resolve();return n<3&&r>=3&&(0!==n&&(!function(t){t.deleteObjectStore(In.store),t.deleteObjectStore(Cn.store),t.deleteObjectStore(Nn.store)}(t),Dn(t)),p=p.next((function(){return function(t){var e=t.store(Nn.store),n=new Nn(0,0,xt.MIN.toTimestamp(),0);return e.put(Nn.key,n)}(e)}))),n<4&&r>=4&&(0!==n&&(p=p.next((function(){return function(t,e){return e.store(bn.store).loadAll().next((function(n){t.deleteObjectStore(bn.store),t.createObjectStore(bn.store,{keyPath:bn.keyPath,autoIncrement:!0}).createIndex(bn.userMutationsIndex,bn.userMutationsKeyPath,{unique:!0});var r=e.store(bn.store),o=n.map((function(t){return r.put(t)}));return te.waitFor(o)}))}(t,e)}))),p=p.next((function(){!function(t){t.createObjectStore(Rn.store,{keyPath:Rn.keyPath})}(t),function(t){t.createObjectStore(kn.store,{keyPath:"id",autoIncrement:!0})}(t)}))),n<5&&r>=5&&(p=p.next((function(){return o.removeAcknowledgedMutations(e)}))),n<6&&r>=6&&(p=p.next((function(){return function(t){t.createObjectStore(Sn.store)}(t),o.addDocumentGlobal(e)}))),n<7&&r>=7&&(p=p.next((function(){return o.ensureSequenceNumbers(e)}))),n<8&&r>=8&&(p=p.next((function(){return o.createCollectionParentIndex(t,e)}))),p},t.prototype.addDocumentGlobal=function(t){var e=0;return t.store(Tn.store).iterate((function(t,n){e+=ln(n)})).next((function(){var n=new Sn(e);return t.store(Sn.store).put(Sn.key,n)}))},t.prototype.removeAcknowledgedMutations=function(t){var e=this,n=t.store(vn.store),r=t.store(bn.store);return n.loadAll().next((function(n){return te.forEach(n,(function(n){var o=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return r.loadAll(bn.userMutationsIndex,o).next((function(r){return te.forEach(r,(function(r){C(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var o=e.serializer.fromDbMutationBatch(r);return re(t,n.userId,o).next((function(){}))}))}))}))}))},t.prototype.ensureSequenceNumbers=function(t){var e=t.store(In.store),n=t.store(Tn.store);return Ee(t).next((function(t){var r=[];return n.iterate((function(n,o){var path=new vt(n),c=function(path){return[0,Dt(path)]}(path);r.push(e.get(c).next((function(n){return n?te.resolve():function(path){return e.put(new In(0,Dt(path),t))}(path)})))})).next((function(){return te.waitFor(r)}))}))},t.prototype.createCollectionParentIndex=function(t,e){t.createObjectStore(An.store,{keyPath:An.keyPath});var n=e.store(An.store),r=new pn,o=function(t){if(r.add(t)){var e=t.lastSegment(),o=t.popLast();return n.put({collectionId:e,parent:Dt(o)})}};return e.store(Tn.store).iterate({keysOnly:!0},(function(t,e){var path=new vt(t);return o(path.popLast())})).next((function(){return e.store(_n.store).iterate({keysOnly:!0},(function(t,e){t[0];var n=t[1],path=(t[2],Ot(n));return o(path.popLast())}))}))},t}();var mn=function(t,e){this.seconds=t,this.nanoseconds=e},gn=function(){function t(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}return t.store="owner",t.key="owner",t}();var vn=function(){function t(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}return t.store="mutationQueues",t.keyPath="userId",t}(),bn=function(){function t(t,e,n,r,o){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=o}return t.store="mutations",t.keyPath="batchId",t.userMutationsIndex="userMutationsIndex",t.userMutationsKeyPath=["userId","batchId"],t}();var _n=function(){function t(){}return t.prefixForUser=function(t){return[t]},t.prefixForPath=function(t,path){return[t,Dt(path)]},t.key=function(t,path,e){return[t,Dt(path),e]},t.store="documentMutations",t.PLACEHOLDER=new t,t}();var wn=function(path,t){this.path=path,this.readTime=t},En=function(path,t){this.path=path,this.version=t},Tn=function(){function t(t,e,n,r){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r}return t.store="remoteDocuments",t}(),Sn=function(){function t(t){this.byteSize=t}return t.store="remoteDocumentGlobal",t.key="remoteDocumentGlobalKey",t}();var Cn=function(){function t(t,e,n,r,o,c){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=o,this.query=c}return t.store="targets",t.keyPath="targetId",t.queryTargetsIndexName="queryTargetsIndex",t.queryTargetsKeyPath=["canonicalId","targetId"],t}(),In=function(){function t(t,path,e){this.targetId=t,this.path=path,this.sequenceNumber=e,C(0===t==(void 0!==e),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}return t.store="targetDocuments",t.keyPath=["targetId","path"],t.documentTargetsIndex="documentTargetsIndex",t.documentTargetsKeyPath=["path","targetId"],t}(),Nn=function(){function t(t,e,n,r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r}return t.key="targetGlobalKey",t.store="targetGlobal",t}(),An=function(){function t(t,e){this.collectionId=t,this.parent=e}return t.store="collectionParents",t.keyPath=["collectionId","parent"],t}();function Dn(t){t.createObjectStore(In.store,{keyPath:In.keyPath}).createIndex(In.documentTargetsIndex,In.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(Cn.store,{keyPath:Cn.keyPath}).createIndex(Cn.queryTargetsIndexName,Cn.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(Nn.store)}var kn=function(){function t(t){this.changes=t}return t.store="remoteDocumentChanges",t.keyPath="id",t}();var Rn=function(){function t(t,e,n,r,o){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r,this.lastProcessedDocumentChangeId=o}return t.store="clientMetadata",t.keyPath="clientId",t}();var On,Pn=[vn.store,bn.store,_n.store,Tn.store,Cn.store,gn.store,Nn.store,In.store].concat([Rn.store,kn.store]).concat([Sn.store]).concat([An.store]),xn=function(){function t(){this.collectionParentsCache=new pn}return t.prototype.addToCollectionParentIndex=function(t,e){if(C(e.length%2==1,"Expected a collection path."),this.collectionParentsCache.add(e)){C(e.length>=1,"Invalid collection path.");var n=e.lastSegment(),r=e.popLast();return Ln(t).put({collectionId:n,parent:Dt(r)})}return te.resolve()},t.prototype.getCollectionParents=function(t,e){var n=[],r=IDBKeyRange.bound([e,""],[at(e),""],!1,!0);return Ln(t).loadAll(r).next((function(t){for(var r=0,o=t;ry.params.maximumSequenceNumbersToCollect?(w("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+y.params.maximumSequenceNumbersToCollect+" from "+e),r=y.params.maximumSequenceNumbersToCollect):r=e,h=Date.now(),y.nthSequenceNumber(t,r)})).next((function(r){return n=r,l=Date.now(),y.removeTargets(t,n,e)})).next((function(e){return c=e,f=Date.now(),y.removeOrphanedDocuments(t,n)})).next((function(t){(d=Date.now(),v()<=o.DEBUG)&&w("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(h-m)+"ms\n\tDetermined least recently used "+r+" in "+(l-h)+"ms\n\tRemoved "+c+" targets in "+(f-l)+"ms\n\tRemoved "+t+" documents in "+(d-f)+"ms\nTotal Duration: "+(d-m)+"ms");return te.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:c,documentsRemoved:t})}))},t}(),Qn="IndexedDbPersistence",Kn="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",Hn="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.",Gn=function(t){function e(e,n){var r=t.call(this)||this;return r.simpleDbTransaction=e,r.currentSequenceNumber=n,r}return l.__extends(e,t),e}((function(){})),zn=function(){function t(e,n,r,o,c,h,l,f){if(this.allowTabSynchronization=e,this.persistenceKey=n,this.clientId=r,this.queue=h,this.sequenceNumberSyncer=f,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.windowUnloadHandler=null,this.inForeground=!1,this.documentVisibilityHandler=null,this.clientMetadataRefresher=null,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(t){return Promise.resolve()},this.referenceDelegate=new $n(this,c),this.dbName=n+t.MAIN_DATABASE,this.serializer=new Fn(l),this.document=o.document,this.queryCache=new be(this.referenceDelegate,this.serializer),this.indexManager=new xn,this.remoteDocumentCache=new an(this.serializer,this.indexManager,this.allowTabSynchronization),!o.window||!o.window.localStorage)throw new D(A.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=o.window,this.webStorage=this.window.localStorage}return t.getStore=function(t,e){if(t instanceof Gn)return fe.getStore(t.simpleDbTransaction,e);throw S("IndexedDbPersistence must use instances of IndexedDbTransaction")},t.createIndexedDbPersistence=function(e){return l.__awaiter(this,void 0,void 0,(function(){var n;return l.__generator(this,(function(r){switch(r.label){case 0:if(!t.isAvailable())throw new D(A.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");return[4,(n=new t(e.allowTabSynchronization,e.persistenceKey,e.clientId,e.platform,e.lruParams,e.queue,e.serializer,e.sequenceNumberSyncer)).start()];case 1:return r.sent(),[2,n]}}))}))},t.prototype.start=function(){var t=this;return C(!this.started,"IndexedDbPersistence double-started!"),C(null!==this.window,"Expected 'window' to be defined"),fe.openOrCreate(this.dbName,dn,new yn(this.serializer)).then((function(e){return t.simpleDb=e,t.updateClientMetadataAndTryBecomePrimary()})).then((function(){return t.attachVisibilityHandler(),t.attachWindowUnloadHook(),t.scheduleClientMetadataAndPrimaryLeaseRefreshes(),t.startRemoteDocumentCache()})).then((function(){return t.simpleDb.runTransaction("readonly",[Nn.store],(function(e){return Ee(e).next((function(e){t.listenSequence=new mt(e,t.sequenceNumberSyncer)}))}))})).then((function(){t._started=!0})).catch((function(e){return t.simpleDb&&t.simpleDb.close(),Promise.reject(e)}))},t.prototype.startRemoteDocumentCache=function(){var t=this;return this.simpleDb.runTransaction("readonly",Pn,(function(e){return t.remoteDocumentCache.start(e)}))},t.prototype.setPrimaryStateListener=function(t){var e=this;return this.primaryStateListener=function(n){return l.__awaiter(e,void 0,void 0,(function(){return l.__generator(this,(function(e){return this.started?[2,t(n)]:[2]}))}))},t(this.isPrimary)},t.prototype.setDatabaseDeletedListener=function(t){var e=this;this.simpleDb.setVersionChangeListener((function(n){return l.__awaiter(e,void 0,void 0,(function(){return l.__generator(this,(function(e){switch(e.label){case 0:return null!==n.newVersion?[3,2]:[4,t()];case 1:e.sent(),e.label=2;case 2:return[2]}}))}))}))},t.prototype.setNetworkEnabled=function(t){var e=this;this.networkEnabled!==t&&(this.networkEnabled=t,this.queue.enqueueAndForget((function(){return l.__awaiter(e,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return this.started?[4,this.updateClientMetadataAndTryBecomePrimary()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))})))},t.prototype.updateClientMetadataAndTryBecomePrimary=function(){var t=this;return this.simpleDb.runTransaction("readwrite",Pn,(function(e){return Jn(e).put(new Rn(t.clientId,Date.now(),t.networkEnabled,t.inForeground,t.remoteDocumentCache.lastProcessedDocumentChangeId)).next((function(){if(t.isPrimary)return t.verifyPrimaryLease(e).next((function(e){e||(t.isPrimary=!1,t.queue.enqueueAndForget((function(){return t.primaryStateListener(!1)})))}))})).next((function(){return t.canActAsPrimary(e)})).next((function(n){var r=t.isPrimary;return t.isPrimary=n,r!==t.isPrimary&&t.queue.enqueueAndForget((function(){return t.primaryStateListener(t.isPrimary)})),r&&!t.isPrimary?t.releasePrimaryLeaseIfHeld(e):t.isPrimary?t.acquireOrExtendPrimaryLease(e):void 0}))}))},t.prototype.verifyPrimaryLease=function(t){var e=this;return Xn(t).get(gn.key).next((function(t){return te.resolve(e.isLocalClient(t))}))},t.prototype.removeClientMetadata=function(t){return Jn(t).delete(this.clientId)},t.prototype.maybeGarbageCollectMultiClientState=function(){return l.__awaiter(this,void 0,void 0,(function(){var e,n,r=this;return l.__generator(this,(function(o){switch(o.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,18e5)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),n=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(function(o){var c=t.getStore(o,Rn.store);return c.loadAll().next((function(t){e=r.filterActiveClients(t,18e5),n=t.filter((function(t){return-1===e.indexOf(t)}))})).next((function(){return te.forEach(n,(function(t){return c.delete(t.clientId)}))})).next((function(){if((e=e.filter((function(t){return t.clientId!==r.clientId}))).length>0){var t=e.map((function(t){return t.lastProcessedDocumentChangeId||0})),n=Math.min.apply(Math,t);return r.remoteDocumentCache.removeDocumentChangesThroughChangeId(o,n)}}))}))]);case 1:o.sent(),n.forEach((function(t){r.window.localStorage.removeItem(r.zombiedClientLocalStorageKey(t.clientId))})),o.label=2;case 2:return[2]}}))}))},t.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var t=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(ct.ClientMetadataRefresh,4e3,(function(){return t.updateClientMetadataAndTryBecomePrimary().then((function(){return t.maybeGarbageCollectMultiClientState()})).then((function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()}))}))},t.prototype.isLocalClient=function(t){return!!t&&t.ownerId===this.clientId},t.prototype.canActAsPrimary=function(t){var e=this;return Xn(t).get(gn.key).next((function(n){if(null!==n&&e.isWithinAge(n.leaseTimestampMs,5e3)&&!e.isClientZombied(n.ownerId)){if(e.isLocalClient(n)&&e.networkEnabled)return!0;if(!e.isLocalClient(n)){if(!n.allowTabSynchronization)throw new D(A.FAILED_PRECONDITION,Hn);return!1}}return!(!e.networkEnabled||!e.inForeground)||Jn(t).loadAll().next((function(t){return void 0===e.filterActiveClients(t,5e3).find((function(t){if(e.clientId!==t.clientId){var n=!e.networkEnabled&&t.networkEnabled,r=!e.inForeground&&t.inForeground,o=e.networkEnabled===t.networkEnabled;if(n||r&&o)return!0}return!1}))}))})).next((function(t){return e.isPrimary!==t&&w(Qn,"Client "+(t?"is":"is not")+" eligible for a primary lease."),t}))},t.prototype.shutdown=function(){return l.__awaiter(this,void 0,void 0,(function(){var t=this;return l.__generator(this,(function(e){switch(e.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&(this.clientMetadataRefresher.cancel(),this.clientMetadataRefresher=null),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite",[gn.store,Rn.store],(function(e){return t.releasePrimaryLeaseIfHeld(e).next((function(){return t.removeClientMetadata(e)}))}))];case 1:return e.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),[2]}}))}))},t.prototype.filterActiveClients=function(t,e){var n=this;return t.filter((function(t){return n.isWithinAge(t.updateTimeMs,e)&&!n.isClientZombied(t.clientId)}))},t.prototype.getActiveClients=function(){var t=this;return this.simpleDb.runTransaction("readonly",[Rn.store],(function(e){return Jn(e).loadAll().next((function(e){return t.filterActiveClients(e,18e5).map((function(t){return t.clientId}))}))}))},t.clearPersistence=function(e){return l.__awaiter(this,void 0,void 0,(function(){var n;return l.__generator(this,(function(r){switch(r.label){case 0:return t.isAvailable()?(n=e+t.MAIN_DATABASE,[4,fe.delete(n)]):[2,Promise.resolve()];case 1:return r.sent(),[2]}}))}))},Object.defineProperty(t.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),t.prototype.getMutationQueue=function(t){return C(this.started,"Cannot initialize MutationQueue before persistence is started."),ee.forUser(t,this.serializer,this.indexManager,this.referenceDelegate)},t.prototype.getQueryCache=function(){return C(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},t.prototype.getRemoteDocumentCache=function(){return C(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},t.prototype.getIndexManager=function(){return C(this.started,"Cannot initialize IndexManager before persistence is started."),this.indexManager},t.prototype.runTransaction=function(t,e,n){var r=this;return w(Qn,"Starting transaction:",t),this.simpleDb.runTransaction("readonly"===e?"readonly":"readwrite",Pn,(function(o){return"readwrite-primary"===e?r.verifyPrimaryLease(o).next((function(e){if(!e)throw E("Failed to obtain primary lease for action '"+t+"'."),r.isPrimary=!1,r.queue.enqueueAndForget((function(){return r.primaryStateListener(!1)})),new D(A.FAILED_PRECONDITION,Kn);return n(new Gn(o,r.listenSequence.next()))})).next((function(t){return r.acquireOrExtendPrimaryLease(o).next((function(){return t}))})):r.verifyAllowTabSynchronization(o).next((function(){return n(new Gn(o,r.listenSequence.next()))}))}))},t.prototype.verifyAllowTabSynchronization=function(t){var e=this;return Xn(t).get(gn.key).next((function(t){if(null!==t&&e.isWithinAge(t.leaseTimestampMs,5e3)&&!e.isClientZombied(t.ownerId)&&!e.isLocalClient(t)&&!t.allowTabSynchronization)throw new D(A.FAILED_PRECONDITION,Hn)}))},t.prototype.acquireOrExtendPrimaryLease=function(t){var e=new gn(this.clientId,this.allowTabSynchronization,Date.now());return Xn(t).put(gn.key,e)},t.isAvailable=function(){return fe.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.releasePrimaryLeaseIfHeld=function(t){var e=this,n=Xn(t);return n.get(gn.key).next((function(t){return e.isLocalClient(t)?(w(Qn,"Releasing primary lease."),n.delete(gn.key)):te.resolve()}))},t.prototype.isWithinAge=function(t,e){var n=Date.now();return!(tn)||(E("Detected an update time that is in the future: "+t+" > "+n),!1))},t.prototype.attachVisibilityHandler=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.documentVisibilityHandler=function(){t.queue.enqueueAndForget((function(){return t.inForeground="visible"===t.document.visibilityState,t.updateClientMetadataAndTryBecomePrimary()}))},this.document.addEventListener("visibilitychange",this.documentVisibilityHandler),this.inForeground="visible"===this.document.visibilityState)},t.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(C(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;"function"==typeof this.window.addEventListener&&(this.windowUnloadHandler=function(){t.markClientZombied(),t.queue.enqueueAndForget((function(){return t.shutdown()}))},this.window.addEventListener("unload",this.windowUnloadHandler))},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(C("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.isClientZombied=function(t){try{var e=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(t));return w(Qn,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return E(Qn,"Failed to get zombied client id.",t),!1}},t.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(t){E("Failed to set zombie client id.",t)}},t.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(t){}},t.prototype.zombiedClientLocalStorageKey=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},t.MAIN_DATABASE="main",t}();function Yn(t){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(e){if(!function(t){return t.code===A.FAILED_PRECONDITION&&t.message===Kn}(t))throw t;return w(Qn,"Unexpectedly lost primary lease"),[2]}))}))}function Xn(t){return t.store(gn.store)}function Jn(t){return t.store(Rn.store)}var $n=function(){function t(t,e){this.db=t,this.inMemoryPins=null,this.garbageCollector=new Wn(this,e)}return t.prototype.getSequenceNumberCount=function(t){var e=this.orphanedDocmentCount(t);return this.db.getQueryCache().getQueryCount(t).next((function(t){return e.next((function(e){return t+e}))}))},t.prototype.orphanedDocmentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,(function(t){e++})).next((function(){return e}))},t.prototype.forEachTarget=function(t,e){return this.db.getQueryCache().forEachTarget(t,e)},t.prototype.forEachOrphanedDocumentSequenceNumber=function(t,e){return this.forEachOrphanedDocument(t,(function(t,n){return e(n)}))},t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.addReference=function(t,e){return Zn(t,e)},t.prototype.removeReference=function(t,e){return Zn(t,e)},t.prototype.removeTargets=function(t,e,n){return this.db.getQueryCache().removeTargets(t,e,n)},t.prototype.removeMutationReference=function(t,e){return Zn(t,e)},t.prototype.isPinned=function(t,e){return this.inMemoryPins.containsKey(e)?te.resolve(!0):function(t,e){var n=!1;return se(t).iterateSerial((function(r){return ne(t,r,e).next((function(t){return t&&(n=!0),te.resolve(!t)}))})).next((function(){return n}))}(t,e)},t.prototype.removeOrphanedDocuments=function(t,e){var n=this,r=this.db.getRemoteDocumentCache().newChangeBuffer(),o=[],c=0;return this.forEachOrphanedDocument(t,(function(h,l){if(l<=e){var p=n.isPinned(t,h).next((function(e){if(!e)return c++,r.getEntry(t,h).next((function(){return r.removeEntry(h),Te(t).delete([0,Dt(h.path)])}))}));o.push(p)}})).next((function(){return te.waitFor(o)})).next((function(){return r.apply(t)})).next((function(){return c}))},t.prototype.removeTarget=function(t,e){var n=e.withSequenceNumber(t.currentSequenceNumber);return this.db.getQueryCache().updateQueryData(t,n)},t.prototype.updateLimboDocument=function(t,e){return Zn(t,e)},t.prototype.forEachOrphanedDocument=function(t,e){var n,r=Te(t),o=mt.INVALID;return r.iterate({index:In.documentTargetsIndex},(function(t,r){var c=t[0],path=(t[1],r.path),h=r.sequenceNumber;0===c?(o!==mt.INVALID&&e(new wt(Ot(n)),o),o=h,n=path):o=mt.INVALID})).next((function(){o!==mt.INVALID&&e(new wt(Ot(n)),o)}))},t.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},t}();function Zn(t,e){return Te(t).put(function(t,e){return new In(0,Dt(t.path),e)}(e,t.currentSequenceNumber))}var er=function(){function t(t,e,n){this.remoteDocumentCache=t,this.mutationQueue=e,this.indexManager=n}return t.prototype.getDocument=function(t,e){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(t,e).next((function(r){return n.getDocumentInternal(t,e,r)}))},t.prototype.getDocumentInternal=function(t,e,n){return this.remoteDocumentCache.getEntry(t,e).next((function(t){for(var r=0,o=n;r0){var d=l.withResumeToken(f,o);n.queryDataByTarget[e]=d,t.shouldPersistQueryData(l,d,r)&&h.push(n.queryCache.updateQueryData(c,d))}}}));var l=jt(),f=Yt();if(e.documentUpdates.forEach((function(t,e){f=f.add(t)})),h.push(r.getEntries(c,f).next((function(t){e.documentUpdates.forEach((function(o,f){var d=t.get(o);f instanceof tn&&f.version.isEqual(xt.MIN)?(r.removeEntry(o),l=l.insert(o,f)):null==d||f.version.compareTo(d.version)>0||0===f.version.compareTo(d.version)&&d.hasPendingWrites?(xt.MIN.isEqual(e.snapshotVersion)&&E("LocalStore","Cannot add a document when the remote version is zero"),r.addEntry(f),l=l.insert(o,f)):w("LocalStore","Ignoring outdated watch update for ",o,". Current version:",d.version," Watch version:",f.version),e.resolvedLimboDocuments.has(o)&&h.push(n.persistence.referenceDelegate.updateLimboDocument(c,o))}))}))),!o.isEqual(xt.MIN)){var d=n.queryCache.getLastRemoteSnapshotVersion(c).next((function(t){return C(o.compareTo(t)>=0,"Watch stream reverted to previous snapshot?? "+o+" < "+t),n.queryCache.setTargetsMetadata(c,c.currentSequenceNumber,o)}));h.push(d)}return te.waitFor(h).next((function(){return r.apply(c)})).next((function(){return n.localDocuments.getLocalViewOfDocuments(c,l)}))}))},t.shouldPersistQueryData=function(t,e,n){return C(e.resumeToken.length>0,"Attempted to persist query data with no resume token"),0===t.resumeToken.length||(e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=this.RESUME_TOKEN_MAX_AGE_MICROS||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0)},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("notifyLocalViewChanges","readwrite",(function(n){return te.forEach(t,(function(t){return e.localViewReferences.addReferences(t.addedKeys,t.targetId),e.localViewReferences.removeReferences(t.removedKeys,t.targetId),te.forEach(t.removedKeys,(function(t){return e.persistence.referenceDelegate.removeReference(n,t)}))}))}))},t.prototype.nextMutationBatch=function(t){var e=this;return this.persistence.runTransaction("Get next mutation batch","readonly",(function(n){return void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)}))},t.prototype.readDocument=function(t){var e=this;return this.persistence.runTransaction("read document","readonly",(function(n){return e.localDocuments.getDocument(n,t)}))},t.prototype.allocateQuery=function(t){var e=this;return this.persistence.runTransaction("Allocate query","readwrite",(function(n){var r;return e.queryCache.getQueryData(n,t).next((function(o){return o?(r=o,te.resolve()):e.queryCache.allocateTargetId(n).next((function(o){return r=new Mn(t,o,On.Listen,n.currentSequenceNumber),e.queryCache.addQueryData(n,r)}))})).next((function(){return C(!e.queryDataByTarget[r.targetId],"Tried to allocate an already allocated query: "+t),e.queryDataByTarget[r.targetId]=r,r}))}))},t.prototype.releaseQuery=function(t,e){var n=this,r=e?"readwrite":"readwrite-primary";return this.persistence.runTransaction("Release query",r,(function(r){return n.queryCache.getQueryData(r,t).next((function(o){C(null!=o,"Tried to release nonexistent query: "+t);var c=o.targetId,h=n.queryDataByTarget[c],l=n.localViewReferences.removeReferencesForId(c);return delete n.queryDataByTarget[c],e?te.resolve():te.forEach(l,(function(t){return n.persistence.referenceDelegate.removeReference(r,t)})).next((function(){return n.persistence.referenceDelegate.removeTarget(r,h)}))}))}))},t.prototype.executeQuery=function(t){var e=this;return this.persistence.runTransaction("Execute query","readonly",(function(n){return e.localDocuments.getDocumentsMatchingQuery(n,t)}))},t.prototype.remoteDocumentKeys=function(t){var e=this;return this.persistence.runTransaction("Remote document keys","readonly",(function(n){return e.queryCache.getMatchingKeysForTargetId(n,t)}))},t.prototype.getActiveClients=function(){return this.persistence.getActiveClients()},t.prototype.removeCachedMutationBatchMetadata=function(t){this.mutationQueue.removeCachedMutationKeys(t)},t.prototype.setNetworkEnabled=function(t){this.persistence.setNetworkEnabled(t)},t.prototype.applyWriteToRemoteDocuments=function(t,e,n){var r=this,o=e.batch,c=o.keys(),h=te.resolve();return c.forEach((function(r){h=h.next((function(){return n.getEntry(t,r)})).next((function(t){var c=t,h=e.docVersions.get(r);C(null!==h,"ackVersions should contain every doc in the write."),(!c||c.version.compareTo(h)<0)&&((c=o.applyToRemoteDocument(r,c,e))?n.addEntry(c):C(!t,"Mutation batch "+o+" applied to document "+t+" resulted in null"))}))})),h.next((function(){return r.mutationQueue.removeMutationBatch(t,o)}))},t.prototype.collectGarbage=function(t){var e=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",(function(n){return t.collect(n,e.queryDataByTarget)}))},t.prototype.getQueryForTarget=function(t){var e=this;return this.queryDataByTarget[t]?Promise.resolve(this.queryDataByTarget[t].query):this.persistence.runTransaction("Get query data","readonly",(function(n){return e.queryCache.getQueryDataForTarget(n,t).next((function(t){return t?t.query:null}))}))},t.prototype.getNewDocumentChanges=function(){var t=this;return this.persistence.runTransaction("Get new document changes","readonly",(function(e){return t.remoteDocuments.getNewDocumentChanges(e)}))},t.RESUME_TOKEN_MAX_AGE_MICROS=3e8,t}(),or=function(){function t(t,e){this.indexManager=t,this.referenceDelegate=e,this.mutationQueue=[],this.nextBatchId=1,this.lastStreamToken=N(),this.batchesByDocumentKey=new qt(rr.compareByKey)}return t.prototype.checkEmpty=function(t){return te.resolve(0===this.mutationQueue.length)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId,o=this.indexOfExistingBatchId(r,"acknowledged");C(0===o,"Can only acknowledge the first batch in the mutation queue");var c=this.mutationQueue[o];return C(r===c.batchId,"Queue ordering failure: expected batch "+r+", got batch "+c.batchId),this.lastStreamToken=n,te.resolve()},t.prototype.getLastStreamToken=function(t){return te.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,te.resolve()},t.prototype.addMutationBatch=function(t,e,n,r){C(0!==r.length,"Mutation batches should not be empty");var o=this.nextBatchId;(this.nextBatchId++,this.mutationQueue.length>0)&&C(this.mutationQueue[this.mutationQueue.length-1].batchIdo?this.mutationQueue[o]:null)},t.prototype.getHighestUnacknowledgedBatchId=function(){return te.resolve(0===this.mutationQueue.length?-1:this.nextBatchId-1)},t.prototype.getAllMutationBatches=function(t){return te.resolve(this.mutationQueue.slice())},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new rr(e,0),o=new rr(e,Number.POSITIVE_INFINITY),c=[];return this.batchesByDocumentKey.forEachInRange([r,o],(function(t){C(e.isEqual(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);C(null!==r,"Batches in the index must exist in the main table"),c.push(r)})),te.resolve(c)},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new qt(it);return e.forEach((function(t){var e=new rr(t,0),o=new rr(t,Number.POSITIVE_INFINITY);n.batchesByDocumentKey.forEachInRange([e,o],(function(e){C(t.isEqual(e.key),"For each key, should only iterate over a single key's batches"),r=r.add(e.targetOrBatchId)}))})),te.resolve(this.findMutationBatches(r))},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){C(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var n=e.path,r=n.length+1,o=n;wt.isDocumentKey(o)||(o=o.child(""));var c=new rr(new wt(o),0),h=new qt(it);return this.batchesByDocumentKey.forEachWhile((function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(h=h.add(t.targetOrBatchId)),!0)}),c),te.resolve(this.findMutationBatches(h))},t.prototype.findMutationBatches=function(t){var e=this,n=[];return t.forEach((function(t){var r=e.findMutationBatch(t);null!==r&&n.push(r)})),n},t.prototype.removeMutationBatch=function(t,e){var n=this;C(0===this.indexOfExistingBatchId(e.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var r=this.batchesByDocumentKey;return te.forEach(e.mutations,(function(o){var c=new rr(o.key,e.batchId);return r=r.delete(c),n.referenceDelegate.removeMutationReference(t,o.key)})).next((function(){n.batchesByDocumentKey=r}))},t.prototype.removeCachedMutationKeys=function(t){},t.prototype.containsKey=function(t,e){var n=new rr(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return te.resolve(e.isEqual(r&&r.key))},t.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&C(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),te.resolve()},t.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return C(n>=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return C(n.batchId===t,"If found batch must match"),n},t}(),ar=function(){function t(t){this.persistence=t,this.queries=new nn((function(q){return q.canonicalId()})),this.lastRemoteSnapshotVersion=xt.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new nr,this.targetCount=0,this.targetIdGenerator=he.forQueryCache()}return t.prototype.getTargetCount=function(t){return te.resolve(this.targetCount)},t.prototype.forEachTarget=function(t,e){return this.queries.forEach((function(t,n){return e(n)})),te.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(t){return te.resolve(this.lastRemoteSnapshotVersion)},t.prototype.getHighestSequenceNumber=function(t){return te.resolve(this.highestSequenceNumber)},t.prototype.allocateTargetId=function(t){var e=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=e,te.resolve(e)},t.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.highestSequenceNumber&&(this.highestSequenceNumber=e),te.resolve()},t.prototype.saveQueryData=function(t){this.queries.set(t.query,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.highestSequenceNumber&&(this.highestSequenceNumber=t.sequenceNumber)},t.prototype.addQueryData=function(t,e){return C(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,te.resolve()},t.prototype.updateQueryData=function(t,e){return C(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),te.resolve()},t.prototype.removeQueryData=function(t,e){return C(this.targetCount>0,"Removing a target from an empty cache"),C(this.queries.has(e.query),"Removing a non-existent target from the cache"),this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),this.targetCount-=1,te.resolve()},t.prototype.removeTargets=function(t,e,n){var r=this,o=0,c=[];return this.queries.forEach((function(h,l){l.sequenceNumber<=e&&!n[l.targetId]&&(r.queries.delete(h),c.push(r.removeMatchingKeysForTargetId(t,l.targetId)),o++)})),te.waitFor(c).next((function(){return o}))},t.prototype.getQueryCount=function(t){return te.resolve(this.targetCount)},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return te.resolve(n)},t.prototype.getQueryDataForTarget=function(t,e){return S("Not yet implemented.")},t.prototype.addMatchingKeys=function(t,e,n){this.references.addReferences(e,n);var r=this.persistence.referenceDelegate,o=[];return r&&e.forEach((function(e){o.push(r.addReference(t,e))})),te.waitFor(o)},t.prototype.removeMatchingKeys=function(t,e,n){this.references.removeReferences(e,n);var r=this.persistence.referenceDelegate,o=[];return r&&e.forEach((function(e){o.push(r.removeReference(t,e))})),te.waitFor(o)},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),te.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return te.resolve(n)},t.prototype.containsKey=function(t,e){return te.resolve(this.references.containsKey(e))},t}();var sr=function(){function t(t,e){this.indexManager=t,this.sizer=e,this.docs=new Lt(wt.comparator),this.newDocumentChanges=Yt(),this.size=0}return t.prototype.addEntry=function(t,e){var n=e.key,r=this.docs.get(n),o=r?r.size:0,c=this.sizer(e);return this.docs=this.docs.insert(n,{maybeDocument:e,size:c}),this.newDocumentChanges=this.newDocumentChanges.add(n),this.size+=c-o,this.indexManager.addToCollectionParentIndex(t,n.path.popLast())},t.prototype.removeEntry=function(t){var e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)},t.prototype.getEntry=function(t,e){var n=this.docs.get(e);return te.resolve(n?n.maybeDocument:null)},t.prototype.getEntries=function(t,e){var n=this,r=Wt();return e.forEach((function(t){var e=n.docs.get(t);r=r.insert(t,e?e.maybeDocument:null)})),te.resolve(r)},t.prototype.getDocumentsMatchingQuery=function(t,e){C(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");for(var n=Kt(),r=new wt(e.path.child("")),o=this.docs.getIteratorFrom(r);o.hasNext();){var c=o.getNext(),h=c.key,l=c.value.maybeDocument;if(!e.path.isPrefixOf(h.path))break;l instanceof Ze&&e.matches(l)&&(n=n.insert(l.key,l))}return te.resolve(n)},t.prototype.forEachDocumentKey=function(t,e){return te.forEach(this.docs,(function(t){return e(t)}))},t.prototype.getNewDocumentChanges=function(t){var e=this,n=jt();return this.newDocumentChanges.forEach((function(t){var r=e.docs.get(t),o=r?r.maybeDocument:new tn(t,xt.forDeletedDoc());n=n.insert(t,o)})),this.newDocumentChanges=Yt(),te.resolve(n)},t.prototype.newChangeBuffer=function(){return new t.RemoteDocumentChangeBuffer(this)},t.prototype.getSize=function(t){return te.resolve(this.size)},t.RemoteDocumentChangeBuffer=function(t){function e(e){var n=t.call(this)||this;return n.documentCache=e,n}return l.__extends(e,t),e.prototype.applyChanges=function(t){var e=this,n=[];return this.changes.forEach((function(r,o){o?n.push(e.documentCache.addEntry(t,o)):e.documentCache.removeEntry(r)})),te.waitFor(n)},e.prototype.getFromCache=function(t,e){return this.documentCache.getEntry(t,e)},e.prototype.getAllFromCache=function(t,e){return this.documentCache.getEntries(t,e)},e}(rn),t}(),ur=function(){function t(t,e){var n=this;this.clientId=t,this.mutationQueues={},this.listenSequence=new mt(0),this._started=!1,this._started=!0,this.referenceDelegate=e(this),this.queryCache=new ar(this);this.indexManager=new fn,this.remoteDocumentCache=new sr(this.indexManager,(function(t){return n.referenceDelegate.documentSize(t)}))}return t.createLruPersistence=function(e,n,r){return new t(e,(function(p){return new fr(p,new Fn(n),r)}))},t.createEagerPersistence=function(e){return new t(e,(function(p){return new lr(p)}))},t.prototype.shutdown=function(){return this._started=!1,Promise.resolve()},Object.defineProperty(t.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),t.prototype.getActiveClients=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){return[2,[this.clientId]]}))}))},t.prototype.setPrimaryStateListener=function(t){return t(!0)},t.prototype.setDatabaseDeletedListener=function(){},t.prototype.setNetworkEnabled=function(t){},t.prototype.getIndexManager=function(){return this.indexManager},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new or(this.indexManager,this.referenceDelegate),this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e,n){var r=this;w("MemoryPersistence","Starting transaction:",t);var o=new cr(this.listenSequence.next());return this.referenceDelegate.onTransactionStarted(),n(o).next((function(t){return r.referenceDelegate.onTransactionCommitted(o).next((function(){return t}))})).toPromise()},t.prototype.mutationQueuesContainKey=function(t,e){return te.or((n=this.mutationQueues,r=[],x(n,(function(t,e){return r.push(e)})),r).map((function(n){return function(){return n.containsKey(t,e)}})));var n,r},t}(),cr=function(t){this.currentSequenceNumber=t},lr=function(){function t(t){this.persistence=t,this.inMemoryPins=null,this._orphanedDocuments=null}return Object.defineProperty(t.prototype,"orphanedDocuments",{get:function(){if(this._orphanedDocuments)return this._orphanedDocuments;throw S("orphanedDocuments is only valid during a transaction.")},enumerable:!0,configurable:!0}),t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.addReference=function(t,e){return this.orphanedDocuments.delete(e),te.resolve()},t.prototype.removeReference=function(t,e){return this.orphanedDocuments.add(e),te.resolve()},t.prototype.removeMutationReference=function(t,e){return this.orphanedDocuments.add(e),te.resolve()},t.prototype.removeTarget=function(t,e){var n=this,r=this.persistence.getQueryCache();return r.getMatchingKeysForTargetId(t,e.targetId).next((function(t){t.forEach((function(t){return n.orphanedDocuments.add(t)}))})).next((function(){return r.removeQueryData(t,e)}))},t.prototype.onTransactionStarted=function(){this._orphanedDocuments=new Set},t.prototype.onTransactionCommitted=function(t){var e=this,n=this.persistence.getRemoteDocumentCache().newChangeBuffer();return te.forEach(this.orphanedDocuments,(function(r){return e.isReferenced(t,r).next((function(t){t||n.removeEntry(r)}))})).next((function(){return e._orphanedDocuments=null,n.apply(t)}))},t.prototype.updateLimboDocument=function(t,e){var n=this;return this.isReferenced(t,e).next((function(t){t?n.orphanedDocuments.delete(e):n.orphanedDocuments.add(e)}))},t.prototype.documentSize=function(t){return 0},t.prototype.isReferenced=function(t,e){var n=this;return te.or([function(){return n.persistence.getQueryCache().containsKey(t,e)},function(){return n.persistence.mutationQueuesContainKey(t,e)},function(){return te.resolve(n.inMemoryPins.containsKey(e))}])},t}(),fr=function(){function t(t,e,n){this.persistence=t,this.serializer=e,this.inMemoryPins=null,this.orphanedSequenceNumbers=new nn((function(t){return Dt(t.path)})),this.garbageCollector=new Wn(this,n)}return t.prototype.onTransactionStarted=function(){},t.prototype.onTransactionCommitted=function(t){return te.resolve()},t.prototype.forEachTarget=function(t,e){return this.persistence.getQueryCache().forEachTarget(t,e)},t.prototype.getSequenceNumberCount=function(t){var e=this.orphanedDocumentCount(t);return this.persistence.getQueryCache().getTargetCount(t).next((function(t){return e.next((function(e){return t+e}))}))},t.prototype.orphanedDocumentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,(function(t){e++})).next((function(){return e}))},t.prototype.forEachOrphanedDocumentSequenceNumber=function(t,e){var n=this;return te.forEach(this.orphanedSequenceNumbers,(function(r,o){return n.isPinned(t,r,o).next((function(t){return t?te.resolve():e(o)}))}))},t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.removeTargets=function(t,e,n){return this.persistence.getQueryCache().removeTargets(t,e,n)},t.prototype.removeOrphanedDocuments=function(t,e){var n=this,r=0,o=this.persistence.getRemoteDocumentCache(),c=o.newChangeBuffer();return o.forEachDocumentKey(t,(function(o){return n.isPinned(t,o,e).next((function(t){t||(r++,c.removeEntry(o))}))})).next((function(){return c.apply(t)})).next((function(){return r}))},t.prototype.removeMutationReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),te.resolve()},t.prototype.removeTarget=function(t,e){var n=e.withSequenceNumber(t.currentSequenceNumber);return this.persistence.getQueryCache().updateQueryData(t,n)},t.prototype.addReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),te.resolve()},t.prototype.removeReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),te.resolve()},t.prototype.updateLimboDocument=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),te.resolve()},t.prototype.documentSize=function(t){var e,n=this.serializer.toDbRemoteDocument(t);if(n.document)e=n.document;else if(n.unknownDocument)e=n.unknownDocument;else{if(!n.noDocument)throw S("Unknown remote document type");e=n.noDocument}return JSON.stringify(e).length},t.prototype.isPinned=function(t,e,n){var r=this;return te.or([function(){return r.persistence.mutationQueuesContainKey(t,e)},function(){return te.resolve(r.inMemoryPins.containsKey(e))},function(){return r.persistence.getQueryCache().containsKey(t,e)},function(){var t=r.orphanedSequenceNumbers.get(e);return te.resolve(void 0!==t&&t>n)}])},t.prototype.getCacheSize=function(t){return this.persistence.getRemoteDocumentCache().getSize(t)},t}(),pr=Number,dr=pr.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),yr=pr.MAX_SAFE_INTEGER||Math.pow(2,53)-1,mr=pr.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function gr(t){return null==t}function vr(t){return mr(t)&&t<=yr&&t>=dr}var _r,wr=1e3,Er=1.5,Tr=6e4,Sr=function(){function t(t,e,n,r,o){void 0===n&&(n=wr),void 0===r&&(r=Er),void 0===o&&(o=Tr),this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=o,this.currentBaseMs=0,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndRun=function(t){var e=this;this.cancel();var n=Math.floor(this.currentBaseMs+this.jitterDelayMs()),r=Math.max(0,Date.now()-this.lastAttemptTime),o=Math.max(0,n-r);this.currentBaseMs>0&&w("ExponentialBackoff","Backing off for "+o+" ms (base delay: "+this.currentBaseMs+" ms, delay with jitter: "+n+" ms, last attempt: "+r+" ms ago)"),this.timerPromise=this.queue.enqueueAfterDelay(this.timerId,o,(function(){return e.lastAttemptTime=Date.now(),t()})),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},t.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}();!function(t){t[t.Initial=0]="Initial",t[t.Starting=1]="Starting",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff"}(_r||(_r={}));var Cr,Ir,Nr=function(){function t(t,e,n,r,o,c){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=o,this.listener=c,this.state=_r.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new Sr(t,e)}return t.prototype.isStarted=function(){return this.state===_r.Starting||this.state===_r.Open||this.state===_r.Backoff},t.prototype.isOpen=function(){return this.state===_r.Open},t.prototype.start=function(){this.state!==_r.Error?(C(this.state===_r.Initial,"Already started"),this.auth()):this.performBackoff()},t.prototype.stop=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return this.isStarted()?[4,this.close(_r.Initial)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},t.prototype.inhibitBackoff=function(){C(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=_r.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,(function(){return t.handleIdleCloseTimer()})))},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){return this.isOpen()?[2,this.close(_r.Initial)]:[2]}))}))},t.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},t.prototype.close=function(t,e){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(n){switch(n.label){case 0:return C(this.isStarted(),"Only started streams should be closed."),C(t===_r.Error||gr(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,t!==_r.Error?this.backoff.reset():e&&e.code===A.RESOURCE_EXHAUSTED?(E(e.toString()),E("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):e&&e.code===A.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t,[4,this.listener.onClose(e)];case 1:return n.sent(),[2]}}))}))},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;C(this.state===_r.Initial,"Must be in initial state to auth"),this.state=_r.Starting;var e=this.getCloseGuardedDispatcher(this.closeCount),n=this.closeCount;this.credentialsProvider.getToken().then((function(e){t.closeCount===n&&t.startStream(e)}),(function(n){e((function(){var e=new D(A.UNKNOWN,"Fetching auth token failed: "+n.message);return t.handleStreamClose(e)}))}))},t.prototype.startStream=function(t){var e=this;C(this.state===_r.Starting,"Trying to start stream in a non-starting state");var n=this.getCloseGuardedDispatcher(this.closeCount);this.stream=this.startRpc(t),this.stream.onOpen((function(){n((function(){return C(e.state===_r.Starting,"Expected stream to be in state Starting, but was "+e.state),e.state=_r.Open,e.listener.onOpen()}))})),this.stream.onClose((function(t){n((function(){return e.handleStreamClose(t)}))})),this.stream.onMessage((function(t){n((function(){return e.onMessage(t)}))}))},t.prototype.performBackoff=function(){var t=this;C(this.state===_r.Error,"Should only perform backoff when in Error state"),this.state=_r.Backoff,this.backoff.backoffAndRun((function(){return l.__awaiter(t,void 0,void 0,(function(){return l.__generator(this,(function(t){return C(this.state===_r.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=_r.Initial,this.start(),C(this.isStarted(),"PersistentStream should have started"),[2]}))}))}))},t.prototype.handleStreamClose=function(t){return C(this.isStarted(),"Can't handle server close on non-started stream"),w("PersistentStream","close with error: "+t),this.stream=null,this.close(_r.Error,t)},t.prototype.getCloseGuardedDispatcher=function(t){var e=this;return function(n){e.queue.enqueueAndForget((function(){return e.closeCount===t?n():(w("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())}))}},t}(),Ar=function(t){function e(e,n,r,o,c){var h=t.call(this,e,ct.ListenStreamConnectionBackoff,ct.ListenStreamIdle,n,r,c)||this;return h.serializer=o,h}return l.__extends(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.sendRequest(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},e}(Nr),Dr=function(t){function e(e,n,r,o,c){var h=t.call(this,e,ct.WriteStreamConnectionBackoff,ct.WriteStreamIdle,n,r,c)||this;return h.serializer=o,h.handshakeComplete_=!1,h.lastStreamToken=N(),h}return l.__extends(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.handshakeComplete_=!1,t.prototype.start.call(this)},e.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(C(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.handshakeComplete_){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults,t.commitTime),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return C(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){C(this.isOpen(),"Writing handshake requires an opened stream"),C(!this.handshakeComplete_,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;C(this.isOpen(),"Writing mutations requires an opened stream"),C(this.handshakeComplete_,"Handshake must be complete before writing mutations"),C(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map((function(t){return e.serializer.toMutation(t)}))};this.sendRequest(n)},e}(Nr),kr=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentials=n,this.serializer=r}return t.prototype.newPersistentWriteStream=function(t){return new Dr(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.newPersistentWatchStream=function(t){return new Ar(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,writes:t.map((function(t){return e.serializer.toMutation(t)}))};return this.invokeRPC("Commit",n).then((function(t){return e.serializer.fromWriteResults(t.writeResults,t.commitTime)}))},t.prototype.lookup=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,documents:t.map((function(t){return e.serializer.toName(t)}))};return this.invokeStreamingRPC("BatchGetDocuments",n).then((function(n){var r=jt();n.forEach((function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)}));var o=[];return t.forEach((function(t){var e=r.get(t);C(!!e,"Missing entity in write response for "+t),o.push(e)})),o}))},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken().then((function(r){return n.connection.invokeRPC(t,e,r)})).catch((function(t){throw t.code===A.UNAUTHENTICATED&&n.credentials.invalidateToken(),t}))},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken().then((function(r){return n.connection.invokeStreamingRPC(t,e,r)})).catch((function(t){throw t.code===A.UNAUTHENTICATED&&n.credentials.invalidateToken(),t}))},t}(),Rr=function(){function t(t){this.datastore=t,this.readVersions=Gt(),this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}return t.prototype.lookup=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n=this;return l.__generator(this,(function(r){switch(r.label){case 0:if(this.ensureCommitNotCalled(),this.mutations.length>0)throw new D(A.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");return[4,this.datastore.lookup(t)];case 1:return(e=r.sent()).forEach((function(t){t instanceof tn||t instanceof Ze?n.recordVersion(t):S("Document in a transaction was a "+t.constructor.name)})),[2,e]}}))}))},t.prototype.set=function(t,data){this.write(data.toMutations(t,this.precondition(t))),this.writtenDocs.add(t)},t.prototype.update=function(t,data){try{this.write(data.toMutations(t,this.preconditionForUpdate(t)))}catch(t){this.lastWriteError=t}this.writtenDocs.add(t)},t.prototype.delete=function(t){this.write([new Le(t,this.precondition(t))]),this.writtenDocs.add(t)},t.prototype.commit=function(){return l.__awaiter(this,void 0,void 0,(function(){var t;return l.__generator(this,(function(e){switch(e.label){case 0:if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;if(t=this.readVersions,this.mutations.forEach((function(e){t=t.remove(e.key)})),!t.isEmpty())throw new D(A.INVALID_ARGUMENT,"Every document read in a transaction must also be written.");return[4,this.datastore.commit(this.mutations)];case 1:return e.sent(),this.committed=!0,[2]}}))}))},t.prototype.recordVersion=function(t){var e;if(t instanceof Ze)e=t.version;else{if(!(t instanceof tn))throw S("Document in a transaction was a "+t.constructor.name);e=xt.forDeletedDoc()}var n=this.readVersions.get(t.key);if(null!==n){if(!e.isEqual(n))throw new D(A.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return!this.writtenDocs.has(t)&&e?ke.updateTime(e):ke.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(!this.writtenDocs.has(t)&&e){if(e.isEqual(xt.forDeletedDoc()))throw new D(A.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return ke.updateTime(e)}return ke.exists(!0)},t.prototype.write=function(t){this.ensureCommitNotCalled(),this.mutations=this.mutations.concat(t)},t.prototype.ensureCommitNotCalled=function(){C(!this.committed,"A transaction object cannot be used after its update callback has been invoked.")},t}();!function(t){t[t.Unknown=0]="Unknown",t[t.Online=1]="Online",t[t.Offline=2]="Offline"}(Cr||(Cr={})),function(t){t[t.RemoteStore=0]="RemoteStore",t[t.SharedClientState=1]="SharedClientState"}(Ir||(Ir={}));var Or,Pr=function(){function t(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state=Cr.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return t.prototype.handleWatchStreamStart=function(){var t=this;0===this.watchStreamFailures&&(this.setAndBroadcast(Cr.Unknown),C(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(ct.OnlineStateTimeout,1e4,(function(){return t.onlineStateTimer=null,C(t.state===Cr.Unknown,"Timer should be canceled if we transitioned to a different state."),t.logClientOfflineWarningIfNecessary("Backend didn't respond within 10 seconds."),t.setAndBroadcast(Cr.Offline),Promise.resolve()})))},t.prototype.handleWatchStreamFailure=function(t){this.state===Cr.Online?(this.setAndBroadcast(Cr.Unknown),C(0===this.watchStreamFailures,"watchStreamFailures must be 0"),C(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,this.watchStreamFailures>=1&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed 1 times. Most recent error: "+t.toString()),this.setAndBroadcast(Cr.Offline)))},t.prototype.set=function(t){this.clearOnlineStateTimer(),this.watchStreamFailures=0,t===Cr.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(t)},t.prototype.setAndBroadcast=function(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))},t.prototype.logClientOfflineWarningIfNecessary=function(details){var t="Could not reach Cloud Firestore backend. "+details+"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.";this.shouldWarnClientIsOffline?(E(t),this.shouldWarnClientIsOffline=!1):w("OnlineStateTracker",t)},t.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},t}();function xr(code){switch(code){case A.OK:return S("Treated status OK as error");case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return S("Unknown status code: "+code)}}function Lr(code){if(void 0===code)return E("GRPC error has no .code"),A.UNKNOWN;switch(code){case Or.OK:return A.OK;case Or.CANCELLED:return A.CANCELLED;case Or.UNKNOWN:return A.UNKNOWN;case Or.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case Or.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case Or.INTERNAL:return A.INTERNAL;case Or.UNAVAILABLE:return A.UNAVAILABLE;case Or.UNAUTHENTICATED:return A.UNAUTHENTICATED;case Or.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case Or.NOT_FOUND:return A.NOT_FOUND;case Or.ALREADY_EXISTS:return A.ALREADY_EXISTS;case Or.PERMISSION_DENIED:return A.PERMISSION_DENIED;case Or.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case Or.ABORTED:return A.ABORTED;case Or.OUT_OF_RANGE:return A.OUT_OF_RANGE;case Or.UNIMPLEMENTED:return A.UNIMPLEMENTED;case Or.DATA_LOSS:return A.DATA_LOSS;default:return S("Unknown status code: "+code)}}function Mr(code){if(void 0===code)return Or.OK;switch(code){case A.OK:return Or.OK;case A.CANCELLED:return Or.CANCELLED;case A.UNKNOWN:return Or.UNKNOWN;case A.DEADLINE_EXCEEDED:return Or.DEADLINE_EXCEEDED;case A.RESOURCE_EXHAUSTED:return Or.RESOURCE_EXHAUSTED;case A.INTERNAL:return Or.INTERNAL;case A.UNAVAILABLE:return Or.UNAVAILABLE;case A.UNAUTHENTICATED:return Or.UNAUTHENTICATED;case A.INVALID_ARGUMENT:return Or.INVALID_ARGUMENT;case A.NOT_FOUND:return Or.NOT_FOUND;case A.ALREADY_EXISTS:return Or.ALREADY_EXISTS;case A.PERMISSION_DENIED:return Or.PERMISSION_DENIED;case A.FAILED_PRECONDITION:return Or.FAILED_PRECONDITION;case A.ABORTED:return Or.ABORTED;case A.OUT_OF_RANGE:return Or.OUT_OF_RANGE;case A.UNIMPLEMENTED:return Or.UNIMPLEMENTED;case A.DATA_LOSS:return Or.DATA_LOSS;default:return S("Unknown status code: "+code)}}!function(t){t[t.OK=0]="OK",t[t.CANCELLED=1]="CANCELLED",t[t.UNKNOWN=2]="UNKNOWN",t[t.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",t[t.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",t[t.NOT_FOUND=5]="NOT_FOUND",t[t.ALREADY_EXISTS=6]="ALREADY_EXISTS",t[t.PERMISSION_DENIED=7]="PERMISSION_DENIED",t[t.UNAUTHENTICATED=16]="UNAUTHENTICATED",t[t.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",t[t.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",t[t.ABORTED=10]="ABORTED",t[t.OUT_OF_RANGE=11]="OUT_OF_RANGE",t[t.UNIMPLEMENTED=12]="UNIMPLEMENTED",t[t.INTERNAL=13]="INTERNAL",t[t.UNAVAILABLE=14]="UNAVAILABLE",t[t.DATA_LOSS=15]="DATA_LOSS"}(Or||(Or={}));var Fr,Ur,qr=function(){function t(t){this.comparator=t?function(e,n){return t(e,n)||wt.comparator(e.key,n.key)}:function(t,e){return wt.comparator(t.key,e.key)},this.keyedMap=Kt(),this.sortedSet=new Lt(this.comparator)}return t.emptySet=function(e){return new t(e.comparator)},t.prototype.has=function(t){return null!=this.keyedMap.get(t)},t.prototype.get=function(t){return this.keyedMap.get(t)},t.prototype.first=function(){return this.sortedSet.minKey()},t.prototype.last=function(){return this.sortedSet.maxKey()},t.prototype.isEmpty=function(){return this.sortedSet.isEmpty()},t.prototype.indexOf=function(t){var e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1},Object.defineProperty(t.prototype,"size",{get:function(){return this.sortedSet.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t){this.sortedSet.inorderTraversal((function(e,n){return t(e),!1}))},t.prototype.add=function(t){var e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))},t.prototype.delete=function(t){var e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();n.hasNext();){var o=n.getNext().key,c=r.getNext().key;if(!o.isEqual(c))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach((function(e){t.push(e.toString())})),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"},t.prototype.copy=function(e,n){var r=new t;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=n,r},t}();!function(t){t[t.Added=0]="Added",t[t.Removed=1]="Removed",t[t.Modified=2]="Modified",t[t.Metadata=3]="Metadata"}(Fr||(Fr={})),function(t){t[t.Local=0]="Local",t[t.Synced=1]="Synced"}(Ur||(Ur={}));var Vr,Br=function(){function t(){this.changeMap=new Lt(wt.comparator)}return t.prototype.track=function(t){var e=t.doc.key,n=this.changeMap.get(e);n?t.type!==Fr.Added&&n.type===Fr.Metadata?this.changeMap=this.changeMap.insert(e,t):t.type===Fr.Metadata&&n.type!==Fr.Removed?this.changeMap=this.changeMap.insert(e,{type:n.type,doc:t.doc}):t.type===Fr.Modified&&n.type===Fr.Modified?this.changeMap=this.changeMap.insert(e,{type:Fr.Modified,doc:t.doc}):t.type===Fr.Modified&&n.type===Fr.Added?this.changeMap=this.changeMap.insert(e,{type:Fr.Added,doc:t.doc}):t.type===Fr.Removed&&n.type===Fr.Added?this.changeMap=this.changeMap.remove(e):t.type===Fr.Removed&&n.type===Fr.Modified?this.changeMap=this.changeMap.insert(e,{type:Fr.Removed,doc:n.doc}):t.type===Fr.Added&&n.type===Fr.Removed?this.changeMap=this.changeMap.insert(e,{type:Fr.Modified,doc:t.doc}):S("unsupported combination of changes: "+JSON.stringify(t)+" after "+JSON.stringify(n)):this.changeMap=this.changeMap.insert(e,t)},t.prototype.getChanges=function(){var t=[];return this.changeMap.inorderTraversal((function(e,n){t.push(n)})),t},t}(),jr=function(){function t(t,e,n,r,o,c,h,l){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=o,this.fromCache=c,this.syncStateChanged=h,this.excludesMetadataChanges=l}return t.fromInitialDocuments=function(e,n,r,o){var c=[];return n.forEach((function(t){c.push({type:Fr.Added,doc:t})})),new t(e,n,qr.emptySet(n),c,r,o,!0,!1)},Object.defineProperty(t.prototype,"hasPendingWrites",{get:function(){return!this.mutatedKeys.isEmpty()},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&this.query.isEqual(t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;var e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(var i=0;i0&&(this._hasPendingChanges=!0,this._resumeToken=t)},t.prototype.toTargetChange=function(){var t=Yt(),e=Yt(),n=Yt();return this.documentChanges.forEach((function(r,o){switch(o){case Fr.Added:t=t.add(r);break;case Fr.Modified:e=e.add(r);break;case Fr.Removed:n=n.add(r);break;default:S("Encountered invalid change type: "+o)}})),new Qr(this._resumeToken,this._current,t,e,n)},t.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=Jr()},t.prototype.addDocumentChange=function(t,e){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.insert(t,e)},t.prototype.removeDocumentChange=function(t){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.remove(t)},t.prototype.recordPendingTargetRequest=function(){this.pendingResponses+=1},t.prototype.recordTargetResponse=function(){this.pendingResponses-=1},t.prototype.markCurrent=function(){this._hasPendingChanges=!0,this._current=!0},t}(),Yr=function(){function t(t){this.metadataProvider=t,this.targetStates={},this.pendingDocumentUpdates=jt(),this.pendingDocumentTargetMapping=Xr(),this.pendingTargetResets=new qt(it)}return t.prototype.handleDocumentChange=function(t){for(var e=0,n=t.updatedTargetIds;e0?t.targetIds.forEach(e):P(this.targetStates,e)},t.prototype.handleExistenceFilter=function(t){var e=t.targetId,n=t.existenceFilter.count,r=this.queryDataForActiveTarget(e);if(r){var o=r.query;if(o.isDocumentQuery())if(0===n){var c=new wt(o.path);this.removeDocumentFromTarget(e,c,new tn(c,xt.forDeletedDoc()))}else C(1===n,"Single document existence filter with count: "+n);else this.getCurrentDocumentCountForTarget(e)!==n&&(this.resetTarget(e),this.pendingTargetResets=this.pendingTargetResets.add(e))}},t.prototype.createRemoteEvent=function(t){var e=this,n={};P(this.targetStates,(function(r,o){var c=e.queryDataForActiveTarget(r);if(c){if(o.current&&c.query.isDocumentQuery()){var h=new wt(c.query.path);null!==e.pendingDocumentUpdates.get(h)||e.targetContainsDocument(r,h)||e.removeDocumentFromTarget(r,h,new tn(h,t))}o.hasPendingChanges&&(n[r]=o.toTargetChange(),o.clearPendingChanges())}}));var r=Yt();this.pendingDocumentTargetMapping.forEach((function(t,n){var o=!0;n.forEachWhile((function(t){var n=e.queryDataForActiveTarget(t);return!n||n.purpose===On.LimboResolution||(o=!1,!1)})),o&&(r=r.add(t))}));var o=new Wr(t,n,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=jt(),this.pendingDocumentTargetMapping=Xr(),this.pendingTargetResets=new qt(it),o},t.prototype.addDocumentToTarget=function(t,e){if(this.isActiveTarget(t)){var n=this.targetContainsDocument(t,e.key)?Fr.Modified:Fr.Added;this.ensureTargetState(t).addDocumentChange(e.key,n),this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e.key,e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e.key,this.ensureDocumentTargetMapping(e.key).add(t))}},t.prototype.removeDocumentFromTarget=function(t,e,n){if(this.isActiveTarget(t)){var r=this.ensureTargetState(t);this.targetContainsDocument(t,e)?r.addDocumentChange(e,Fr.Removed):r.removeDocumentChange(e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,this.ensureDocumentTargetMapping(e).delete(t)),n&&(this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e,n))}},t.prototype.removeTarget=function(t){delete this.targetStates[t]},t.prototype.getCurrentDocumentCountForTarget=function(t){var e=this.ensureTargetState(t).toTargetChange();return this.metadataProvider.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size},t.prototype.recordPendingTargetRequest=function(t){this.ensureTargetState(t).recordPendingTargetRequest()},t.prototype.ensureTargetState=function(t){return this.targetStates[t]||(this.targetStates[t]=new zr),this.targetStates[t]},t.prototype.ensureDocumentTargetMapping=function(t){var e=this.pendingDocumentTargetMapping.get(t);return e||(e=new qt(it),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t,e)),e},t.prototype.isActiveTarget=function(t){var e=null!==this.queryDataForActiveTarget(t);return e||w("WatchChangeAggregator","Detected inactive target",t),e},t.prototype.queryDataForActiveTarget=function(t){var e=this.targetStates[t];return e&&e.isPending?null:this.metadataProvider.getQueryDataForTarget(t)},t.prototype.resetTarget=function(t){var e=this;C(!this.targetStates[t].isPending,"Should only reset active targets"),this.targetStates[t]=new zr,this.metadataProvider.getRemoteKeysForTarget(t).forEach((function(n){e.removeDocumentFromTarget(t,n,null)}))},t.prototype.targetContainsDocument=function(t,e){return this.metadataProvider.getRemoteKeysForTarget(t).has(e)},t}();function Xr(){return new Lt(wt.comparator)}function Jr(){return new Lt(wt.comparator)}var $r="RemoteStore",Zr=function(){function t(t,e,n,r,o){var c=this;this.localStore=t,this.datastore=e,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.connectivityMonitor=o,this.connectivityMonitor.addCallback((function(t){n.enqueueAndForget((function(){return l.__awaiter(c,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return this.canUseNetwork()?(w($r,"Restarting streams for network reachability change."),[4,this.restartNetwork()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))}))})),this.onlineStateTracker=new Pr(n,r),this.watchStream=this.datastore.newPersistentWatchStream({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.writeStream=this.datastore.newPersistentWriteStream({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.enableNetwork=function(){return l.__awaiter(this,void 0,void 0,(function(){var t;return l.__generator(this,(function(e){switch(e.label){case 0:return this.networkEnabled=!0,this.canUseNetwork()?(t=this.writeStream,[4,this.localStore.getLastStreamToken()]):[3,3];case 1:return t.lastStreamToken=e.sent(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(Cr.Unknown),[4,this.fillWritePipeline()];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},t.prototype.disableNetwork=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Cr.Offline),[2]}}))}))},t.prototype.disableNetworkInternal=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return[4,this.writeStream.stop()];case 1:return t.sent(),[4,this.watchStream.stop()];case 2:return t.sent(),this.writePipeline.length>0&&(w($r,"Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}}))}))},t.prototype.shutdown=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return w($r,"RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.connectivityMonitor.shutdown(),this.onlineStateTracker.set(Cr.Unknown),[2]}}))}))},t.prototype.listen=function(t){C(!R(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){C(R(this.listenTargets,t),"unlisten called without assigned target ID!"),delete this.listenTargets[t],this.watchStream.isOpen()&&this.sendUnwatchRequest(t),L(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(Cr.Unknown))},t.prototype.getQueryDataForTarget=function(t){return this.listenTargets[t]||null},t.prototype.getRemoteKeysForTarget=function(t){return this.syncEngine.getRemoteKeysForTarget(t)},t.prototype.sendWatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.startWatchStream=function(){C(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new Yr(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},t.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!L(this.listenTargets)},t.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},t.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},t.prototype.onWatchStreamOpen=function(){return l.__awaiter(this,void 0,void 0,(function(){var t=this;return l.__generator(this,(function(e){return P(this.listenTargets,(function(e,n){t.sendWatchRequest(n)})),[2]}))}))},t.prototype.onWatchStreamClose=function(t){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(e){return void 0===t&&C(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(t),this.startWatchStream()):this.onlineStateTracker.set(Cr.Unknown),[2]}))}))},t.prototype.onWatchStreamChange=function(t,e){return l.__awaiter(this,void 0,void 0,(function(){var n;return l.__generator(this,(function(r){switch(r.label){case 0:return this.onlineStateTracker.set(Cr.Online),t instanceof Gr&&t.state===Vr.Removed&&t.cause?[2,this.handleTargetError(t)]:(t instanceof Kr?this.watchChangeAggregator.handleDocumentChange(t):t instanceof Hr?this.watchChangeAggregator.handleExistenceFilter(t):(C(t instanceof Gr,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(t)),e.isEqual(xt.MIN)?[3,3]:[4,this.localStore.getLastRemoteSnapshotVersion()]);case 1:return n=r.sent(),e.compareTo(n)>=0?[4,this.raiseWatchSnapshot(e)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},t.prototype.raiseWatchSnapshot=function(t){var e=this;C(!t.isEqual(xt.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.watchChangeAggregator.createRemoteEvent(t);return P(n.targetChanges,(function(n,r){if(r.resumeToken.length>0){var o=e.listenTargets[n];o&&(e.listenTargets[n]=o.withResumeToken(r.resumeToken,t))}})),n.targetMismatches.forEach((function(t){var n=e.listenTargets[t];if(n){e.listenTargets[t]=n.withResumeToken(N(),n.snapshotVersion),e.sendUnwatchRequest(t);var r=new Mn(n.query,t,On.ExistenceFilterMismatch,n.sequenceNumber);e.sendWatchRequest(r)}})),this.syncEngine.applyRemoteEvent(n)},t.prototype.handleTargetError=function(t){var e=this;C(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach((function(t){r=r.then((function(){return l.__awaiter(e,void 0,void 0,(function(){return l.__generator(this,(function(e){return R(this.listenTargets,t)?(delete this.listenTargets[t],this.watchChangeAggregator.removeTarget(t),[2,this.syncEngine.rejectListen(t,n)]):[2]}))}))}))})),r},t.prototype.fillWritePipeline=function(){return l.__awaiter(this,void 0,void 0,(function(){var t,e;return l.__generator(this,(function(n){switch(n.label){case 0:return this.canAddToWritePipeline()?(t=this.writePipeline.length>0?this.writePipeline[this.writePipeline.length-1].batchId:-1,[4,this.localStore.nextMutationBatch(t)]):[3,4];case 1:return null!==(e=n.sent())?[3,2]:(0===this.writePipeline.length&&this.writeStream.markIdle(),[3,4]);case 2:return this.addToWritePipeline(e),[4,this.fillWritePipeline()];case 3:n.sent(),n.label=4;case 4:return this.shouldStartWriteStream()&&this.startWriteStream(),[2]}}))}))},t.prototype.canAddToWritePipeline=function(){return this.canUseNetwork()&&this.writePipeline.length<10},t.prototype.outstandingWrites=function(){return this.writePipeline.length},t.prototype.addToWritePipeline=function(t){C(this.canAddToWritePipeline(),"addToWritePipeline called when pipeline is full"),this.writePipeline.push(t),this.writeStream.isOpen()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.canUseNetwork()&&!this.writeStream.isStarted()&&this.writePipeline.length>0},t.prototype.startWriteStream=function(){C(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},t.prototype.onWriteStreamOpen=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){return this.writeStream.writeHandshake(),[2]}))}))},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then((function(){for(var e=0,n=t.writePipeline;e0,"Got result for empty write pipeline");var r=this.writePipeline.shift(),o=Zt.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(o).then((function(){return n.fillWritePipeline()}))},t.prototype.onWriteStreamClose=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e=this;return l.__generator(this,(function(n){return void 0===t&&C(!this.shouldStartWriteStream(),"Write stream was stopped gracefully while still needed."),t&&this.writePipeline.length>0?(void 0,[2,(this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t)).then((function(){e.shouldStartWriteStream()&&e.startWriteStream()}))]):[2]}))}))},t.prototype.handleHandshakeError=function(t){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(e){return xr(t.code)?(w($r,"RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=N(),[2,this.localStore.setLastStreamToken(N()).catch(Yn)]):[2]}))}))},t.prototype.handleWriteError=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n=this;return l.__generator(this,(function(r){return xr(code=t.code)&&code!==A.ABORTED?(e=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(e.batchId,t).then((function(){return n.fillWritePipeline()}))]):[2];var code}))}))},t.prototype.createTransaction=function(){return new Rr(this.datastore)},t.prototype.restartNetwork=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Cr.Unknown),[4,this.enableNetwork()];case 2:return t.sent(),[2]}}))}))},t.prototype.handleCredentialChange=function(){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(t){switch(t.label){case 0:return this.canUseNetwork()?(w($r,"RemoteStore restarting streams for new credential"),[4,this.restartNetwork()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},t.prototype.applyPrimaryState=function(t){return l.__awaiter(this,void 0,void 0,(function(){return l.__generator(this,(function(e){switch(e.label){case 0:return this.isPrimary=t,t&&this.networkEnabled?[4,this.enableNetwork()]:[3,2];case 1:return e.sent(),[3,4];case 2:return t?[3,4]:[4,this.disableNetworkInternal()];case 3:e.sent(),this.onlineStateTracker.set(Cr.Unknown),e.label=4;case 4:return[2]}}))}))},t}(),ti=function(){function t(t,e){if(F("GeoPoint",arguments,2),B("GeoPoint","number",1,t),B("GeoPoint","number",2,e),!isFinite(t)||t<-90||t>90)throw new D(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new D(A.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this._long},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){return this._lat===t._lat&&this._long===t._long},t.prototype._compareTo=function(t){return it(this._lat,t._lat)||it(this._long,t._long)},t}(),ei=function(){function t(path,t,e,n,r,o,c){void 0===t&&(t=null),void 0===e&&(e=[]),void 0===n&&(n=[]),void 0===r&&(r=null),void 0===o&&(o=null),void 0===c&&(c=null),this.path=path,this.collectionGroup=t,this.explicitOrderBy=e,this.filters=n,this.limit=r,this.startAt=o,this.endAt=c,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return t.atPath=function(path){return new t(path)},Object.defineProperty(t.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var t=this.getInequalityFilterField(),e=this.getFirstOrderByField();if(null!==t&&null===e)t.isKeyField()?this.memoizedOrderBy=[di]:this.memoizedOrderBy=[new pi(t),di];else{C(null===t||null!==e&&t.isEqual(e),"First orderBy should match inequality field."),this.memoizedOrderBy=[];for(var n=!1,r=0,o=this.explicitOrderBy;r0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:hi.ASCENDING;this.memoizedOrderBy.push(h===hi.ASCENDING?di:yi)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(filter){C(null==this.getInequalityFilterField()||!(filter instanceof ii)||!filter.isInequality()||filter.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),C(!this.isDocumentQuery(),"No filtering allowed for document query");var e=this.filters.concat([filter]);return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),e,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){C(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,this.collectionGroup,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.asCollectionQueryAtPath=function(path){return new t(path,null,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();this.isCollectionGroupQuery()&&(t+="|cg:"+this.collectionGroup),t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),gr(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var i=0;i0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=0)return filter.op}return null},t.prototype.isDocumentQuery=function(){return wt.isDocumentKey(this.path)&&null===this.collectionGroup&&0===this.filters.length},t.prototype.isCollectionGroupQuery=function(){return null!==this.collectionGroup},t.prototype.matchesPathAndCollectionGroup=function(t){var e=t.key.path;return null!==this.collectionGroup?t.key.hasCollectionId(this.collectionGroup)&&this.path.isPrefixOf(e):wt.isDocumentKey(this.path)?this.path.isEqual(e):this.path.isImmediateParentOf(e)},t.prototype.matchesOrderBy=function(t){for(var e=0,n=this.explicitOrderBy;e=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;case"array-contains":return t.ARRAY_CONTAINS;case"in":return t.IN;case"array-contains-any":return t.ARRAY_CONTAINS_ANY;default:return S("Unknown FieldFilter operator: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.isEqual=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t.ARRAY_CONTAINS=new t("array-contains"),t.IN=new t("in"),t.ARRAY_CONTAINS_ANY=new t("array-contains-any"),t}(),ii=function(t){function e(e,n,r){var o=t.call(this)||this;return o.field=e,o.op=n,o.value=r,o}return l.__extends(e,t),e.create=function(t,n,r){if(t.isKeyField())return n===ri.IN?(C(r instanceof Je,"Comparing on key with IN, but filter value not an ArrayValue"),C(r.internalValue.every((function(t){return t instanceof ze})),"Comparing on key with IN, but an array value was not a RefValue"),new ai(t,r)):(C(r instanceof ze,"Comparing on key, but filter value not a RefValue"),C(n!==ri.ARRAY_CONTAINS&&n!==ri.ARRAY_CONTAINS_ANY,"'"+n.toString()+"' queries don't make sense on document keys."),new oi(t,n,r));if(r.isEqual(Ue.INSTANCE)){if(n!==ri.EQUAL)throw new D(A.INVALID_ARGUMENT,"Invalid query. Null supports only equality comparisons.");return new e(t,n,r)}if(r.isEqual(We.NAN)){if(n!==ri.EQUAL)throw new D(A.INVALID_ARGUMENT,"Invalid query. NaN supports only equality comparisons.");return new e(t,n,r)}return n===ri.ARRAY_CONTAINS?new si(t,r):n===ri.IN?(C(r instanceof Je,"IN filter has invalid value: "+r.toString()),new ui(t,r)):n===ri.ARRAY_CONTAINS_ANY?(C(r instanceof Je,"ARRAY_CONTAINS_ANY filter has invalid value: "+r.toString()),new ci(t,r)):new e(t,n,r)},e.prototype.matches=function(t){var e=t.field(this.field);return null!==e&&this.value.typeOrder===e.typeOrder&&this.matchesComparison(e.compareTo(this.value))},e.prototype.matchesComparison=function(t){switch(this.op){case ri.LESS_THAN:return t<0;case ri.LESS_THAN_OR_EQUAL:return t<=0;case ri.EQUAL:return 0===t;case ri.GREATER_THAN:return t>0;case ri.GREATER_THAN_OR_EQUAL:return t>=0;default:return S("Unknown FieldFilter operator: "+this.op)}},e.prototype.isInequality=function(){return[ri.LESS_THAN,ri.LESS_THAN_OR_EQUAL,ri.GREATER_THAN,ri.GREATER_THAN_OR_EQUAL].indexOf(this.op)>=0},e.prototype.canonicalId=function(){return this.field.canonicalString()+this.op.toString()+this.value.toString()},e.prototype.isEqual=function(t){return t instanceof e&&(this.op.isEqual(t.op)&&this.field.isEqual(t.field)&&this.value.isEqual(t.value))},e.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},e}(ni),oi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=wt.comparator(t.key,e.key);return this.matchesComparison(n)},e}(ii),ai=function(t){function e(e,n){var r=t.call(this,e,ri.IN,n)||this;return r.value=n,r}return l.__extends(e,t),e.prototype.matches=function(t){return this.value.internalValue.some((function(e){return t.key.isEqual(e.key)}))},e}(ii),si=function(t){function e(e,n){return t.call(this,e,ri.ARRAY_CONTAINS,n)||this}return l.__extends(e,t),e.prototype.matches=function(t){var e=t.field(this.field);return e instanceof Je&&e.contains(this.value)},e}(ii),ui=function(t){function e(e,n){var r=t.call(this,e,ri.IN,n)||this;return r.value=n,r}return l.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=t.field(this.field);return null!==n&&e.contains(n)},e}(ii),ci=function(t){function e(e,n){var r=t.call(this,e,ri.ARRAY_CONTAINS_ANY,n)||this;return r.value=n,r}return l.__extends(e,t),e.prototype.matches=function(t){var e=this,n=t.field(this.field);return n instanceof Je&&n.internalValue.some((function(t){return e.value.contains(t)}))},e}(ii),hi=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),fi=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e4&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.popFirst(5)},t.prototype.isValidResourceName=function(path){return path.length>=4&&"projects"===path.get(0)&&"databases"===path.get(2)},t.prototype.toValue=function(t){if(t instanceof Ue)return{nullValue:"NULL_VALUE"};if(t instanceof qe)return{booleanValue:t.value()};if(t instanceof je)return{integerValue:""+t.value()};if(t instanceof We){var e=t.value();if(this.options.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof Qe?{stringValue:t.value()}:t instanceof Xe?{mapValue:this.toMapValue(t)}:t instanceof Je?{arrayValue:this.toArrayValue(t)}:t instanceof Ke?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Ye?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof Ge?{bytesValue:this.toBytes(t.value())}:t instanceof ze?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:S("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this;if("nullValue"in t)return Ue.INSTANCE;if("booleanValue"in t)return qe.of(t.booleanValue);if("integerValue"in t)return new je(Ai(t.integerValue));if("doubleValue"in t){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return We.NAN;if("Infinity"===t.doubleValue)return We.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return We.NEGATIVE_INFINITY}return new We(t.doubleValue)}if("stringValue"in t)return new Qe(t.stringValue);if("mapValue"in t)return this.fromFields(t.mapValue.fields||{});if("arrayValue"in t){Ni(t.arrayValue,"arrayValue");var n=t.arrayValue.values||[];return new Je(n.map((function(t){return e.fromValue(t)})))}if("timestampValue"in t)return Ni(t.timestampValue,"timestampValue"),new Ke(this.fromTimestamp(t.timestampValue));if("geoPointValue"in t){Ni(t.geoPointValue,"geoPointValue");var r=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new Ye(new ti(r,o))}if("bytesValue"in t){Ni(t.bytesValue,"bytesValue");var c=this.fromBlob(t.bytesValue);return new Ge(c)}if("referenceValue"in t){Ni(t.referenceValue,"referenceValue");var h=this.fromResourceName(t.referenceValue),l=new yt(h.get(1),h.get(3)),f=new wt(this.extractLocalPathFromResourceName(h));return new ze(l,f)}return S("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return C(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data()),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t,e){var n=this,r=this.fromName(t.name),o=this.fromVersion(t.updateTime);return new Ze(r,o,{hasCommittedMutations:!!e},void 0,t,(function(t){return n.fromValue(t)}))},t.prototype.toFields=function(t){var e=this,n={};return t.forEach((function(t,r){n[t]=e.toValue(r)})),n},t.prototype.fromFields=function(object){var t=this,map=object,e=Xe.EMPTY;return x(map,(function(n,r){e=e.set(new _t([n]),t.fromValue(r))})),e},t.prototype.toMapValue=function(map){return{fields:this.toFields(map)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach((function(t){n.push(e.toValue(t))})),{values:n}},t.prototype.fromFound=function(t){var e=this;C(!!t.found,"Tried to deserialize a found document from a missing document."),Ni(t.found.name,"doc.found.name"),Ni(t.found.updateTime,"doc.found.updateTime");var n=this.fromName(t.found.name),r=this.fromVersion(t.found.updateTime);return new Ze(n,r,{},void 0,t.found,(function(t){return e.fromValue(t)}))},t.prototype.fromMissing=function(t){C(!!t.missing,"Tried to deserialize a missing document from a found document."),C(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new tn(e,n)},t.prototype.fromMaybeDocument=function(t){return"found"in t?this.fromFound(t):"missing"in t?this.fromMissing(t):S("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case Vr.Added:return"ADD";case Vr.Current:return"CURRENT";case Vr.NoChange:return"NO_CHANGE";case Vr.Removed:return"REMOVE";case Vr.Reset:return"RESET";default:return S("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof Hr)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof Kr){if(t.newDoc instanceof Ze){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data()),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof tn){e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof Gr){var n=void 0;return t.cause&&(n={code:Mr(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return S("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=this;if("targetChange"in t){Ni(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),o=t.targetChange.targetIds||[],c=t.targetChange.resumeToken||this.emptyByteString(),h=t.targetChange.cause,l=h&&this.fromRpcStatus(h);e=new Gr(r,o,c,l||null)}else if("documentChange"in t){Ni(t.documentChange,"documentChange"),Ni(t.documentChange.document,"documentChange.name"),Ni(t.documentChange.document.name,"documentChange.document.name"),Ni(t.documentChange.document.updateTime,"documentChange.document.updateTime");var f=t.documentChange,d=this.fromName(f.document.name),y=this.fromVersion(f.document.updateTime),m=new Ze(d,y,{},void 0,f.document,(function(t){return n.fromValue(t)})),v=f.targetIds||[],_=f.removedTargetIds||[];e=new Kr(v,_,m.key,m)}else if("documentDelete"in t){Ni(t.documentDelete,"documentDelete"),Ni(t.documentDelete.document,"documentDelete.document");var w=t.documentDelete;d=this.fromName(w.document),y=w.readTime?this.fromVersion(w.readTime):xt.forDeletedDoc(),m=new tn(d,y),_=w.removedTargetIds||[];e=new Kr([],_,m.key,m)}else if("documentRemove"in t){Ni(t.documentRemove,"documentRemove"),Ni(t.documentRemove.document,"documentRemove");var E=t.documentRemove;d=this.fromName(E.document),_=E.removedTargetIds||[];e=new Kr([],_,d,null)}else{if(!("filter"in t))return S("Unknown change type "+JSON.stringify(t));Ni(t.filter,"filter"),Ni(t.filter.targetId,"filter.targetId");var filter=t.filter,T=filter.count||0,C=new Ti(T),I=filter.targetId;e=new Hr(I,C)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?Vr.NoChange:"ADD"===t?Vr.Added:"REMOVE"===t?Vr.Removed:"CURRENT"===t?Vr.Current:"RESET"===t?Vr.Reset:S("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!("targetChange"in t))return xt.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?xt.MIN:e.readTime?this.fromVersion(e.readTime):xt.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof Oe)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof Le)e={delete:this.toName(t.key)};else if(t instanceof Pe)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof xe))return S("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map((function(t){return n.toFieldTransform(t)}))}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):ke.NONE;if(t.update){Ni(t.update.name,"name");var r=this.fromName(t.update.name),o=this.fromFields(t.update.fields||{});if(t.updateMask){var c=this.fromDocumentMask(t.updateMask);return new Pe(r,o,c,n)}return new Oe(r,o,n)}if(t.delete){r=this.fromName(t.delete);return new Le(r,n)}if(t.transform){r=this.fromName(t.transform.document);var h=t.transform.fieldTransforms.map((function(t){return e.fromFieldTransform(t)}));return C(!0===n.exists,'Transforms only support precondition "exists == true"'),new xe(r,h)}return S("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return C(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:S("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?ke.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?ke.exists(t.exists):ke.NONE},t.prototype.fromWriteResult=function(t,e){var n=this,r=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e),o=null;return t.transformResults&&t.transformResults.length>0&&(o=t.transformResults.map((function(t){return n.fromValue(t)}))),new Ne(r,o)},t.prototype.fromWriteResults=function(t,e){var n=this;return t&&t.length>0?(C(void 0!==e,"Received a write result without a commit time"),t.map((function(t){return n.fromWriteResult(t,e)}))):[]},t.prototype.toFieldTransform=function(t){var e=this,n=t.transform;if(n instanceof mi)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof gi)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements.map((function(t){return e.toValue(t)}))}};if(n instanceof vi)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements.map((function(t){return e.toValue(t)}))}};if(n instanceof bi)return{fieldPath:t.field.canonicalString(),increment:this.toValue(n.operand)};throw S("Unknown transform: "+t.transform)},t.prototype.fromFieldTransform=function(t){var e=this,n=null;if("setToServerValue"in t)C("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),n=mi.instance;else if("appendMissingElements"in t){var r=t.appendMissingElements.values||[];n=new gi(r.map((function(t){return e.fromValue(t)})))}else if("removeAllFromArray"in t){r=t.removeAllFromArray.values||[];n=new vi(r.map((function(t){return e.fromValue(t)})))}else if("increment"in t){var o=this.fromValue(t.increment);C(o instanceof Ve,"NUMERIC_ADD transform requires a NumberValue"),n=new bi(o)}else S("Unknown transform proto: "+JSON.stringify(t));var c=_t.fromServerFormat(t.fieldPath);return new Ie(c,n)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;C(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return ei.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}},path=t.path;null!==t.collectionGroup?(C(path.length%2==0,"Collection Group queries should be within a document path or root."),e.parent=this.toQueryPath(path),e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(C(path.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(path.popLast()),e.structuredQuery.from=[{collectionId:path.lastSegment()}]);var n=this.toFilter(t.filters);n&&(e.structuredQuery.where=n);var r=this.toOrder(t.orderBy);r&&(e.structuredQuery.orderBy=r);var o=this.toInt32Value(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var path=this.fromQueryPath(t.parent),e=t.structuredQuery,n=e.from?e.from.length:0,r=null;if(n>0){C(1===n,"StructuredQuery.from with more than one collection is not supported.");var o=e.from[0];o.allDescendants?r=o.collectionId:path=path.child(o.collectionId)}var c=[];e.where&&(c=this.fromFilter(e.where));var h=[];e.orderBy&&(h=this.fromOrder(e.orderBy));var l=null;e.limit&&(l=this.fromInt32Value(e.limit));var f=null;e.startAt&&(f=this.fromCursor(e.startAt));var d=null;return e.endAt&&(d=this.fromCursor(e.endAt)),new ei(path,r,h,c,l,f,d)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case On.Listen:return null;case On.ExistenceFilterMismatch:return"existence-filter-mismatch";case On.LimboResolution:return"limbo-document";default:return S("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return(e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)}).targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map((function(filter){return filter instanceof ii?e.toUnaryOrFieldFilter(filter):S("Unrecognized filter: "+JSON.stringify(filter))}));return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(filter){var t=this;return filter?void 0!==filter.unaryFilter?[this.fromUnaryFilter(filter)]:void 0!==filter.fieldFilter?[this.fromFieldFilter(filter)]:void 0!==filter.compositeFilter?filter.compositeFilter.filters.map((function(e){return t.fromFilter(e)})).reduce((function(t,e){return t.concat(e)})):S("Unknown filter: "+JSON.stringify(filter)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map((function(t){return e.toPropertyOrder(t)}))},t.prototype.fromOrder=function(t){var e=this;return t.map((function(t){return e.fromPropertyOrder(t)}))},t.prototype.toCursor=function(cursor){var t=this;return{before:cursor.before,values:cursor.position.map((function(component){return t.toValue(component)}))}},t.prototype.fromCursor=function(cursor){var t=this,e=!!cursor.before,n=cursor.values.map((function(component){return t.fromValue(component)}));return new fi(n,e)},t.prototype.toDirection=function(t){return Si[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return hi.ASCENDING;case"DESCENDING":return hi.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Ci[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return ri.EQUAL;case"GREATER_THAN":return ri.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return ri.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return ri.LESS_THAN;case"LESS_THAN_OR_EQUAL":return ri.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return ri.ARRAY_CONTAINS;case"IN":return ri.IN;case"ARRAY_CONTAINS_ANY":return ri.ARRAY_CONTAINS_ANY;case"OPERATOR_UNSPECIFIED":return S("Unspecified operator");default:return S("Unknown operator")}},t.prototype.toFieldPathReference=function(path){return{fieldPath:path.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return _t.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new pi(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.fromFieldFilter=function(filter){return ii.create(this.fromFieldPathReference(filter.fieldFilter.field),this.fromOperatorName(filter.fieldFilter.op),this.fromValue(filter.fieldFilter.value))},t.prototype.toUnaryOrFieldFilter=function(filter){if(filter.op===ri.EQUAL){if(filter.value.isEqual(We.NAN))return{unaryFilter:{field:this.toFieldPathReference(filter.field),op:"IS_NAN"}};if(filter.value.isEqual(Ue.INSTANCE))return{unaryFilter:{field:this.toFieldPathReference(filter.field),op:"IS_NULL"}}}return{fieldFilter:{field:this.toFieldPathReference(filter.field),op:this.toOperatorName(filter.op),value:this.toValue(filter.value)}}},t.prototype.fromUnaryFilter=function(filter){switch(filter.unaryFilter.op){case"IS_NAN":var t=this.fromFieldPathReference(filter.unaryFilter.field);return ii.create(t,ri.EQUAL,We.NAN);case"IS_NULL":var e=this.fromFieldPathReference(filter.unaryFilter.field);return ii.create(e,ri.EQUAL,Ue.INSTANCE);case"OPERATOR_UNSPECIFIED":return S("Unspecified filter");default:return S("Unknown filter")}},t.prototype.toDocumentMask=function(t){var e=[];return t.fields.forEach((function(t){return e.push(t.canonicalString())})),{fieldPaths:e}},t.prototype.fromDocumentMask=function(t){var e=(t.fieldPaths||[]).map((function(path){return _t.fromServerFormat(path)}));return Ce.fromArray(e)},t}(),ki=function(){this.viewSnap=null,this.targetId=0,this.listeners=[]},Ri=function(){function t(t){this.syncEngine=t,this.queries=new nn((function(q){return q.canonicalId()})),this.onlineState=Cr.Unknown,this.snapshotsInSyncListeners=new Set,this.syncEngine.subscribe(this)}return t.prototype.listen=function(t){var e=t.query,n=!1,r=this.queries.get(e);(r||(n=!0,r=new ki,this.queries.set(e,r)),r.listeners.push(t),C(!t.applyOnlineStateChange(this.onlineState),"applyOnlineStateChange() shouldn't raise an event for brand-new listeners."),r.viewSnap)&&(t.onViewSnapshot(r.viewSnap)&&this.raiseSnapshotsInSyncEvent());return n?this.syncEngine.listen(e).then((function(t){return r.targetId=t,t})):Promise.resolve(r.targetId)},t.prototype.unlisten=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n,r,i;return l.__generator(this,(function(o){return e=t.query,n=!1,(r=this.queries.get(e))&&(i=r.listeners.indexOf(t))>=0&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(e),[2,this.syncEngine.unlisten(e)]):[2]}))}))},t.prototype.onWatchChange=function(t){for(var e=!1,n=0,r=t;n0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){for(var e=[],n=0,r=t.docChanges;n0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges},t.prototype.raiseInitialEvent=function(t){C(!this.raisedInitialEvent,"Trying to raise initial events for second time"),t=jr.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(t)},t}(),Pi=function(){function t(t,e,n){this.targetId=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e,n){for(var r=Yt(),o=Yt(),c=0,h=n.docChanges;c0&&this.isRetryableTransactionError(t)?(this.retries-=1,this.asyncQueue.enqueueAndForget((function(){return e.runWithBackOff(),Promise.resolve()}))):this.deferred.reject(t)},t.prototype.isRetryableTransactionError=function(t){if("FirebaseError"===t.name){var code=t.code;return"aborted"===code||"failed-precondition"===code||!xr(code)}return!1},t}(),qi=function(t,e,view){this.query=t,this.targetId=e,this.view=view},Vi=function(t){this.key=t,this.receivedDocument=!1},Bi=function(){function t(t,e,n,r){this.localStore=t,this.remoteStore=e,this.sharedClientState=n,this.currentUser=r,this.syncEngineListener=null,this.queryViewsByQuery=new nn((function(q){return q.canonicalId()})),this.queryViewsByTarget={},this.limboTargetsByKey=new Lt(wt.comparator),this.limboResolutionsByTarget={},this.limboDocumentRefs=new nr,this.mutationUserCallbacks={},this.pendingWritesCallbacks=new Map,this.limboTargetIdGenerator=he.forSyncEngine(),this.isPrimary=void 0,this.onlineState=Cr.Unknown}return Object.defineProperty(t.prototype,"isPrimaryClient",{get:function(){return!0===this.isPrimary},enumerable:!0,configurable:!0}),t.prototype.subscribe=function(t){C(null!==t,"SyncEngine listener cannot be null"),C(null===this.syncEngineListener,"SyncEngine already has a subscriber."),this.syncEngineListener=t},t.prototype.listen=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n,r,o,c;return l.__generator(this,(function(h){switch(h.label){case 0:return this.assertSubscribed("listen()"),(r=this.queryViewsByQuery.get(t))?(e=r.targetId,this.sharedClientState.addLocalQueryTarget(e),n=r.view.computeInitialSnapshot(),[3,4]):[3,1];case 1:return[4,this.localStore.allocateQuery(t)];case 2:return o=h.sent(),c=this.sharedClientState.addLocalQueryTarget(o.targetId),e=o.targetId,[4,this.initializeViewAndComputeSnapshot(o,"current"===c)];case 3:n=h.sent(),this.isPrimary&&this.remoteStore.listen(o),h.label=4;case 4:return this.syncEngineListener.onWatchChange([n]),[2,e]}}))}))},t.prototype.initializeViewAndComputeSnapshot=function(t,e){return l.__awaiter(this,void 0,void 0,(function(){var n,r,o,view,c,h,f,data;return l.__generator(this,(function(l){switch(l.label){case 0:return n=t.query,[4,this.localStore.executeQuery(n)];case 1:return r=l.sent(),[4,this.localStore.remoteDocumentKeys(t.targetId)];case 2:return o=l.sent(),view=new Mi(n,o),c=view.computeDocChanges(r),h=Qr.createSynthesizedTargetChangeForCurrentChange(t.targetId,e&&this.onlineState!==Cr.Offline),C(0===(f=view.applyChanges(c,!0===this.isPrimary,h)).limboChanges.length,"View returned limbo docs before target ack from the server."),C(!!f.snapshot,"applyChanges for new view should always return a snapshot"),data=new qi(n,t.targetId,view),this.queryViewsByQuery.set(n,data),this.queryViewsByTarget[t.targetId]=data,[2,f.snapshot]}}))}))},t.prototype.synchronizeViewAndComputeSnapshot=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n,r;return l.__generator(this,(function(o){switch(o.label){case 0:return[4,this.localStore.executeQuery(t.query)];case 1:return e=o.sent(),[4,this.localStore.remoteDocumentKeys(t.targetId)];case 2:return n=o.sent(),r=t.view.synchronizeWithPersistedState(e,n),this.isPrimary&&this.updateTrackedLimbos(t.targetId,r.limboChanges),[2,r]}}))}))},t.prototype.unlisten=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n=this;return l.__generator(this,(function(r){switch(r.label){case 0:return this.assertSubscribed("unlisten()"),C(!!(e=this.queryViewsByQuery.get(t)),"Trying to unlisten on query not found:"+t),this.isPrimary?(this.sharedClientState.removeLocalQueryTarget(e.targetId),this.sharedClientState.isActiveQueryTarget(e.targetId)?[3,2]:[4,this.localStore.releaseQuery(t,!1).then((function(){n.sharedClientState.clearQueryState(e.targetId),n.remoteStore.unlisten(e.targetId),n.removeAndCleanupQuery(e)})).catch(Yn)]):[3,3];case 1:r.sent(),r.label=2;case 2:return[3,5];case 3:return this.removeAndCleanupQuery(e),[4,this.localStore.releaseQuery(t,!0)];case 4:r.sent(),r.label=5;case 5:return[2]}}))}))},t.prototype.write=function(t,e){return l.__awaiter(this,void 0,void 0,(function(){var n;return l.__generator(this,(function(r){switch(r.label){case 0:return this.assertSubscribed("write()"),[4,this.localStore.localWrite(t)];case 1:return n=r.sent(),this.sharedClientState.addPendingMutation(n.batchId),this.addMutationCallback(n.batchId,e),[4,this.emitNewSnapsAndNotifyLocalStore(n.changes)];case 2:return r.sent(),[4,this.remoteStore.fillWritePipeline()];case 3:return r.sent(),[2]}}))}))},t.prototype.runTransaction=function(t,e,n){new Ui(t,this.remoteStore,e,n).run()},t.prototype.applyRemoteEvent=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n=this;return l.__generator(this,(function(r){switch(r.label){case 0:this.assertSubscribed("applyRemoteEvent()"),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.localStore.applyRemoteEvent(t)];case 2:return e=r.sent(),x(t.targetChanges,(function(t,e){var r=n.limboResolutionsByTarget[Number(t)];r&&(C(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1,"Limbo resolution for single document contains multiple changes."),e.addedDocuments.size>0?r.receivedDocument=!0:e.modifiedDocuments.size>0?C(r.receivedDocument,"Received change for limbo target document without add."):e.removedDocuments.size>0&&(C(r.receivedDocument,"Received remove for limbo target document without add."),r.receivedDocument=!1))})),[4,this.emitNewSnapsAndNotifyLocalStore(e,t)];case 3:return r.sent(),[3,6];case 4:return[4,Yn(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},t.prototype.applyOnlineStateChange=function(t,source){if(this.isPrimary&&source===Ir.RemoteStore||!this.isPrimary&&source===Ir.SharedClientState){this.assertSubscribed("applyOnlineStateChange()");var e=[];this.queryViewsByQuery.forEach((function(n,r){var o=r.view.applyOnlineStateChange(t);C(0===o.limboChanges.length,"OnlineState should not affect limbo documents."),o.snapshot&&e.push(o.snapshot)})),this.syncEngineListener.onOnlineStateChange(t),this.syncEngineListener.onWatchChange(e),this.onlineState=t,this.isPrimary&&this.sharedClientState.setOnlineState(t)}},t.prototype.rejectListen=function(t,e){return l.__awaiter(this,void 0,void 0,(function(){var n,r,o,c,h,f,d=this;return l.__generator(this,(function(l){switch(l.label){case 0:return this.assertSubscribed("rejectListens()"),this.sharedClientState.updateQueryState(t,"rejected",e),n=this.limboResolutionsByTarget[t],(r=n&&n.key)?(this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboResolutionsByTarget[t],o=(o=new Lt(wt.comparator)).insert(r,new tn(r,xt.forDeletedDoc())),c=Yt().add(r),h=new Wr(xt.MIN,{},new qt(it),o,c),[2,this.applyRemoteEvent(h)]):[3,1];case 1:return C(!!(f=this.queryViewsByTarget[t]),"Unknown targetId: "+t),[4,this.localStore.releaseQuery(f.query,!1).then((function(){return d.removeAndCleanupQuery(f)})).catch(Yn)];case 2:l.sent(),this.syncEngineListener.onWatchError(f.query,e),l.label=3;case 3:return[2]}}))}))},t.prototype.applyBatchState=function(t,e,n){return l.__awaiter(this,void 0,void 0,(function(){var r;return l.__generator(this,(function(o){switch(o.label){case 0:return this.assertSubscribed("applyBatchState()"),[4,this.localStore.lookupMutationDocuments(t)];case 1:return null===(r=o.sent())?(w("SyncEngine","Cannot apply mutation batch with id: "+t),[2]):"pending"!==e?[3,3]:[4,this.remoteStore.fillWritePipeline()];case 2:return o.sent(),[3,4];case 3:"acknowledged"===e||"rejected"===e?(this.processUserCallback(t,n||null),this.localStore.removeCachedMutationBatchMetadata(t)):S("Unknown batchState: "+e),o.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(r)];case 5:return o.sent(),[2]}}))}))},t.prototype.applySuccessfulWrite=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n;return l.__generator(this,(function(r){switch(r.label){case 0:this.assertSubscribed("applySuccessfulWrite()"),e=t.batch.batchId,this.processUserCallback(e,null),this.triggerPendingWritesCallbacks(e),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.localStore.acknowledgeBatch(t)];case 2:return n=r.sent(),this.sharedClientState.updateMutationState(e,"acknowledged"),[4,this.emitNewSnapsAndNotifyLocalStore(n)];case 3:return r.sent(),[3,6];case 4:return[4,Yn(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},t.prototype.rejectFailedWrite=function(t,e){return l.__awaiter(this,void 0,void 0,(function(){var n;return l.__generator(this,(function(r){switch(r.label){case 0:this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.triggerPendingWritesCallbacks(t),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.localStore.rejectBatch(t)];case 2:return n=r.sent(),this.sharedClientState.updateMutationState(t,"rejected",e),[4,this.emitNewSnapsAndNotifyLocalStore(n)];case 3:return r.sent(),[3,6];case 4:return[4,Yn(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},t.prototype.registerPendingWritesCallback=function(t){return l.__awaiter(this,void 0,void 0,(function(){var e,n;return l.__generator(this,(function(r){switch(r.label){case 0:return this.remoteStore.canUseNetwork()||w("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),[4,this.localStore.getHighestUnacknowledgedBatchId()];case 1:return-1===(e=r.sent())?(t.resolve(),[2]):((n=this.pendingWritesCallbacks.get(e)||[]).push(t),this.pendingWritesCallbacks.set(e,n),[2])}}))}))},t.prototype.triggerPendingWritesCallbacks=function(t){(this.pendingWritesCallbacks.get(t)||[]).forEach((function(t){t.resolve()})),this.pendingWritesCallbacks.delete(t)},t.prototype.rejectOutstandingPendingWritesCallbacks=function(t){this.pendingWritesCallbacks.forEach((function(e){e.forEach((function(e){e.reject(new D(A.CANCELLED,t))}))})),this.pendingWritesCallbacks.clear()},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new Lt(it)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(C(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){var e=this;if(this.sharedClientState.removeLocalQueryTarget(t.targetId),this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.isPrimary){var n=this.limboDocumentRefs.referencesForId(t.targetId);this.limboDocumentRefs.removeReferencesForId(t.targetId),n.forEach((function(t){e.limboDocumentRefs.containsKey(t)||e.removeLimboTarget(t)}))}},t.prototype.removeLimboTarget=function(t){var e=this.limboTargetsByKey.get(t);null!==e&&(this.remoteStore.unlisten(e),this.limboTargetsByKey=this.limboTargetsByKey.remove(t),delete this.limboResolutionsByTarget[e])},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n() instead."),So=/^__.*__$/,Co=function(){function t(data,t,e){this.data=data,this.fieldMask=t,this.fieldTransforms=e}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new Pe(t,this.data,this.fieldMask,e)):n.push(new Oe(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new xe(t,this.fieldTransforms)),n},t}(),Io=function(){function t(data,t,e){this.data=data,this.fieldMask=t,this.fieldTransforms=e}return t.prototype.toMutations=function(t,e){var n=[new Pe(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new xe(t,this.fieldTransforms)),n},t}();function No(t){switch(t){case mo.Set:case mo.MergeSet:case mo.Update:return!0;case mo.Argument:return!1;default:throw S("Unexpected case for UserDataSource: "+t)}}!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.Argument=3]="Argument"}(mo||(mo={}));var Ao=function(){function t(t,e,path,n,r,o){this.dataSource=t,this.methodName=e,this.path=path,this.arrayElement=n,void 0===r&&this.validatePath(),this.arrayElement=void 0!==n&&n,this.fieldTransforms=r||[],this.fieldMask=o||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path.toString()+")";return new D(A.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.contains=function(t){return void 0!==this.fieldMask.find((function(e){return t.isPrefixOf(e)}))||void 0!==this.fieldTransforms.find((function(e){return t.isPrefixOf(e.field)}))},t.prototype.validatePath=function(){if(null!==this.path)for(var i=0;i0&&e.fieldMask.push(e.path):x(t,(function(t,o){var c=n.parseData(o,e.childContextForField(t));null!=c&&(r=r.insert(t,c))})),new Xe(r)},t.prototype.parseArray=function(t,e){for(var n=[],r=0,o=0,c=t;o0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");e.fieldMask.push(e.path)}else if(t instanceof bo)e.fieldTransforms.push(new Ie(e.path,mi.instance));else if(t instanceof _o){var n=this.parseArrayTransformElements(t._methodName,t._elements),r=new gi(n);e.fieldTransforms.push(new Ie(e.path,r))}else if(t instanceof wo){n=this.parseArrayTransformElements(t._methodName,t._elements);var o=new vi(n);e.fieldTransforms.push(new Ie(e.path,o))}else if(t instanceof Eo){var c=this.parseQueryValue("FieldValue.increment",t._operand),h=new bi(c);e.fieldTransforms.push(new Ie(e.path,h))}else S("Unknown FieldValue type: "+t)},t.prototype.parseScalarValue=function(t,e){if(null===t)return Ue.INSTANCE;if("number"==typeof t)return vr(t)?new je(t):new We(t);if("boolean"==typeof t)return qe.of(t);if("string"==typeof t)return new Qe(t);if(t instanceof Date)return new Ke(Pt.fromDate(t));if(t instanceof Pt)return new Ke(new Pt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof ti)return new Ye(t);if(t instanceof ht)return new Ge(t);if(t instanceof Do)return new ze(t.databaseId,t.key);throw e.createError("Unsupported field value: "+X(t))},t.prototype.parseArrayTransformElements=function(t,e){var n=this;return e.map((function(element,i){var e=new Ao(mo.Argument,t,_t.EMPTY_PATH);return n.parseData(element,e.childContextForArray(i))}))},t}();function Ro(input){return!("object"!=typeof input||null===input||input instanceof Array||input instanceof Date||input instanceof Pt||input instanceof ti||input instanceof ht||input instanceof Do||input instanceof go)}function Oo(t,e,input){if(!Ro(input)||!Y(input)){var n=X(input);throw"an object"===n?e.createError(t+" a custom object"):e.createError(t+" "+n)}}function Po(t,path){if(path instanceof ao)return path._internalPath;if("string"==typeof path)return xo(t,path);throw new D(A.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function xo(t,path){try{return function(path){if(path.search(so)>=0)throw new D(A.INVALID_ARGUMENT,"Invalid field path ("+path+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(ao.bind.apply(ao,[void 0].concat(path.split("."))))}catch(t){throw new D(A.INVALID_ARGUMENT,"Invalid field path ("+path+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}(path)._internalPath}catch(n){var e=Lo(n);throw new D(A.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. "+e)}}function Lo(t){return t instanceof Error?t.message:t.toString()}var Mo="firestore.googleapis.com",Fo=!0,Uo=!0,qo=!1,Vo=Bn.COLLECTION_DISABLED,Bo=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new D(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Mo,this.ssl=Fo}else W("settings","non-empty string","host",t.host),this.host=t.host,Q("settings","boolean","ssl",t.ssl),this.ssl=O(t.ssl,Fo);if($("settings",t,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes","experimentalForceLongPolling"]),Q("settings","object","credentials",t.credentials),this.credentials=t.credentials,Q("settings","boolean","timestampsInSnapshots",t.timestampsInSnapshots),!0===t.timestampsInSnapshots?E("\n The timestampsInSnapshots setting now defaults to true and you no\n longer need to explicitly set it. In a future release, the setting\n will be removed entirely and so it is recommended that you remove it\n from your firestore.settings() call now."):!1===t.timestampsInSnapshots&&E("\n The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n YOUR CODE.\n\n To hide this warning, stop using the timestampsInSnapshots setting in your\n firestore.settings({ ... }) call.\n\n Once you remove the setting, Timestamps stored in Cloud Firestore will be\n read back as Firebase Timestamp objects instead of as system Date objects.\n So you will also need to update code expecting a Date to instead expect a\n Timestamp. For example:\n\n // Old:\n const date = snapshot.get('created_at');\n // New:\n const timestamp = snapshot.get('created_at'); const date =\n timestamp.toDate();\n\n Please audit all existing usages of Date when you enable the new\n behavior."),this.timestampsInSnapshots=O(t.timestampsInSnapshots,Uo),Q("settings","number","cacheSizeBytes",t.cacheSizeBytes),void 0===t.cacheSizeBytes)this.cacheSizeBytes=Bn.DEFAULT_CACHE_SIZE_BYTES;else{if(t.cacheSizeBytes!==Vo&&t.cacheSizeBytes=0)throw new D(A.INVALID_ARGUMENT,"Invalid collection ID '"+t+"' passed to function Firestore.collectionGroup(). Collection IDs must not contain '/'.");return this.ensureClientConfigured(),new Yo(new ei(vt.EMPTY_PATH,t),this)},t.prototype.runTransaction=function(t){var e=this;return F("Firestore.runTransaction",arguments,1),B("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction((function(n){return t(new Wo(e,n))}))},t.prototype.batch=function(){return this.ensureClientConfigured(),new Qo(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(v()){case o.DEBUG:return"debug";case o.ERROR:return"error";case o.SILENT:return"silent";default:return S("Unknown log level: "+v())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(F("Firestore.setLogLevel",arguments,1),B("Firestore.setLogLevel","non-empty string",1,t),t){case"debug":_(o.DEBUG);break;case"error":_(o.ERROR);break;case"silent":_(o.SILENT);break;default:throw new D(A.INVALID_ARGUMENT,"Invalid log level: "+t)}},t.prototype._areTimestampsInSnapshotsEnabled=function(){return this._settings.timestampsInSnapshots},t}(),Wo=function(){function t(t,e){this._firestore=t,this._transaction=e}return t.prototype.get=function(t){var e=this;F("Transaction.get",arguments,1);var n=ea("Transaction.get",t,this._firestore);return this._transaction.lookup([n._key]).then((function(t){if(!t||1!==t.length)return S("Mismatch in docs returned from document lookup.");var r=t[0];if(r instanceof tn)return new Go(e._firestore,n._key,null,!1,!1);if(r instanceof Ze)return new Go(e._firestore,n._key,r,!1,!1);throw S("BatchGetDocumentsRequest returned unexpected document type: "+r.constructor.name)}))},t.prototype.set=function(t,e,n){V("Transaction.set",arguments,2,3);var r=ea("Transaction.set",t,this._firestore),o=(n=$o("Transaction.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("Transaction.set",e,n.mergeFields):this._firestore._dataConverter.parseSetData("Transaction.set",e);return this._transaction.set(r._key,o),this},t.prototype.update=function(t,e,n){for(var r,o,c=[],h=3;h0?[2,this._firestore.ensureClientConfigured().write(this._mutations)]:[2]}))}))},t.prototype.verifyNotCommitted=function(){if(this._committed)throw new D(A.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),Ko=function(){function t(t,e){this._key=t,this.firestore=e,this._firestoreClient=this.firestore.ensureClientConfigured()}return t.forPath=function(path,e){if(path.length%2!=0)throw new D(A.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+path.canonicalString()+" has "+path.length);return new t(new wt(path),e)},Object.defineProperty(t.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new Jo(this._key.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this._key.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(F("DocumentReference.collection",arguments,1),B("DocumentReference.collection","non-empty string",1,t),!t)throw new D(A.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var path=vt.fromString(t);return new Jo(this._key.path.child(path),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Z("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this._key.isEqual(e._key)},t.prototype.set=function(t,e){V("DocumentReference.set",arguments,1,2);var n=(e=$o("DocumentReference.set",e)).merge||e.mergeFields?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t,e.mergeFields):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._firestoreClient.write(n.toMutations(this._key,ke.NONE))},t.prototype.update=function(t,e){for(var n,r=[],o=2;o=",">","array-contains"];G("Query.where",o,2,n)}var c,h=Po("Query.where",e),l=ri.fromString(n);if(h.isKeyField()){if(l===ri.ARRAY_CONTAINS||l===ri.ARRAY_CONTAINS_ANY)throw new D(A.INVALID_ARGUMENT,"Invalid Query. You can't perform '"+l.toString()+"' queries on FieldPath.documentId().");if(l===ri.IN){this.validateDisjunctiveFilterElements(r,l);for(var f=[],d=0,y=r;d0)throw new D(A.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var o=e;if(!o.exists)throw new D(A.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,o._document,r)}var c=[e].concat(n);return this.boundFromFields(t,c,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],o=0,c=this._query.orderBy;or.length)throw new D(A.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var o=[],i=0;i10)throw new D(A.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters support a maximum of 10 elements in the value array.");if(t.indexOf(null)>=0)throw new D(A.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters cannot contain 'null' in the value array.");if(t.filter((function(element){return Number.isNaN(element)})).length>0)throw new D(A.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters cannot contain 'NaN' in the value array.")},t.prototype.validateNewFilter=function(filter){if(filter instanceof ii){var t=[ri.ARRAY_CONTAINS,ri.ARRAY_CONTAINS_ANY],e=[ri.IN,ri.ARRAY_CONTAINS_ANY],n=t.indexOf(filter.op)>=0,r=e.indexOf(filter.op)>=0;if(filter.isInequality()){var o=this._query.getInequalityFilterField();if(null!==o&&!o.isEqual(filter.field))throw new D(A.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+o.toString()+"' and '"+filter.field.toString()+"'");var c=this._query.getFirstOrderByField();null!==c&&this.validateOrderByAndInequalityMatch(filter.field,c)}else if(r||n){var h=null;if(r&&(h=this._query.findFilterOperator(e)),null===h&&n&&(h=this._query.findFilterOperator(t)),null!=h)throw h===filter.op?new D(A.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '"+filter.op.toString()+"' filter."):new D(A.INVALID_ARGUMENT,"Invalid query. You cannot use '"+filter.op.toString()+"' filters with '"+h.toString()+"' filters.")}}},t.prototype.validateNewOrderBy=function(t){if(null===this._query.getFirstOrderByField()){var e=this._query.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new D(A.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t.toString()+"' and so you must also use '"+t.toString()+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e.toString()+"' instead.")},t}(),Xo=function(){function t(t,e,n){this._firestore=t,this._originalQuery=e,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new Ho(n.hasPendingWrites,n.fromCache)}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach((function(e){return t.push(e)})),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;V("QuerySnapshot.forEach",arguments,1,2),B("QuerySnapshot.forEach","function",1,t),this._snapshot.docs.forEach((function(r){t.call(e,n.convertToDocumentImpl(r))}))},Object.defineProperty(t.prototype,"query",{get:function(){return new Yo(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),t.prototype.docChanges=function(t){t&&($("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),Q("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this._snapshot.excludesMetadataChanges)throw new D(A.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(t,e,n){if(n.oldDocs.isEmpty()){var r,o=0;return n.docChanges.map((function(e){var c=new zo(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key));return C(e.type===Fr.Added,"Invalid event type for first snapshot"),C(!r||n.query.docComparator(r,e.doc)<0,"Got added events in wrong order"),r=e.doc,{type:"added",doc:c,oldIndex:-1,newIndex:o++}}))}var c=n.oldDocs;return n.docChanges.filter((function(t){return e||t.type!==Fr.Metadata})).map((function(e){var r=new zo(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key)),o=-1,h=-1;return e.type!==Fr.Added&&(C((o=c.indexOf(e.doc.key))>=0,"Index for document not found"),c=c.delete(e.doc.key)),e.type!==Fr.Removed&&(h=(c=c.add(e.doc)).indexOf(e.doc.key)),{type:na(e.type),doc:r,oldIndex:o,newIndex:h}}))}(this._firestore,e,this._snapshot),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Z("isEqual","QuerySnapshot",1,e);return this._firestore===e._firestore&&this._originalQuery.isEqual(e._originalQuery)&&this._snapshot.isEqual(e._snapshot)},t.prototype.convertToDocumentImpl=function(t){return new zo(this._firestore,t.key,t,this.metadata.fromCache,this._snapshot.mutatedKeys.has(t.key))},t}();["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]).forEach((function(t){try{Object.defineProperty(Xo.prototype.docChanges,t,{get:function(){return function(){throw new D(A.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}()}})}catch(t){}}));var Jo=function(t){function e(path,e){var n=t.call(this,ei.atPath(path),e)||this;if(path.length%2!=1)throw new D(A.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+path.canonicalString()+" has "+path.length);return n}return l.__extends(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this._query.path.popLast();return t.isEmpty()?null:new Ko(new wt(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(V("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=nt.newId()),B("CollectionReference.doc","non-empty string",1,t),""===t)throw new D(A.INVALID_ARGUMENT,"Document path must be a non-empty string");var path=vt.fromString(t);return Ko.forPath(this._query.path.child(path),this.firestore)},e.prototype.add=function(t){F("CollectionReference.add",arguments,1),B("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then((function(){return e}))},e}(Yo);function $o(t,e){if(void 0===e)return{merge:!1};if($(t,e,["merge","mergeFields"]),Q(t,"boolean","merge",e.merge),K(t,"mergeFields","a string or a FieldPath",e.mergeFields,(function(element){return"string"==typeof element||element instanceof ao})),void 0!==e.mergeFields&&void 0!==e.merge)throw new D(A.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function Zo(t,e){return void 0===e?{}:($(t,e,["serverTimestamps"]),H(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function ta(t,e){j(t,"object",1,e),e&&($(t,e,["source"]),H(t,0,"source",e.source,["default","server","cache"]))}function ea(t,e,n){if(e instanceof Ko){if(e.firestore!==n)throw new D(A.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw Z(t,"DocumentReference",1,e)}function na(t){switch(t){case Fr.Added:return"added";case Fr.Modified:case Fr.Metadata:return"modified";case Fr.Removed:return"removed";default:return S("Unknown change type: "+t)}}var ra=k(jo,"Use firebase.firestore() instead."),ia=k(Wo,"Use firebase.firestore().runTransaction() instead."),oa=k(Qo,"Use firebase.firestore().batch() instead."),aa=k(Ko,"Use firebase.firestore().doc() instead."),sa=k(Go),ua=k(zo),ca=k(Yo),ha=k(Xo),la=k(Jo,"Use firebase.firestore().collection() instead."),fa={Firestore:ra,GeoPoint:ti,Timestamp:Pt,Blob:lt,Transaction:ia,WriteBatch:oa,DocumentReference:aa,DocumentSnapshot:sa,Query:ca,QueryDocumentSnapshot:ua,QuerySnapshot:ha,CollectionReference:la,FieldPath:ao,FieldValue:To,setLogLevel:jo.setLogLevel,CACHE_SIZE_UNLIMITED:Vo};function pa(t){t.INTERNAL.registerService("firestore",(function(t){return new jo(t)}),function(t){C(t&&"object"==typeof t,"shallowCopy() expects object parameter.");var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}(fa))}var da=function(){function t(){}return t.prototype.addCallback=function(t){},t.prototype.shutdown=function(){},t}(),ya=function(){function t(){var t=this;this.networkAvailableListener=function(){return t.onNetworkAvailable()},this.networkUnavailableListener=function(){return t.onNetworkUnavailable()},this.callbacks=[],this.configureNetworkMonitoring()}return t.prototype.addCallback=function(t){this.callbacks.push(t)},t.prototype.shutdown=function(){window.removeEventListener("online",this.networkAvailableListener),window.removeEventListener("offline",this.networkUnavailableListener)},t.prototype.configureNetworkMonitoring=function(){window.addEventListener("online",this.networkAvailableListener),window.addEventListener("offline",this.networkUnavailableListener)},t.prototype.onNetworkAvailable=function(){w("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(var t=0,e=this.callbacks;t0){var r=l.getResponseJson().error;if(r&&r.status&&r.message){var o=(f=r.status,y=f.toLowerCase().replace("_","-"),Object.values(A).indexOf(y)>=0?y:A.UNKNOWN);h(new D(o,r.message))}else h(new D(A.UNKNOWN,"Server responded with status "+l.getStatus()))}else w(ga,'RPC "'+t+'" failed'),h(new D(A.UNAVAILABLE,"Connection failed."));break;default:S('RPC "'+t+'" failed with unanticipated webchannel error '+l.getLastErrorCode()+": "+l.getLastError()+", giving up.")}}finally{w(ga,'RPC "'+t+'" completed.')}var f,y}));var f=JSON.stringify(e);w(ga,"XHR sending: ",o+" "+f);var y={"Content-Type":"text/plain"};r.modifyHeadersForRequest(y,n),l.send(o,"POST",f,y,15)}))},t.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},t.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1.Firestore","/",t,"/channel"],r=d.createWebChannelTransport(),o={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling};this.modifyHeadersForRequest(o.initMessageHeaders,e),f.isReactNative()||(o.httpHeadersOverwriteParam="$httpHeaders");var c=n.join("");w(ga,"Creating WebChannel: "+c+" "+o);var h=r.createWebChannel(c,o),l=!1,y=!1,m=new ma({sendFn:function(t){y?w(ga,"Not sending because WebChannel is closed:",t):(l||(w(ga,"Opening WebChannel transport."),h.open(),l=!0),w(ga,"WebChannel sending:",t),h.send(t))},closeFn:function(){return h.close()}}),v=function(t,e){h.listen(t,(function(param){try{e(param)}catch(t){setTimeout((function(){throw t}),0)}}))};return v(d.WebChannel.EventType.OPEN,(function(){y||w(ga,"WebChannel transport opened.")})),v(d.WebChannel.EventType.CLOSE,(function(){y||(y=!0,w(ga,"WebChannel transport closed"),m.callOnClose())})),v(d.WebChannel.EventType.ERROR,(function(t){y||(y=!0,w(ga,"WebChannel transport errored:",t),m.callOnClose(new D(A.UNAVAILABLE,"The operation could not be completed")))})),v(d.WebChannel.EventType.MESSAGE,(function(t){if(!y){var e=t.data[0];C(!!e,"Got a webchannel message without data.");var n=e,r=n.error||n[0]&&n[0].error;if(r){w(ga,"WebChannel received error:",r);var o=r.status,code=function(t){var code=Or[t];if(void 0!==code)return Lr(code)}(o),c=r.message;void 0===code&&(code=A.INTERNAL,c="Unknown error status: "+o+" with message "+r.message),y=!0,m.callOnClose(new D(code,c)),h.close()}else w(ga,"WebChannel received:",e),m.callOnMessage(e)}})),setTimeout((function(){m.callOnOpen()}),0),m},t.prototype.makeUrl=function(t){var e=va[t];C(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(e),n.join("")},t}(),wa=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return Object.defineProperty(t.prototype,"document",{get:function(){return"undefined"!=typeof document?document:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return"undefined"!=typeof window?window:null},enumerable:!0,configurable:!0}),t.prototype.loadConnection=function(t){return Promise.resolve(new _a(t))},t.prototype.newConnectivityMonitor=function(){return ya.isAvailable()?new ya:new da},t.prototype.newSerializer=function(t){return new Di(t,{useProto3Json:!0})},t.prototype.formatJSON=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();function Ea(t){pa(t)}I.setPlatform(new wa),Ea(c),e.registerFirestore=Ea}).call(this,n(70))},192:function(t,e,n){"use strict";n.r(e),function(t){n.d(e,"ErrorCode",(function(){return dr})),n.d(e,"EventType",(function(){return yr})),n.d(e,"WebChannel",(function(){return mr})),n.d(e,"XhrIo",(function(){return gr})),n.d(e,"createWebChannelTransport",(function(){return pr}));var g,r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{},o=o||{},c=r;function h(a){return"string"==typeof a}function l(a){return"number"==typeof a}function f(a,b){a=a.split("."),b=b||c;for(var t=0;t>>0),_=0;function w(a,b,t){return a.call.apply(a.bind,arguments)}function E(a,b,t){if(!a)throw Error();if(2b?1:0}t:{var M=c.navigator;if(M){var F=M.userAgent;if(F){O=F;break t}}O=""}function U(a,b,t){for(var e in a)b.call(t,a[e],e,a)}function V(a){var t,b={};for(t in a)b[t]=a[t];return b}var B="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function j(a,b){for(var t,e,n=1;nparseFloat($)){Q=String(tt);break t}}Q=$}var et,nt={};function it(a){return function(a,b){var t=nt;return Object.prototype.hasOwnProperty.call(t,a)?t[a]:t[a]=b(a)}(a,(function(){for(var b=0,t=P(String(Q)).split("."),e=P(String(a)).split("."),n=Math.max(t.length,e.length),r=0;0==b&&r=a.keyCode)&&(a.keyCode=-1)}catch(t){}};var ft="closure_listenable_"+(1e6*Math.random()|0),pt=0;function yt(a,b,t,e,n){this.listener=a,this.proxy=null,this.src=b,this.type=t,this.capture=!!e,this.da=n,this.key=++pt,this.X=this.Z=!1}function mt(a){a.X=!0,a.listener=null,a.proxy=null,a.src=null,a.da=null}function gt(a){this.src=a,this.a={},this.b=0}function vt(a,b){var t=b.type;if(t in a.a){var e,n=a.a[t],r=N(n,b);(e=0<=r)&&Array.prototype.splice.call(n,r,1),e&&(mt(b),0==a.a[t].length&&(delete a.a[t],a.b--))}}function bt(a,b,t,e){for(var n=0;n>>0);function kt(a){return"function"==p(a)?a:(a[Dt]||(a[Dt]=function(b){return a.handleEvent(b)}),a[Dt])}function Rt(){I.call(this),this.c=new gt(this),this.J=this,this.B=null}function Ot(a,b,t,e){if(!(b=a.c.a[String(b)]))return!0;b=b.concat();for(var n=!0,r=0;rb.b&&(b.b++,a.next=b.a,b.a=a)}jt=!1}function Kt(a,b){Rt.call(this),this.b=a||1,this.a=b||c,this.f=u(this.gb,this),this.g=S()}function Ht(a){a.ba=!1,a.L&&(a.a.clearTimeout(a.L),a.L=null)}function Gt(a,b,t){if("function"==p(a))t&&(a=u(a,t));else{if(!a||"function"!=typeof a.handleEvent)throw Error("Invalid listener argument");a=u(a.handleEvent,a)}return 2147483647b.length?we:(b=b.substr(e,t),a.A=e+t,b))}function Ne(a){a.R=S()+a.O,Ae(a,a.O)}function Ae(a,b){if(null!=a.i)throw Error("WatchDog timer not null");a.i=se(u(a.bb,a),b)}function De(a){a.i&&(c.clearTimeout(a.i),a.i=null)}function ke(a){a.g.Da()||a.m||a.g.na(a)}function Re(a){De(a);var b=a.B;b&&"function"==typeof b.la&&b.la(),a.B=null,Ht(a.P),Zt(a.I),a.a&&(b=a.a,a.a=null,b.abort(),b.la())}function Oe(a,b){try{a.g.Ga(a,b),re(4)}catch(t){}}function Pe(a,b){if(a.forEach&&"function"==typeof a.forEach)a.forEach(b,void 0);else if(y(a)||h(a))A(a,b,void 0);else{if(a.K&&"function"==typeof a.K)var t=a.K();else if(a.C&&"function"==typeof a.C)t=void 0;else if(y(a)||h(a)){t=[];for(var e=a.length,n=0;n2*a.c&&Me(a))}function Me(a){if(a.c!=a.a.length){for(var b=0,t=0;bb||3==b&&!z&&!this.a.aa())){this.m||4!=b||7==t||re(8==t||0>=e?3:2),De(this);var n=this.a.T();this.o=n;var r=this.a.aa();if(this.b=200==n){if(this.S&&!this.s){e:{if(this.a){var o=qn(this.a,"X-HTTP-Initial-Response");if(o&&!R(o)){var c=o;break e}}c=null}if(!c){this.b=!1,this.c=3,oe(12),Re(this),ke(this);break t}this.s=!0,Oe(this,c)}this.H?(Ce(this,b,r),z&&this.b&&3==b&&($t(this.I,this.P,"tick",this.cb),this.P.start())):Oe(this,r),4==b&&Re(this),this.b&&!this.m&&(4==b?this.g.na(this):(this.b=!1,Ne(this)))}else 400==n&&0b)throw Error("Bad port number "+b);a.i=b}else a.i=null}function Qe(a,b,t){b instanceof nn?(a.c=b,function(a,b){b&&!a.f&&(rn(a),a.c=null,a.a.forEach((function(t,e){var n=e.toLowerCase();e!=n&&(on(this,e),sn(this,n,t))}),a)),a.f=b}(a.c,a.h)):(t||(b=Ye(b,tn)),a.c=new nn(b,a.h))}function Ke(a,b,t){a.c.set(b,t)}function He(a,b,t){q(t)||(t=[String(t)]),sn(a.c,b,t)}function Ge(a){return Ke(a,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^S()).toString(36)),a}function ze(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function Ye(a,b,t){return h(a)?(a=encodeURI(a).replace(b,Xe),t&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null}function Xe(a){return"%"+((a=a.charCodeAt(0))>>4&15).toString(16)+(15&a).toString(16)}qe.prototype.toString=function(){var a=[],b=this.f;b&&a.push(Ye(b,Je,!0),":");var t=this.b;return(t||"file"==b)&&(a.push("//"),(b=this.j)&&a.push(Ye(b,Je,!0),"@"),a.push(encodeURIComponent(String(t)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(t=this.i)&&a.push(":",String(t))),(t=this.a)&&(this.b&&"/"!=t.charAt(0)&&a.push("/"),a.push(Ye(t,"/"==t.charAt(0)?Ze:$e,!0))),(t=this.c.toString())&&a.push("?",t),(t=this.g)&&a.push("#",Ye(t,en)),a.join("")},qe.prototype.resolve=function(a){var b=Ve(this),t=!!a.f;t?Be(b,a.f):t=!!a.j,t?b.j=a.j:t=!!a.b,t?je(b,a.b):t=null!=a.i;var e=a.a;if(t)We(b,a.i);else if(t=!!a.a){if("/"!=e.charAt(0))if(this.b&&!this.a)e="/"+e;else{var n=b.a.lastIndexOf("/");-1!=n&&(e=b.a.substr(0,n+1)+e)}if(".."==(n=e)||"."==n)e="";else if(x(n,"./")||x(n,"/.")){e=0==n.lastIndexOf("/",0),n=n.split("/");for(var r=[],o=0;o=a.f}function _n(a){return a.b?1:a.a?a.a.a.c:0}function wn(a,b){return a.b?a=a.b==b:a.a?(b=dn(b),a=Fe(a.a.a.b,b)):a=!1,a}function dd(a,b){a.a?a.a.add(b):a.b=b}function En(a,b){var t;a.b&&a.b==b?a.b=null:((t=a.a)&&(t=dn(b),t=Fe(a.a.a.b,t)),t&&Le(a.a.a,dn(b)))}function Tn(a){if(null!=a.b)return a.c.concat(a.b.j);if(null!=a.a&&0!=a.a.a.c){var b=a.c;return A(a.a.C(),(function(t){b=b.concat(t.j)})),b}return k(a.c)}function Sn(){}function Cn(){this.a=new Sn}function In(a,b,t){var e=t||"";try{Pe(a,(function(t,n){var r=t;m(t)&&(r=Pt(t)),b.push(e+n+"="+encodeURIComponent(r))}))}catch(t){throw b.push(e+"type="+encodeURIComponent("_badmap")),t}}function Nn(a,b,t,e,n){try{b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,n(e)}catch(t){}}mn.prototype.cancel=function(){this.c=Tn(this),this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(A(this.a.C(),(function(a){a.cancel()})),function(a){a.b={},a.a.length=0,a.c=0}(this.a.a))},Sn.prototype.stringify=function(a){return c.JSON.stringify(a,void 0)},Sn.prototype.parse=function(a){return c.JSON.parse(a,void 0)};var An=c.JSON.parse;function Dn(a){Rt.call(this),this.headers=new xe,this.H=a||null,this.b=!1,this.s=this.a=null,this.A="",this.h=0,this.f="",this.g=this.w=this.l=this.v=!1,this.o=0,this.m=null,this.I=kn,this.D=this.F=!1}C(Dn,Rt);var kn="",Rn=/^https?$/i,On=["POST","PUT"];function Pn(a){return"content-type"==a.toLowerCase()}function xn(a,b){a.b=!1,a.a&&(a.g=!0,a.a.abort(),a.g=!1),a.f=b,a.h=5,Ln(a),Fn(a)}function Ln(a){a.v||(a.v=!0,a.dispatchEvent("complete"),a.dispatchEvent("error"))}function Mn(a){if(a.b&&void 0!==o&&(!a.s[1]||4!=Un(a)||2!=a.T()))if(a.l&&4==Un(a))Gt(a.Fa,0,a);else if(a.dispatchEvent("readystatechange"),4==Un(a)){a.b=!1;try{var t,b=a.T();t:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var e=!0;break t;default:e=!1}if(!(t=e)){var n;if(n=0===b){var r=String(a.A).match(Ue)[1]||null;if(!r&&c.self&&c.self.location){var h=c.self.location.protocol;r=h.substr(0,h.length-1)}n=!Rn.test(r?r.toLowerCase():"")}t=n}t?(a.dispatchEvent("complete"),a.dispatchEvent("success")):(a.h=6,a.f=a.za()+" ["+a.T()+"]",Ln(a))}finally{Fn(a)}}}function Fn(a,b){if(a.a){td(a);var t=a.a,e=a.s[0]?d:null;a.a=null,a.s=null,b||a.dispatchEvent("ready");try{t.onreadystatechange=e}catch(t){}}}function td(a){a.a&&a.D&&(a.a.ontimeout=null),a.m&&(c.clearTimeout(a.m),a.m=null)}function Un(a){return a.a?a.a.readyState:0}function qn(a,b){return a.a?a.a.getResponseHeader(b):null}function Vn(a,b,t){t:{for(e in t){var e=!1;break t}e=!0}if(e)return a;if(t=function(a){var b="";return U(a,(function(t,e){b+=e,b+=":",b+=t,b+="\r\n"})),b}(t),h(a)){if(b=encodeURIComponent(String(b)),b+=t=null!=t?"="+encodeURIComponent(String(t)):""){if(0>(t=a.indexOf("#"))&&(t=a.length),0>(e=a.indexOf("?"))||e>t){e=t;var n=""}else n=a.substring(e+1,t);t=(a=[a.substr(0,e),n,a.substr(t)])[1],a[1]=b?t?t+"&"+b:b:t,a=a[0]+(a[1]?"?"+a[1]:"")+a[2]}return a}return Ke(a,b,t),a}function Bn(a){this.f=[],this.F=new fn,this.ga=this.pa=this.B=this.ha=this.a=this.I=this.j=this.V=this.g=this.J=this.i=null,this.Ra=this.P=0,this.Pa=!!f("internalChannelParams.failFast",a),this.ia=this.w=this.s=this.l=this.h=this.c=null,this.oa=!0,this.m=this.ra=this.O=-1,this.S=this.v=this.A=0,this.Oa=f("internalChannelParams.baseRetryDelayMs",a)||5e3,this.Sa=f("internalChannelParams.retryDelaySeedMs",a)||1e4,this.Qa=f("internalChannelParams.forwardChannelMaxRetries",a)||2,this.qa=f("internalChannelParams.forwardChannelRequestTimeoutMs",a)||2e4,this.La=a&&a.Ab||void 0,this.D=void 0,this.R=a&&a.supportsCrossDomainXhr||!1,this.H="",this.b=new mn(a&&a.concurrentRequestLimit),this.ja=new Cn,this.o=!a||void 0===a.backgroundChannelTest||a.backgroundChannelTest,(this.W=a&&a.fastHandshake||!1)&&!this.o&&(this.o=!0),a&&a.forceLongPolling&&(this.oa=!1),this.fa=void 0}function jn(a){if(Wn(a),3==a.u){var b=a.P++,t=Ve(a.B);Ke(t,"SID",a.H),Ke(t,"RID",b),Ke(t,"TYPE","terminate"),Gn(a,t),(b=new ve(a,b,void 0)).F=2,b.f=Ge(Ve(t)),t=!1,c.navigator&&c.navigator.sendBeacon&&(t=c.navigator.sendBeacon(b.f.toString(),"")),!t&&c.Image&&((new Image).src=b.f,t=!0),t||(b.a=b.g.$(null),b.a.ca(b.f)),b.v=S(),Ne(b)}nr(a)}function Wn(a){a.w&&(a.w.abort(),a.w=null),a.a&&(a.a.cancel(),a.a=null),a.l&&(c.clearTimeout(a.l),a.l=null),$n(a),a.b.cancel(),a.h&&(l(a.h)&&c.clearTimeout(a.h),a.h=null)}function Qn(a,b){a.f.push(new yn(a.Ra++,b)),3==a.u&&Kn(a)}function Kn(a){bn(a.b)||a.h||(a.h=!0,Bt(a.Ia,a),a.A=0)}function Hn(a,b){var t;t=b?b.W:a.P++;var e=Ve(a.B);Ke(e,"SID",a.H),Ke(e,"RID",t),Ke(e,"AID",a.O),Gn(a,e),a.g&&a.i&&Vn(e,a.g,a.i),t=new ve(a,t,a.A+1),null===a.g&&(t.h=a.i),b&&(a.f=b.j.concat(a.f)),b=zn(a,t,1e3),t.setTimeout(Math.round(.5*a.qa)+Math.round(.5*a.qa*Math.random())),dd(a.b,t),Ee(t,e,b)}function Gn(a,b){a.c&&Pe({},(function(t,e){Ke(b,e,t)}))}function zn(a,b,t){t=Math.min(a.f.length,t);var e=a.c?u(a.c.Ta,a.c,a):null;t:for(var n=a.f,r=-1;;){var o=["count="+t];-1==r?0(l-=r))r=Math.max(0,n[h].b-100),c=!1;else try{In(f,o,"req"+l+"_")}catch(t){e&&e(f)}}if(c){e=o.join("&");break t}}return a=a.f.splice(0,t),b.j=a,e}function Yn(a){a.a||a.l||(a.S=1,Bt(a.Ha,a),a.v=0)}function Xn(a){return!(a.a||a.l||3<=a.v)&&(a.S++,a.l=se(u(a.Ha,a),Zn(a,a.v)),a.v++,!0)}function Jn(a,b,t){var e=b.l;e&&vn(a.b,e),a.ia=a.oa&&t,a.m=b.c,a.B=rr(a,null,a.ha),Kn(a)}function $n(a){null!=a.s&&(c.clearTimeout(a.s),a.s=null)}function Zn(a,b){var t=a.Oa+Math.floor(Math.random()*a.Sa);return a.ma()||(t*=2),t*b}function er(a,b){if(2==b){var t=null;a.c&&(t=null);var e=u(a.fb,a);t||(t=new qe("//www.google.com/images/cleardot.gif"),c.location&&"http"==c.location.protocol||Be(t,"https"),Ge(t)),function(a,b){var t=new te;if(c.Image){var e=new Image;e.onload=T(Nn,t,e,"TestLoadImage: loaded",!0,b),e.onerror=T(Nn,t,e,"TestLoadImage: error",!1,b),e.onabort=T(Nn,t,e,"TestLoadImage: abort",!1,b),e.ontimeout=T(Nn,t,e,"TestLoadImage: timeout",!1,b),c.setTimeout((function(){e.ontimeout&&e.ontimeout()}),1e4),e.src=a}else b(!1)}(t.toString(),e)}else oe(2);a.u=0,a.c&&a.c.ta(b),nr(a),Wn(a)}function nr(a){a.u=0,a.m=-1,a.c&&(0==Tn(a.b).length&&0==a.f.length||(a.b.c.length=0,k(a.f),a.f.length=0),a.c.sa())}function rr(a,b,t){var e=function(a){return a instanceof qe?Ve(a):new qe(a,void 0)}(t);if(""!=e.b)b&&je(e,b+"."+e.b),We(e,e.i);else{var n,r=c.location;n=b?b+"."+r.hostname:r.hostname,e=function(a,b,t,e){var n=new qe(null,void 0);return a&&Be(n,a),b&&je(n,b),t&&We(n,t),e&&(n.a=e),n}(r.protocol,n,+r.port,t)}return a.V&&U(a.V,(function(t,n){Ke(e,n,t)})),b=a.j,t=a.I,b&&t&&Ke(e,b,t),Ke(e,"VER",a.wa),Gn(a,e),e}function ir(){}function or(){if(H&&!(10<=Number(et)))throw Error("Environmental error: no available transport.")}function ar(a,b){Rt.call(this),this.a=new Bn(b),this.g=a,this.m=b&&b.testUrl?b.testUrl:function(a){for(var b=arguments[0],t=1;tb?null:h(a)?a.charAt(b):a[b]}(n.K()),t=c.FormData&&a instanceof c.FormData,!(0<=N(On,b))||e||t||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),n.forEach((function(t,e){this.a.setRequestHeader(e,t)}),this),this.I&&(this.a.responseType=this.I),"withCredentials"in this.a&&this.a.withCredentials!==this.F&&(this.a.withCredentials=this.F);try{td(this),0b[2]&&this.ia&&0==this.v&&!this.s&&(this.s=se(u(this.Za,this),6e3));if(1>=_n(this.b)&&this.fa){try{this.fa()}catch(t){}this.fa=void 0}}else er(this,11)}else if((a.s||this.a==a)&&$n(this),!R(b))for(b=t=this.ja.a.parse(b),t=0;t=a.b.f-(a.h?1:0))&&(a.h?(a.f=b.j.concat(a.f),!0):!(1==a.u||2==a.u||a.A>=(a.Pa?0:a.Qa))&&(a.h=se(u(a.Ia,a,b),Zn(a,a.A)),a.A++,!0))}(this,a)||2==t&&Xn(this)))switch(b&&0n?r.push(t.substring(o,n)):r.push(t.substring(o,o+e));return r};function Q(t,e){for(var n in t)t.hasOwnProperty(n)&&e(n,t[n])}var K=function(t){f.assert(!L(t),"Invalid JSON number");var s,e,n,r,i,o,c;for(0===t?(e=0,n=0,s=1/t==-1/0?1:0):(s=t<0,(t=Math.abs(t))>=Math.pow(2,-1022)?(e=(r=Math.min(Math.floor(Math.log(t)/Math.LN2),1023))+1023,n=Math.round(t*Math.pow(2,52-r)-Math.pow(2,52))):(e=0,n=Math.round(t/Math.pow(2,-1074)))),o=[],i=52;i;i-=1)o.push(n%2?1:0),n=Math.floor(n/2);for(i=11;i;i-=1)o.push(e%2?1:0),e=Math.floor(e/2);o.push(s?1:0),o.reverse(),c=o.join("");var h="";for(i=0;i<64;i+=8){var l=parseInt(c.substr(i,8),2).toString(16);1===l.length&&(l="0"+l),h+=l}return h.toLowerCase()},H=new RegExp("^-?\\d{1,10}$"),G=function(t){if(H.test(t)){var e=Number(t);if(e>=-2147483648&&e<=2147483647)return e}return null},z=function(t){try{t()}catch(t){setTimeout((function(){var e=t.stack||"";throw x("Exception was thrown by user callback.",e),t}),Math.floor(0))}},Y=function(){return("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},X=function(t,time){var e=setTimeout(t,time);return"object"==typeof e&&e.unref&&e.unref(),e},J=function(){function t(t,e){if(void 0===e){this.pieces_=t.split("/");for(var n=0,i=0;i0&&(this.pieces_[n]=this.pieces_[i],n++);this.pieces_.length=n,this.pieceNum_=0}else this.pieces_=t,this.pieceNum_=e}return Object.defineProperty(t,"Empty",{get:function(){return new t("")},enumerable:!0,configurable:!0}),t.prototype.getFront=function(){return this.pieceNum_>=this.pieces_.length?null:this.pieces_[this.pieceNum_]},t.prototype.getLength=function(){return this.pieces_.length-this.pieceNum_},t.prototype.popFront=function(){var e=this.pieceNum_;return e=this.pieces_.length)return null;for(var e=[],i=this.pieceNum_;i0&&n.push(r[i])}return new t(n,0)},t.prototype.isEmpty=function(){return this.pieceNum_>=this.pieces_.length},t.relativePath=function(e,n){var r=e.getFront(),o=n.getFront();if(null===r)return n;if(r===o)return t.relativePath(e.popFront(),n.popFront());throw new Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+e+")")},t.comparePaths=function(t,e){for(var n=t.slice(),r=e.slice(),i=0;it.getLength())return!1;for(;i0&&(this.byteLength_+=1),this.parts_.push(t),this.byteLength_+=f.stringLength(t),this.checkValid_()},t.prototype.pop=function(){var t=this.parts_.pop();this.byteLength_-=f.stringLength(t),this.parts_.length>0&&(this.byteLength_-=1)},t.prototype.checkValid_=function(){if(this.byteLength_>t.MAX_PATH_LENGTH_BYTES)throw new Error(this.errorPrefix_+"has a key path longer than "+t.MAX_PATH_LENGTH_BYTES+" bytes ("+this.byteLength_+").");if(this.parts_.length>t.MAX_PATH_DEPTH)throw new Error(this.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+t.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},t.prototype.toErrorString=function(){return 0==this.parts_.length?"":"in property '"+this.parts_.join(".")+"'"},t}(),Z="long_polling",tt=function(){function t(t,e,n,r,o,c){void 0===o&&(o=""),void 0===c&&(c=!1),this.secure=e,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=o,this.includeNamespaceInQueryParams=c,this.host=t.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=_.get("host:"+t)||this.host}return t.prototype.needsQueryParam=function(){return this.host!==this.internalHost||this.isCustomHost()||this.includeNamespaceInQueryParams},t.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},t.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},t.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},t.prototype.updateHost=function(t){t!==this.internalHost&&(this.internalHost=t,this.isCacheableHost()&&_.set("host:"+this.host,this.internalHost))},t.prototype.connectionURL=function(t,e){var n;if(f.assert("string"==typeof t,"typeof type must == string"),f.assert("object"==typeof e,"typeof params must == object"),"websocket"===t)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(t!==Z)throw new Error("Unknown connection type: "+t);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(e.ns=this.namespace);var r=[];return Q(e,(function(t,e){r.push(t+"="+e)})),n+r.join("&")},t.prototype.toString=function(){var t=this.toURLString();return this.persistenceKey&&(t+="<"+this.persistenceKey+">"),t},t.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},t}();var et,nt,it,ot,at,st=function(t){var e=ut(t),n=e.namespace;"firebase"===e.domain&&P(e.host+" is no longer supported. Please use .firebaseio.com instead"),n&&"undefined"!=n||"localhost"===e.domain||P("Cannot parse Firebase url. Please use https://.firebaseio.com"),e.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&x("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");var r="ws"===e.scheme||"wss"===e.scheme;return{repoInfo:new tt(e.host,e.secure,n,r,"",n!=e.subdomain),path:new J(e.pathString)}},ut=function(t){var e="",n="",r="",o="",c="",h=!0,f="https",d=443;if("string"==typeof t){var y=t.indexOf("//");y>=0&&(f=t.substring(0,y-1),t=t.substring(y+2));var m=t.indexOf("/");-1===m&&(m=t.length);var v=t.indexOf("?");-1===v&&(v=t.length),e=t.substring(0,Math.min(m,v)),m0){var r=n[i];try{r=decodeURIComponent(r.replace(/\+/g," "))}catch(t){}e+="/"+r}return e}(t.substring(m,v)));var _=function(t){var e,n,r={};"?"===t.charAt(0)&&(t=t.substring(1));try{for(var o=l.__values(t.split("&")),c=o.next();!c.done;c=o.next()){var h=c.value;if(0!==h.length){var f=h.split("=");2===f.length?r[decodeURIComponent(f[0])]=decodeURIComponent(f[1]):x("Invalid query segment '"+h+"' in query '"+t+"'")}}}catch(t){e={error:t}}finally{try{c&&!c.done&&(n=o.return)&&n.call(o)}finally{if(e)throw e.error}}return r}(t.substring(Math.min(t.length,v)));(y=e.indexOf(":"))>=0?(h="https"===f||"wss"===f,d=parseInt(e.substring(y+1),10)):y=t.length;var w=e.split(".");3===w.length?(n=w[1],c=r=w[0].toLowerCase()):2===w.length?n=w[0]:"localhost"===w[0].slice(0,y).toLowerCase()&&(n="localhost"),"ns"in _&&(c=_.ns)}return{host:e,port:d,domain:n,subdomain:r,secure:h,scheme:f,pathString:o,namespace:c}},ct=/[\[\].#$\/\u0000-\u001F\u007F]/,ht=/[\[\].#$\u0000-\u001F\u007F]/,lt=function(t){return"string"==typeof t&&0!==t.length&&!ct.test(t)},ft=function(t){return"string"==typeof t&&0!==t.length&&!ht.test(t)},pt=function(t){return null===t||"string"==typeof t||"number"==typeof t&&!L(t)||t&&"object"==typeof t&&f.contains(t,".sv")},yt=function(t,e,data,path,n){n&&void 0===data||mt(f.errorPrefix(t,e,n),data,path)},mt=function(t,data,e){var path=e instanceof J?new $(e,t):e;if(void 0===data)throw new Error(t+"contains undefined "+path.toErrorString());if("function"==typeof data)throw new Error(t+"contains a function "+path.toErrorString()+" with contents = "+data.toString());if(L(data))throw new Error(t+"contains "+data.toString()+" "+path.toErrorString());if("string"==typeof data&&data.length>10485760/3&&f.stringLength(data)>10485760)throw new Error(t+"contains a string greater than 10485760 utf8 bytes "+path.toErrorString()+" ('"+data.substring(0,50)+"...')");if(data&&"object"==typeof data){var n=!1,r=!1;if(Q(data,(function(e,o){if(".value"===e)n=!0;else if(".priority"!==e&&".sv"!==e&&(r=!0,!lt(e)))throw new Error(t+" contains an invalid key ("+e+") "+path.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');path.push(e),mt(t,o,path),path.pop()})),n&&r)throw new Error(t+' contains ".value" child '+path.toErrorString()+" in addition to actual children.")}},gt=function(t,e,data,path,n){if(!n||void 0!==data){var r=f.errorPrefix(t,e,n);if(!data||"object"!=typeof data||Array.isArray(data))throw new Error(r+" must be an object containing the children to replace.");var o=[];Q(data,(function(t,e){var n=new J(t);if(mt(r,e,path.child(n)),".priority"===n.getBack()&&!pt(e))throw new Error(r+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(n)})),function(t,e){var i,n;for(i=0;i=0;i--)n[i]=et.charAt(t%64),t=Math.floor(t/64);f.assert(0===t,"Cannot push at time == 0");var r=n.join("");if(e){for(i=11;i>=0&&63===it[i];i--)it[i]=0;it[i]++}else for(i=0;i<12;i++)it[i]=Math.floor(64*Math.random());for(i=0;i<12;i++)r+=et.charAt(it[i]);return f.assert(20===r.length,"nextPushId: Length should be 20."),r}),Dt=function(){function t(t,e){this.name=t,this.node=e}return t.Wrap=function(e,n){return new t(e,n)},t}(),kt=function(){function t(){}return t.prototype.getCompare=function(){return this.compare.bind(this)},t.prototype.indexedValueChanged=function(t,e){var n=new Dt(M,t),r=new Dt(M,e);return 0!==this.compare(n,r)},t.prototype.minPost=function(){return Dt.MIN},t}(),Rt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),Object.defineProperty(e,"__EMPTY_NODE",{get:function(){return ot},set:function(t){ot=t},enumerable:!0,configurable:!0}),e.prototype.compare=function(a,b){return U(a.name,b.name)},e.prototype.isDefinedOn=function(t){throw f.assertionError("KeyIndex.isDefinedOn not expected to be called.")},e.prototype.indexedValueChanged=function(t,e){return!1},e.prototype.minPost=function(){return Dt.MIN},e.prototype.maxPost=function(){return new Dt(F,ot)},e.prototype.makePost=function(t,e){return f.assert("string"==typeof t,"KeyIndex indexValue must always be a string."),new Dt(t,ot)},e.prototype.toString=function(){return".key"},e}(kt),Ot=new Rt;var Pt,xt,Lt,Mt=function(t){return"number"==typeof t?"number:"+K(t):"string:"+t},Ft=function(t){if(t.isLeafNode()){var e=t.val();f.assert("string"==typeof e||"number"==typeof e||"object"==typeof e&&f.contains(e,".sv"),"Priority must be a string or number.")}else f.assert(t===at||t.isEmpty(),"priority of unexpected type.");f.assert(t===at||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")},Ut=function(){function t(e,n){void 0===n&&(n=t.__childrenNodeConstructor.EMPTY_NODE),this.value_=e,this.priorityNode_=n,this.lazyHash_=null,f.assert(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Ft(this.priorityNode_)}return Object.defineProperty(t,"__childrenNodeConstructor",{get:function(){return Pt},set:function(t){Pt=t},enumerable:!0,configurable:!0}),t.prototype.isLeafNode=function(){return!0},t.prototype.getPriority=function(){return this.priorityNode_},t.prototype.updatePriority=function(e){return new t(this.value_,e)},t.prototype.getImmediateChild=function(e){return".priority"===e?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE},t.prototype.getChild=function(path){return path.isEmpty()?this:".priority"===path.getFront()?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE},t.prototype.hasChild=function(){return!1},t.prototype.getPredecessorChildName=function(t,e){return null},t.prototype.updateImmediateChild=function(e,n){return".priority"===e?this.updatePriority(n):n.isEmpty()&&".priority"!==e?this:t.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)},t.prototype.updateChild=function(path,e){var n=path.getFront();return null===n?e:e.isEmpty()&&".priority"!==n?this:(f.assert(".priority"!==n||1===path.getLength(),".priority must be the last token in a path"),this.updateImmediateChild(n,t.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(),e)))},t.prototype.isEmpty=function(){return!1},t.prototype.numChildren=function(){return 0},t.prototype.forEachChild=function(t,e){return!1},t.prototype.val=function(t){return t&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()},t.prototype.hash=function(){if(null===this.lazyHash_){var t="";this.priorityNode_.isEmpty()||(t+="priority:"+Mt(this.priorityNode_.val())+":");var e=typeof this.value_;t+=e+":",t+="number"===e?K(this.value_):this.value_,this.lazyHash_=C(t)}return this.lazyHash_},t.prototype.getValue=function(){return this.value_},t.prototype.compareTo=function(e){return e===t.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof t.__childrenNodeConstructor?-1:(f.assert(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))},t.prototype.compareToLeafNode_=function(e){var n=typeof e.value_,r=typeof this.value_,o=t.VALUE_TYPE_ORDER.indexOf(n),c=t.VALUE_TYPE_ORDER.indexOf(r);return f.assert(o>=0,"Unknown leaf type: "+n),f.assert(c>=0,"Unknown leaf type: "+r),o===c?"object"===r?0:this.value_0},t.prototype.peek=function(){if(0===this.nodeStack_.length)return null;var t=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value}},t}(),Wt=function(){function t(e,n,r,o,c){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=o?o:Kt.EMPTY_NODE,this.right=null!=c?c:Kt.EMPTY_NODE}return t.prototype.copy=function(e,n,r,o,c){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=o?o:this.left,null!=c?c:this.right)},t.prototype.count=function(){return this.left.count()+1+this.right.count()},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min_=function(){return this.left.isEmpty()?this:this.left.min_()},t.prototype.minKey=function(){return this.min_().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r,o;return(o=(r=n(t,(o=this).key))<0?o.copy(null,null,null,o.left.insert(t,e,n),null):0===r?o.copy(null,e,null,null,null):o.copy(null,null,null,null,o.right.insert(t,e,n))).fixUp_()},t.prototype.removeMin_=function(){if(this.left.isEmpty())return Kt.EMPTY_NODE;var t=this;return t.left.isRed_()||t.left.left.isRed_()||(t=t.moveRedLeft_()),(t=t.copy(null,null,null,t.left.removeMin_(),null)).fixUp_()},t.prototype.remove=function(t,e){var n,r;if(e(t,(n=this).key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(t,e),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===e(t,n.key)){if(n.right.isEmpty())return Kt.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(t,e))}return n.fixUp_()},t.prototype.isRed_=function(){return this.color},t.prototype.fixUp_=function(){var t=this;return t.right.isRed_()&&!t.left.isRed_()&&(t=t.rotateLeft_()),t.left.isRed_()&&t.left.left.isRed_()&&(t=t.rotateRight_()),t.left.isRed_()&&t.right.isRed_()&&(t=t.colorFlip_()),t},t.prototype.moveRedLeft_=function(){var t=this.colorFlip_();return t.right.left.isRed_()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight_())).rotateLeft_()).colorFlip_()),t},t.prototype.moveRedRight_=function(){var t=this.colorFlip_();return t.left.left.isRed_()&&(t=(t=t.rotateRight_()).colorFlip_()),t},t.prototype.rotateLeft_=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight_=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip_=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth_=function(){var t=this.check_();return Math.pow(2,t)<=this.count()+1},t.prototype.check_=function(){var t;if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");if((t=this.left.check_())!==this.right.check_())throw new Error("Black depths differ");return t+(this.isRed_()?0:1)},t.RED=!0,t.BLACK=!1,t}(),Qt=function(){function t(){}return t.prototype.copy=function(t,e,n,r,o){return this},t.prototype.insert=function(t,e,n){return new Wt(t,e,null)},t.prototype.remove=function(t,e){return this},t.prototype.count=function(){return 0},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.check_=function(){return 0},t.prototype.isRed_=function(){return!1},t}(),Kt=function(){function t(e,n){void 0===n&&(n=t.EMPTY_NODE),this.comparator_=e,this.root_=n}return t.prototype.insert=function(e,n){return new t(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,Wt.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Wt.BLACK,null,null))},t.prototype.get=function(t){for(var e,n=this.root_;!n.isEmpty();){if(0===(e=this.comparator_(t,n.key)))return n.value;e<0?n=n.left:e>0&&(n=n.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e,n=this.root_,r=null;!n.isEmpty();){if(0===(e=this.comparator_(t,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}e<0?n=n.left:e>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")},t.prototype.isEmpty=function(){return this.root_.isEmpty()},t.prototype.count=function(){return this.root_.count()},t.prototype.minKey=function(){return this.root_.minKey()},t.prototype.maxKey=function(){return this.root_.maxKey()},t.prototype.inorderTraversal=function(t){return this.root_.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.root_.reverseTraversal(t)},t.prototype.getIterator=function(t){return new jt(this.root_,null,this.comparator_,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new jt(this.root_,t,this.comparator_,!1,e)},t.prototype.getReverseIteratorFrom=function(t,e){return new jt(this.root_,t,this.comparator_,!0,e)},t.prototype.getReverseIterator=function(t){return new jt(this.root_,null,this.comparator_,!0,t)},t.EMPTY_NODE=new Qt,t}(),Ht=Math.log(2),Gt=function(){function t(t){var e;this.count=(e=t+1,parseInt(Math.log(e)/Ht,10)),this.current_=this.count-1;var n,mask=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=t+1&mask}return t.prototype.nextBitIsOne=function(){var t=!(this.bits_&1<0;)r.getNext(),o=r.peek();return r},t.prototype.compareTo=function(t){return this.isEmpty()?t.isEmpty()?0:-1:t.isLeafNode()||t.isEmpty()?1:t===te?-1:0},t.prototype.withIndex=function(e){if(e===Ot||this.indexMap_.hasIndex(e))return this;var n=this.indexMap_.addIndex(e,this.children_);return new t(this.children_,this.priorityNode_,n)},t.prototype.isIndexed=function(t){return t===Ot||this.indexMap_.hasIndex(t)},t.prototype.equals=function(t){if(t===this)return!0;if(t.isLeafNode())return!1;var e=t;if(this.getPriority().equals(e.getPriority())){if(this.children_.count()===e.children_.count()){for(var n=this.getIterator(Bt),r=e.getIterator(Bt),o=n.getNext(),c=r.getNext();o&&c;){if(o.name!==c.name||!o.node.equals(c.node))return!1;o=n.getNext(),c=r.getNext()}return null===o&&null===c}return!1}return!1},t.prototype.resolveIndex_=function(t){return t===Ot?null:this.indexMap_.get(t.toString())},t.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,t}(),te=new(function(t){function e(){return t.call(this,new Kt($t),Zt.EMPTY_NODE,Xt.Default)||this}return l.__extends(e,t),e.prototype.compareTo=function(t){return t===this?0:1},e.prototype.equals=function(t){return t===this},e.prototype.getPriority=function(){return this},e.prototype.getImmediateChild=function(t){return Zt.EMPTY_NODE},e.prototype.isEmpty=function(){return!1},e}(Zt));Object.defineProperties(Dt,{MIN:{value:new Dt(M,Zt.EMPTY_NODE)},MAX:{value:new Dt(F,te)}}),Rt.__EMPTY_NODE=Zt.EMPTY_NODE,Ut.__childrenNodeConstructor=Zt,at=te,function(t){Lt=t}(te);var ee=!0;function ne(t,e){if(void 0===e&&(e=null),null===t)return Zt.EMPTY_NODE;if("object"==typeof t&&".priority"in t&&(e=t[".priority"]),f.assert(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"==typeof t&&".value"in t&&null!==t[".value"]&&(t=t[".value"]),"object"!=typeof t||".sv"in t)return new Ut(t,ne(e));if(t instanceof Array||!ee){var n=Zt.EMPTY_NODE;return Q(t,(function(e,r){if(f.contains(t,e)&&"."!==e.substring(0,1)){var o=ne(r);!o.isLeafNode()&&o.isEmpty()||(n=n.updateImmediateChild(e,o))}})),n.updatePriority(ne(e))}var r=[],o=!1;if(Q(t,(function(t,e){if("."!==t.substring(0,1)){var n=ne(e);n.isEmpty()||(o=o||!n.getPriority().isEmpty(),r.push(new Dt(t,n)))}})),0==r.length)return Zt.EMPTY_NODE;var c=zt(r,Jt,(function(t){return t.name}),$t);if(o){var h=zt(r,Bt.getCompare());return new Zt(c,ne(e),new Xt({".priority":h},{".priority":Bt}))}return new Zt(c,ne(e),Xt.Default)}!function(t){xt=t}(ne);var re,ie,oe=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.compare=function(a,b){var t=a.node.compareTo(b.node);return 0===t?U(a.name,b.name):t},e.prototype.isDefinedOn=function(t){return!0},e.prototype.indexedValueChanged=function(t,e){return!t.equals(e)},e.prototype.minPost=function(){return Dt.MIN},e.prototype.maxPost=function(){return Dt.MAX},e.prototype.makePost=function(t,e){var n=ne(t);return new Dt(e,n)},e.prototype.toString=function(){return".value"},e}(kt)),ae=function(t){function e(e){var n=t.call(this)||this;return n.indexPath_=e,f.assert(!e.isEmpty()&&".priority"!==e.getFront(),"Can't create PathIndex with empty path or .priority key"),n}return l.__extends(e,t),e.prototype.extractChild=function(t){return t.getChild(this.indexPath_)},e.prototype.isDefinedOn=function(t){return!t.getChild(this.indexPath_).isEmpty()},e.prototype.compare=function(a,b){var t=this.extractChild(a.node),e=this.extractChild(b.node),n=t.compareTo(e);return 0===n?U(a.name,b.name):n},e.prototype.makePost=function(t,e){var n=ne(t),r=Zt.EMPTY_NODE.updateChild(this.indexPath_,n);return new Dt(e,r)},e.prototype.maxPost=function(){var t=Zt.EMPTY_NODE.updateChild(this.indexPath_,te);return new Dt(F,t)},e.prototype.toString=function(){return this.indexPath_.slice().join("/")},e}(kt),se=function(){function t(t,e,n){this.node_=t,this.ref_=e,this.index_=n}return t.prototype.val=function(){return f.validateArgCount("DataSnapshot.val",0,0,arguments.length),this.node_.val()},t.prototype.exportVal=function(){return f.validateArgCount("DataSnapshot.exportVal",0,0,arguments.length),this.node_.val(!0)},t.prototype.toJSON=function(){return f.validateArgCount("DataSnapshot.toJSON",0,1,arguments.length),this.exportVal()},t.prototype.exists=function(){return f.validateArgCount("DataSnapshot.exists",0,0,arguments.length),!this.node_.isEmpty()},t.prototype.child=function(e){f.validateArgCount("DataSnapshot.child",0,1,arguments.length),e=String(e),wt("DataSnapshot.child",1,e,!1);var n=new J(e),r=this.ref_.child(n);return new t(this.node_.getChild(n),r,Bt)},t.prototype.hasChild=function(t){f.validateArgCount("DataSnapshot.hasChild",1,1,arguments.length),wt("DataSnapshot.hasChild",1,t,!1);var e=new J(t);return!this.node_.getChild(e).isEmpty()},t.prototype.getPriority=function(){return f.validateArgCount("DataSnapshot.getPriority",0,0,arguments.length),this.node_.getPriority().val()},t.prototype.forEach=function(e){var n=this;if(f.validateArgCount("DataSnapshot.forEach",1,1,arguments.length),f.validateCallback("DataSnapshot.forEach",1,e,!1),this.node_.isLeafNode())return!1;var r=this.node_;return!!r.forEachChild(this.index_,(function(r,o){return e(new t(o,n.ref_.child(r),Bt))}))},t.prototype.hasChildren=function(){return f.validateArgCount("DataSnapshot.hasChildren",0,0,arguments.length),!this.node_.isLeafNode()&&!this.node_.isEmpty()},Object.defineProperty(t.prototype,"key",{get:function(){return this.ref_.getKey()},enumerable:!0,configurable:!0}),t.prototype.numChildren=function(){return f.validateArgCount("DataSnapshot.numChildren",0,0,arguments.length),this.node_.numChildren()},t.prototype.getRef=function(){return f.validateArgCount("DataSnapshot.ref",0,0,arguments.length),this.ref_},Object.defineProperty(t.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),t}(),ue=function(){function t(t,e,n,r){this.eventType=t,this.eventRegistration=e,this.snapshot=n,this.prevName=r}return t.prototype.getPath=function(){var t=this.snapshot.getRef();return"value"===this.eventType?t.path:t.getParent().path},t.prototype.getEventType=function(){return this.eventType},t.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},t.prototype.toString=function(){return this.getPath().toString()+":"+this.eventType+":"+f.stringify(this.snapshot.exportVal())},t}(),ce=function(){function t(t,e,path){this.eventRegistration=t,this.error=e,this.path=path}return t.prototype.getPath=function(){return this.path},t.prototype.getEventType=function(){return"cancel"},t.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},t.prototype.toString=function(){return this.path.toString()+":cancel"},t}(),he=function(){function t(t,e,n){this.callback_=t,this.cancelCallback_=e,this.context_=n}return t.prototype.respondsTo=function(t){return"value"===t},t.prototype.createEvent=function(t,e){var n=e.getQueryParams().getIndex();return new ue("value",this,new se(t.snapshotNode,e.getRef(),n))},t.prototype.getEventRunner=function(t){var e=this.context_;if("cancel"===t.getEventType()){f.assert(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(e,t.error)}}var r=this.callback_;return function(){r.call(e,t.snapshot)}},t.prototype.createCancelEvent=function(t,path){return this.cancelCallback_?new ce(this,t,path):null},t.prototype.matches=function(e){return e instanceof t&&(!e.callback_||!this.callback_||e.callback_===this.callback_&&e.context_===this.context_)},t.prototype.hasAnyCallback=function(){return null!==this.callback_},t}(),le=function(){function t(t,e,n){this.callbacks_=t,this.cancelCallback_=e,this.context_=n}return t.prototype.respondsTo=function(t){var e="children_added"===t?"child_added":t;return e="children_removed"===e?"child_removed":e,f.contains(this.callbacks_,e)},t.prototype.createCancelEvent=function(t,path){return this.cancelCallback_?new ce(this,t,path):null},t.prototype.createEvent=function(t,e){f.assert(null!=t.childName,"Child events should have a childName.");var n=e.getRef().child(t.childName),r=e.getQueryParams().getIndex();return new ue(t.type,this,new se(t.snapshotNode,n,r),t.prevName)},t.prototype.getEventRunner=function(t){var e=this.context_;if("cancel"===t.getEventType()){f.assert(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(e,t.error)}}var r=this.callbacks_[t.eventType];return function(){r.call(e,t.snapshot,t.prevName)}},t.prototype.matches=function(e){var n=this;if(e instanceof t){if(!this.callbacks_||!e.callbacks_)return!0;if(this.context_===e.context_){var r=Object.keys(e.callbacks_),o=Object.keys(this.callbacks_),c=r.length;if(c===o.length){if(1===c){var h=r[0],l=o[0];return!(l!==h||e.callbacks_[h]&&this.callbacks_[l]&&e.callbacks_[h]!==this.callbacks_[l])}return o.every((function(t){return e.callbacks_[t]===n.callbacks_[t]}))}}}return!1},t.prototype.hasAnyCallback=function(){return null!==this.callbacks_},t}(),fe=function(){function t(t,path,e,n){this.repo=t,this.path=path,this.queryParams_=e,this.orderByCalled_=n}return Object.defineProperty(t,"__referenceConstructor",{get:function(){return f.assert(re,"Reference.ts has not been loaded"),re},set:function(t){re=t},enumerable:!0,configurable:!0}),t.validateQueryEndpoints_=function(t){var e=null,n=null;if(t.hasStart()&&(e=t.getIndexStartValue()),t.hasEnd()&&(n=t.getIndexEndValue()),t.getIndex()===Ot){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",o="Query: When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string.";if(t.hasStart()){if(t.getIndexStartName()!=M)throw new Error(r);if("string"!=typeof e)throw new Error(o)}if(t.hasEnd()){if(t.getIndexEndName()!=F)throw new Error(r);if("string"!=typeof n)throw new Error(o)}}else if(t.getIndex()===Bt){if(null!=e&&!pt(e)||null!=n&&!pt(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), endAt(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(f.assert(t.getIndex()instanceof ae||t.getIndex()===oe,"unknown index type."),null!=e&&"object"==typeof e||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be an object.")},t.validateLimit_=function(t){if(t.hasStart()&&t.hasEnd()&&t.hasLimit()&&!t.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.")},t.prototype.validateNoPreviousOrderByCall_=function(t){if(!0===this.orderByCalled_)throw new Error(t+": You can't combine multiple orderBy calls.")},t.prototype.getQueryParams=function(){return this.queryParams_},t.prototype.getRef=function(){return f.validateArgCount("Query.ref",0,0,arguments.length),new t.__referenceConstructor(this.repo,this.path)},t.prototype.on=function(e,n,r,o){f.validateArgCount("Query.on",2,4,arguments.length),bt("Query.on",1,e,!1),f.validateCallback("Query.on",2,n,!1);var c=t.getCancelAndContextArgs_("Query.on",r,o);if("value"===e)this.onValueEvent(n,c.cancel,c.context);else{var h={};h[e]=n,this.onChildEvent(h,c.cancel,c.context)}return n},t.prototype.onValueEvent=function(t,e,n){var r=new he(t,e||null,n||null);this.repo.addEventCallbackForQuery(this,r)},t.prototype.onChildEvent=function(t,e,n){var r=new le(t,e,n);this.repo.addEventCallbackForQuery(this,r)},t.prototype.off=function(t,e,n){f.validateArgCount("Query.off",0,3,arguments.length),bt("Query.off",1,t,!0),f.validateCallback("Query.off",2,e,!0),f.validateContextObject("Query.off",3,n,!0);var r=null,o=null;if("value"===t){var c=e||null;r=new he(c,null,n||null)}else t&&(e&&((o={})[t]=e),r=new le(o,null,n||null));this.repo.removeEventCallbackForQuery(this,r)},t.prototype.once=function(e,n,r,o){var c=this;f.validateArgCount("Query.once",1,4,arguments.length),bt("Query.once",1,e,!1),f.validateCallback("Query.once",2,n,!0);var h=t.getCancelAndContextArgs_("Query.once",r,o),l=!0,d=new f.Deferred;d.promise.catch((function(){}));var y=function(t){l&&(l=!1,c.off(e,y),n&&n.bind(h.context)(t),d.resolve(t))};return this.on(e,y,(function(t){c.off(e,y),h.cancel&&h.cancel.bind(h.context)(t),d.reject(t)})),d.promise},t.prototype.limitToFirst=function(e){if(f.validateArgCount("Query.limitToFirst",1,1,arguments.length),"number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("Query.limitToFirst: First argument must be a positive integer.");if(this.queryParams_.hasLimit())throw new Error("Query.limitToFirst: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new t(this.repo,this.path,this.queryParams_.limitToFirst(e),this.orderByCalled_)},t.prototype.limitToLast=function(e){if(f.validateArgCount("Query.limitToLast",1,1,arguments.length),"number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("Query.limitToLast: First argument must be a positive integer.");if(this.queryParams_.hasLimit())throw new Error("Query.limitToLast: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new t(this.repo,this.path,this.queryParams_.limitToLast(e),this.orderByCalled_)},t.prototype.orderByChild=function(path){if(f.validateArgCount("Query.orderByChild",1,1,arguments.length),"$key"===path)throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===path)throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');if("$value"===path)throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.');wt("Query.orderByChild",1,path,!1),this.validateNoPreviousOrderByCall_("Query.orderByChild");var e=new J(path);if(e.isEmpty())throw new Error("Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.");var n=new ae(e),r=this.queryParams_.orderBy(n);return t.validateQueryEndpoints_(r),new t(this.repo,this.path,r,!0)},t.prototype.orderByKey=function(){f.validateArgCount("Query.orderByKey",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByKey");var e=this.queryParams_.orderBy(Ot);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.orderByPriority=function(){f.validateArgCount("Query.orderByPriority",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByPriority");var e=this.queryParams_.orderBy(Bt);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.orderByValue=function(){f.validateArgCount("Query.orderByValue",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByValue");var e=this.queryParams_.orderBy(oe);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.startAt=function(e,n){void 0===e&&(e=null),f.validateArgCount("Query.startAt",0,2,arguments.length),yt("Query.startAt",1,e,this.path,!0),_t("Query.startAt",2,n,!0);var r=this.queryParams_.startAt(e,n);if(t.validateLimit_(r),t.validateQueryEndpoints_(r),this.queryParams_.hasStart())throw new Error("Query.startAt: Starting point was already set (by another call to startAt or equalTo).");return void 0===e&&(e=null,n=null),new t(this.repo,this.path,r,this.orderByCalled_)},t.prototype.endAt=function(e,n){void 0===e&&(e=null),f.validateArgCount("Query.endAt",0,2,arguments.length),yt("Query.endAt",1,e,this.path,!0),_t("Query.endAt",2,n,!0);var r=this.queryParams_.endAt(e,n);if(t.validateLimit_(r),t.validateQueryEndpoints_(r),this.queryParams_.hasEnd())throw new Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new t(this.repo,this.path,r,this.orderByCalled_)},t.prototype.equalTo=function(t,e){if(f.validateArgCount("Query.equalTo",1,2,arguments.length),yt("Query.equalTo",1,t,this.path,!1),_t("Query.equalTo",2,e,!0),this.queryParams_.hasStart())throw new Error("Query.equalTo: Starting point was already set (by another call to startAt or equalTo).");if(this.queryParams_.hasEnd())throw new Error("Query.equalTo: Ending point was already set (by another call to endAt or equalTo).");return this.startAt(t,e).endAt(t,e)},t.prototype.toString=function(){return f.validateArgCount("Query.toString",0,0,arguments.length),this.repo.toString()+this.path.toUrlEncodedString()},t.prototype.toJSON=function(){return f.validateArgCount("Query.toJSON",0,1,arguments.length),this.toString()},t.prototype.queryObject=function(){return this.queryParams_.getQueryObject()},t.prototype.queryIdentifier=function(){var t=this.queryObject(),e=j(t);return"{}"===e?"default":e},t.prototype.isEqual=function(e){if(f.validateArgCount("Query.isEqual",1,1,arguments.length),!(e instanceof t)){var n="Query.isEqual failed: First argument must be an instance of firebase.database.Query.";throw new Error(n)}var r=this.repo===e.repo,o=this.path.equals(e.path),c=this.queryIdentifier()===e.queryIdentifier();return r&&o&&c},t.getCancelAndContextArgs_=function(t,e,n){var r={cancel:null,context:null};if(e&&n)r.cancel=e,f.validateCallback(t,3,r.cancel,!0),r.context=n,f.validateContextObject(t,4,r.context,!0);else if(e)if("object"==typeof e&&null!==e)r.context=e;else{if("function"!=typeof e)throw new Error(f.errorPrefix(t,3,!0)+" must either be a cancel callback or a context object.");r.cancel=e}return r},Object.defineProperty(t.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),t}(),pe=function(){function t(){this.value=null,this.children=new Map}return t.prototype.find=function(path){if(null!=this.value)return this.value.getChild(path);if(!path.isEmpty()&&this.children.size>0){var t=path.getFront();return path=path.popFront(),this.children.has(t)?this.children.get(t).find(path):null}return null},t.prototype.remember=function(path,data){if(path.isEmpty())this.value=data,this.children.clear();else if(null!==this.value)this.value=this.value.updateChild(path,data);else{var e=path.getFront();this.children.has(e)||this.children.set(e,new t);var n=this.children.get(e);path=path.popFront(),n.remember(path,data)}},t.prototype.forget=function(path){if(path.isEmpty())return this.value=null,this.children.clear(),!0;if(null!==this.value){if(this.value.isLeafNode())return!1;var t=this.value;this.value=null;var e=this;return t.forEachChild(Bt,(function(t,n){e.remember(new J(t),n)})),this.forget(path)}if(this.children.size>0){var n=path.getFront();if(path=path.popFront(),this.children.has(n))this.children.get(n).forget(path)&&this.children.delete(n);return 0===this.children.size}return!0},t.prototype.forEachTree=function(t,e){null!==this.value?e(t,this.value):this.forEachChild((function(n,r){var path=new J(t.toString()+"/"+n);r.forEachTree(path,e)}))},t.prototype.forEachChild=function(t){this.children.forEach((function(e,n){t(n,e)}))},t}(),de=function(t,e){return t&&"object"==typeof t?(f.assert(".sv"in t,"Unexpected leaf node or priority contents"),e[t[".sv"]]):t},ye=function(t,e){var n,r=t.getPriority().val(),o=de(r,e);if(t.isLeafNode()){var c=t,h=de(c.getValue(),e);return h!==c.getValue()||o!==c.getPriority().val()?new Ut(h,ne(o)):t}var l=t;return n=l,o!==l.getPriority().val()&&(n=n.updatePriority(new Ut(o))),l.forEachChild(Bt,(function(t,r){var o=ye(r,e);o!==r&&(n=n.updateImmediateChild(t,o))})),n};!function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(ie||(ie={}));var me,ge,ve=function(){function t(t,e,n,r){this.fromUser=t,this.fromServer=e,this.queryId=n,this.tagged=r,f.assert(!r||e,"Tagged queries must be from server.")}return t.User=new t(!0,!1,null,!1),t.Server=new t(!1,!0,null,!1),t.forServerTaggedQuery=function(e){return new t(!1,!0,e,!0)},t}(),be=function(){function t(path,t,e){this.path=path,this.affectedTree=t,this.revert=e,this.type=ie.ACK_USER_WRITE,this.source=ve.User}return t.prototype.operationForChild=function(e){if(this.path.isEmpty()){if(null!=this.affectedTree.value)return f.assert(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var n=this.affectedTree.subtree(new J(e));return new t(J.Empty,n,this.revert)}return f.assert(this.path.getFront()===e,"operationForChild called for unrelated child."),new t(this.path.popFront(),this.affectedTree,this.revert)},t}(),_e=function(){return me||(me=new Kt(V)),me},we=function(){function t(t,e){void 0===e&&(e=_e()),this.value=t,this.children=e}return t.fromObject=function(e){var n=t.Empty;return Q(e,(function(t,e){n=n.set(new J(t),e)})),n},t.prototype.isEmpty=function(){return null===this.value&&this.children.isEmpty()},t.prototype.findRootMostMatchingPathAndValue=function(t,e){if(null!=this.value&&e(this.value))return{path:J.Empty,value:this.value};if(t.isEmpty())return null;var n=t.getFront(),r=this.children.get(n);if(null!==r){var o=r.findRootMostMatchingPathAndValue(t.popFront(),e);return null!=o?{path:new J(n).child(o.path),value:o.value}:null}return null},t.prototype.findRootMostValueAndPath=function(t){return this.findRootMostMatchingPathAndValue(t,(function(){return!0}))},t.prototype.subtree=function(e){if(e.isEmpty())return this;var n=e.getFront(),r=this.children.get(n);return null!==r?r.subtree(e.popFront()):t.Empty},t.prototype.set=function(e,n){if(e.isEmpty())return new t(n,this.children);var r=e.getFront(),o=(this.children.get(r)||t.Empty).set(e.popFront(),n),c=this.children.insert(r,o);return new t(this.value,c)},t.prototype.remove=function(e){if(e.isEmpty())return this.children.isEmpty()?t.Empty:new t(null,this.children);var n=e.getFront(),r=this.children.get(n);if(r){var o=r.remove(e.popFront()),c=void 0;return c=o.isEmpty()?this.children.remove(n):this.children.insert(n,o),null===this.value&&c.isEmpty()?t.Empty:new t(this.value,c)}return this},t.prototype.get=function(t){if(t.isEmpty())return this.value;var e=t.getFront(),n=this.children.get(e);return n?n.get(t.popFront()):null},t.prototype.setTree=function(e,n){if(e.isEmpty())return n;var r=e.getFront(),o=(this.children.get(r)||t.Empty).setTree(e.popFront(),n),c=void 0;return c=o.isEmpty()?this.children.remove(r):this.children.insert(r,o),new t(this.value,c)},t.prototype.fold=function(t){return this.fold_(J.Empty,t)},t.prototype.fold_=function(t,e){var n={};return this.children.inorderTraversal((function(r,o){n[r]=o.fold_(t.child(r),e)})),e(t,this.value,n)},t.prototype.findOnPath=function(path,t){return this.findOnPath_(path,J.Empty,t)},t.prototype.findOnPath_=function(t,e,n){var r=!!this.value&&n(e,this.value);if(r)return r;if(t.isEmpty())return null;var o=t.getFront(),c=this.children.get(o);return c?c.findOnPath_(t.popFront(),e.child(o),n):null},t.prototype.foreachOnPath=function(path,t){return this.foreachOnPath_(path,J.Empty,t)},t.prototype.foreachOnPath_=function(e,n,r){if(e.isEmpty())return this;this.value&&r(n,this.value);var o=e.getFront(),c=this.children.get(o);return c?c.foreachOnPath_(e.popFront(),n.child(o),r):t.Empty},t.prototype.foreach=function(t){this.foreach_(J.Empty,t)},t.prototype.foreach_=function(t,e){this.children.inorderTraversal((function(n,r){r.foreach_(t.child(n),e)})),this.value&&e(t,this.value)},t.prototype.foreachChild=function(t){this.children.inorderTraversal((function(e,n){n.value&&t(e,n.value)}))},t.Empty=new t(null),t}(),Ee=function(){function t(source,path){this.source=source,this.path=path,this.type=ie.LISTEN_COMPLETE}return t.prototype.operationForChild=function(e){return this.path.isEmpty()?new t(this.source,J.Empty):new t(this.source,this.path.popFront())},t}(),Te=function(){function t(source,path,t){this.source=source,this.path=path,this.snap=t,this.type=ie.OVERWRITE}return t.prototype.operationForChild=function(e){return this.path.isEmpty()?new t(this.source,J.Empty,this.snap.getImmediateChild(e)):new t(this.source,this.path.popFront(),this.snap)},t}(),Se=function(){function t(source,path,t){this.source=source,this.path=path,this.children=t,this.type=ie.MERGE}return t.prototype.operationForChild=function(e){if(this.path.isEmpty()){var n=this.children.subtree(new J(e));return n.isEmpty()?null:n.value?new Te(this.source,J.Empty,n.value):new t(this.source,J.Empty,n)}return f.assert(this.path.getFront()===e,"Can't get a merge for a child not on the path of the operation"),new t(this.source,this.path.popFront(),this.children)},t.prototype.toString=function(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"},t}(),Ce=function(){function t(t,e,n){this.node_=t,this.fullyInitialized_=e,this.filtered_=n}return t.prototype.isFullyInitialized=function(){return this.fullyInitialized_},t.prototype.isFiltered=function(){return this.filtered_},t.prototype.isCompleteForPath=function(path){if(path.isEmpty())return this.isFullyInitialized()&&!this.filtered_;var t=path.getFront();return this.isCompleteForChild(t)},t.prototype.isCompleteForChild=function(t){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(t)},t.prototype.getNode=function(){return this.node_},t}(),Ie=function(){function t(t,e){this.eventCache_=t,this.serverCache_=e}return t.prototype.updateEventSnap=function(e,n,r){return new t(new Ce(e,n,r),this.serverCache_)},t.prototype.updateServerSnap=function(e,n,r){return new t(this.eventCache_,new Ce(e,n,r))},t.prototype.getEventCache=function(){return this.eventCache_},t.prototype.getCompleteEventSnap=function(){return this.eventCache_.isFullyInitialized()?this.eventCache_.getNode():null},t.prototype.getServerCache=function(){return this.serverCache_},t.prototype.getCompleteServerSnap=function(){return this.serverCache_.isFullyInitialized()?this.serverCache_.getNode():null},t.Empty=new t(new Ce(Zt.EMPTY_NODE,!1,!1),new Ce(Zt.EMPTY_NODE,!1,!1)),t}(),Ne=function(){function t(t,e,n,r,o){this.type=t,this.snapshotNode=e,this.childName=n,this.oldSnap=r,this.prevName=o}return t.valueChange=function(e){return new t(t.VALUE,e)},t.childAddedChange=function(e,n){return new t(t.CHILD_ADDED,n,e)},t.childRemovedChange=function(e,n){return new t(t.CHILD_REMOVED,n,e)},t.childChangedChange=function(e,n,r){return new t(t.CHILD_CHANGED,n,e,r)},t.childMovedChange=function(e,n){return new t(t.CHILD_MOVED,n,e)},t.CHILD_ADDED="child_added",t.CHILD_REMOVED="child_removed",t.CHILD_CHANGED="child_changed",t.CHILD_MOVED="child_moved",t.VALUE="value",t}(),Ae=function(){function t(t){this.index_=t}return t.prototype.updateChild=function(t,e,n,r,source,o){f.assert(t.isIndexed(this.index_),"A node must be indexed if only a child is updated");var c=t.getImmediateChild(e);return c.getChild(r).equals(n.getChild(r))&&c.isEmpty()==n.isEmpty()?t:(null!=o&&(n.isEmpty()?t.hasChild(e)?o.trackChildChange(Ne.childRemovedChange(e,c)):f.assert(t.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):c.isEmpty()?o.trackChildChange(Ne.childAddedChange(e,n)):o.trackChildChange(Ne.childChangedChange(e,n,c))),t.isLeafNode()&&n.isEmpty()?t:t.updateImmediateChild(e,n).withIndex(this.index_))},t.prototype.updateFullNode=function(t,e,n){return null!=n&&(t.isLeafNode()||t.forEachChild(Bt,(function(t,r){e.hasChild(t)||n.trackChildChange(Ne.childRemovedChange(t,r))})),e.isLeafNode()||e.forEachChild(Bt,(function(e,r){if(t.hasChild(e)){var o=t.getImmediateChild(e);o.equals(r)||n.trackChildChange(Ne.childChangedChange(e,r,o))}else n.trackChildChange(Ne.childAddedChange(e,r))}))),e.withIndex(this.index_)},t.prototype.updatePriority=function(t,e){return t.isEmpty()?Zt.EMPTY_NODE:t.updatePriority(e)},t.prototype.filtersNodes=function(){return!1},t.prototype.getIndexedFilter=function(){return this},t.prototype.getIndex=function(){return this.index_},t}(),De=function(){function t(){this.changeMap=new Map}return t.prototype.trackChildChange=function(t){var e=t.type,n=t.childName;f.assert(e==Ne.CHILD_ADDED||e==Ne.CHILD_CHANGED||e==Ne.CHILD_REMOVED,"Only child changes supported for tracking"),f.assert(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var o=r.type;if(e==Ne.CHILD_ADDED&&o==Ne.CHILD_REMOVED)this.changeMap.set(n,Ne.childChangedChange(n,t.snapshotNode,r.snapshotNode));else if(e==Ne.CHILD_REMOVED&&o==Ne.CHILD_ADDED)this.changeMap.delete(n);else if(e==Ne.CHILD_REMOVED&&o==Ne.CHILD_CHANGED)this.changeMap.set(n,Ne.childRemovedChange(n,r.oldSnap));else if(e==Ne.CHILD_CHANGED&&o==Ne.CHILD_ADDED)this.changeMap.set(n,Ne.childAddedChange(n,t.snapshotNode));else{if(e!=Ne.CHILD_CHANGED||o!=Ne.CHILD_CHANGED)throw f.assertionError("Illegal combination of changes: "+t+" occurred after "+r);this.changeMap.set(n,Ne.childChangedChange(n,t.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,t)},t.prototype.getChanges=function(){return Array.from(this.changeMap.values())},t}(),ke=new(function(){function t(){}return t.prototype.getCompleteChild=function(t){return null},t.prototype.getChildAfterChild=function(t,e,n){return null},t}()),Re=function(){function t(t,e,n){void 0===n&&(n=null),this.writes_=t,this.viewCache_=e,this.optCompleteServerCache_=n}return t.prototype.getCompleteChild=function(t){var e=this.viewCache_.getEventCache();if(e.isCompleteForChild(t))return e.getNode().getImmediateChild(t);var n=null!=this.optCompleteServerCache_?new Ce(this.optCompleteServerCache_,!0,!1):this.viewCache_.getServerCache();return this.writes_.calcCompleteChild(t,n)},t.prototype.getChildAfterChild=function(t,e,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:this.viewCache_.getCompleteServerSnap(),o=this.writes_.calcIndexedSlice(r,e,1,n,t);return 0===o.length?null:o[0]},t}(),Oe=function(t,e){this.viewCache=t,this.changes=e},Pe=function(){function t(t){this.filter_=t}return t.prototype.assertIndexed=function(t){f.assert(t.getEventCache().getNode().isIndexed(this.filter_.getIndex()),"Event snap not indexed"),f.assert(t.getServerCache().getNode().isIndexed(this.filter_.getIndex()),"Server snap not indexed")},t.prototype.applyOperation=function(e,n,r,o){var c,h,l=new De;if(n.type===ie.OVERWRITE){var d=n;d.source.fromUser?c=this.applyUserOverwrite_(e,d.path,d.snap,r,o,l):(f.assert(d.source.fromServer,"Unknown source."),h=d.source.tagged||e.getServerCache().isFiltered()&&!d.path.isEmpty(),c=this.applyServerOverwrite_(e,d.path,d.snap,r,o,h,l))}else if(n.type===ie.MERGE){var y=n;y.source.fromUser?c=this.applyUserMerge_(e,y.path,y.children,r,o,l):(f.assert(y.source.fromServer,"Unknown source."),h=y.source.tagged||e.getServerCache().isFiltered(),c=this.applyServerMerge_(e,y.path,y.children,r,o,h,l))}else if(n.type===ie.ACK_USER_WRITE){var m=n;c=m.revert?this.revertUserWrite_(e,m.path,r,o,l):this.ackUserWrite_(e,m.path,m.affectedTree,r,o,l)}else{if(n.type!==ie.LISTEN_COMPLETE)throw f.assertionError("Unknown operation type: "+n.type);c=this.listenComplete_(e,n.path,r,l)}var v=l.getChanges();return t.maybeAddValueEvent_(e,c,v),new Oe(c,v)},t.maybeAddValueEvent_=function(t,e,n){var r=e.getEventCache();if(r.isFullyInitialized()){var o=r.getNode().isLeafNode()||r.getNode().isEmpty(),c=t.getCompleteEventSnap();(n.length>0||!t.getEventCache().isFullyInitialized()||o&&!r.getNode().equals(c)||!r.getNode().getPriority().equals(c.getPriority()))&&n.push(Ne.valueChange(e.getCompleteEventSnap()))}},t.prototype.generateEventCacheAfterServerEvent_=function(t,e,n,source,r){var o=t.getEventCache();if(null!=n.shadowingWrite(e))return t;var c=void 0,h=void 0;if(e.isEmpty())if(f.assert(t.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),t.getServerCache().isFiltered()){var l=t.getCompleteServerSnap(),d=l instanceof Zt?l:Zt.EMPTY_NODE,y=n.calcCompleteEventChildren(d);c=this.filter_.updateFullNode(t.getEventCache().getNode(),y,r)}else{var m=n.calcCompleteEventCache(t.getCompleteServerSnap());c=this.filter_.updateFullNode(t.getEventCache().getNode(),m,r)}else{var v=e.getFront();if(".priority"==v){f.assert(1==e.getLength(),"Can't have a priority with additional path components");var _=o.getNode();h=t.getServerCache().getNode();var w=n.calcEventCacheAfterServerOverwrite(e,_,h);c=null!=w?this.filter_.updatePriority(_,w):o.getNode()}else{var E=e.popFront(),T=void 0;if(o.isCompleteForChild(v)){h=t.getServerCache().getNode();var S=n.calcEventCacheAfterServerOverwrite(e,o.getNode(),h);T=null!=S?o.getNode().getImmediateChild(v).updateChild(E,S):o.getNode().getImmediateChild(v)}else T=n.calcCompleteChild(v,t.getServerCache());c=null!=T?this.filter_.updateChild(o.getNode(),v,T,E,source,r):o.getNode()}}return t.updateEventSnap(c,o.isFullyInitialized()||e.isEmpty(),this.filter_.filtersNodes())},t.prototype.applyServerOverwrite_=function(t,e,n,r,o,c,h){var l,f=t.getServerCache(),d=c?this.filter_:this.filter_.getIndexedFilter();if(e.isEmpty())l=d.updateFullNode(f.getNode(),n,null);else if(d.filtersNodes()&&!f.isFiltered()){var y=f.getNode().updateChild(e,n);l=d.updateFullNode(f.getNode(),y,null)}else{var m=e.getFront();if(!f.isCompleteForPath(e)&&e.getLength()>1)return t;var v=e.popFront(),_=f.getNode().getImmediateChild(m).updateChild(v,n);l=".priority"==m?d.updatePriority(f.getNode(),_):d.updateChild(f.getNode(),m,_,v,ke,null)}var w=t.updateServerSnap(l,f.isFullyInitialized()||e.isEmpty(),d.filtersNodes()),source=new Re(r,w,o);return this.generateEventCacheAfterServerEvent_(w,e,r,source,h)},t.prototype.applyUserOverwrite_=function(t,e,n,r,o,c){var h,l,f=t.getEventCache(),source=new Re(r,t,o);if(e.isEmpty())l=this.filter_.updateFullNode(t.getEventCache().getNode(),n,c),h=t.updateEventSnap(l,!0,this.filter_.filtersNodes());else{var d=e.getFront();if(".priority"===d)l=this.filter_.updatePriority(t.getEventCache().getNode(),n),h=t.updateEventSnap(l,f.isFullyInitialized(),f.isFiltered());else{var y=e.popFront(),m=f.getNode().getImmediateChild(d),v=void 0;if(y.isEmpty())v=n;else{var _=source.getCompleteChild(d);v=null!=_?".priority"===y.getBack()&&_.getChild(y.parent()).isEmpty()?_:_.updateChild(y,n):Zt.EMPTY_NODE}if(m.equals(v))h=t;else{var w=this.filter_.updateChild(f.getNode(),d,v,y,source,c);h=t.updateEventSnap(w,f.isFullyInitialized(),this.filter_.filtersNodes())}}}return h},t.cacheHasChild_=function(t,e){return t.getEventCache().isCompleteForChild(e)},t.prototype.applyUserMerge_=function(e,path,n,r,o,c){var h=this,l=e;return n.foreach((function(n,f){var d=path.child(n);t.cacheHasChild_(e,d.getFront())&&(l=h.applyUserOverwrite_(l,d,f,r,o,c))})),n.foreach((function(n,f){var d=path.child(n);t.cacheHasChild_(e,d.getFront())||(l=h.applyUserOverwrite_(l,d,f,r,o,c))})),l},t.prototype.applyMerge_=function(t,e){return e.foreach((function(e,n){t=t.updateChild(e,n)})),t},t.prototype.applyServerMerge_=function(t,path,e,n,r,o,c){var h=this;if(t.getServerCache().getNode().isEmpty()&&!t.getServerCache().isFullyInitialized())return t;var l,f=t;l=path.isEmpty()?e:we.Empty.setTree(path,e);var d=t.getServerCache().getNode();return l.children.inorderTraversal((function(e,l){if(d.hasChild(e)){var y=t.getServerCache().getNode().getImmediateChild(e),m=h.applyMerge_(y,l);f=h.applyServerOverwrite_(f,new J(e),m,n,r,o,c)}})),l.children.inorderTraversal((function(e,l){var y=!t.getServerCache().isCompleteForChild(e)&&null==l.value;if(!d.hasChild(e)&&!y){var m=t.getServerCache().getNode().getImmediateChild(e),v=h.applyMerge_(m,l);f=h.applyServerOverwrite_(f,new J(e),v,n,r,o,c)}})),f},t.prototype.ackUserWrite_=function(t,e,n,r,o,c){if(null!=r.shadowingWrite(e))return t;var h=t.getServerCache().isFiltered(),l=t.getServerCache();if(null!=n.value){if(e.isEmpty()&&l.isFullyInitialized()||l.isCompleteForPath(e))return this.applyServerOverwrite_(t,e,l.getNode().getChild(e),r,o,h,c);if(e.isEmpty()){var f=we.Empty;return l.getNode().forEachChild(Ot,(function(t,e){f=f.set(new J(t),e)})),this.applyServerMerge_(t,e,f,r,o,h,c)}return t}var d=we.Empty;return n.foreach((function(t,n){var r=e.child(t);l.isCompleteForPath(r)&&(d=d.set(t,l.getNode().getChild(r)))})),this.applyServerMerge_(t,e,d,r,o,h,c)},t.prototype.listenComplete_=function(t,path,e,n){var r=t.getServerCache(),o=t.updateServerSnap(r.getNode(),r.isFullyInitialized()||path.isEmpty(),r.isFiltered());return this.generateEventCacheAfterServerEvent_(o,path,e,ke,n)},t.prototype.revertUserWrite_=function(t,path,e,n,r){var o;if(null!=e.shadowingWrite(path))return t;var source=new Re(e,t,n),c=t.getEventCache().getNode(),h=void 0;if(path.isEmpty()||".priority"===path.getFront()){var l=void 0;if(t.getServerCache().isFullyInitialized())l=e.calcCompleteEventCache(t.getCompleteServerSnap());else{var d=t.getServerCache().getNode();f.assert(d instanceof Zt,"serverChildren would be complete if leaf node"),l=e.calcCompleteEventChildren(d)}l=l,h=this.filter_.updateFullNode(c,l,r)}else{var y=path.getFront(),m=e.calcCompleteChild(y,t.getServerCache());null==m&&t.getServerCache().isCompleteForChild(y)&&(m=c.getImmediateChild(y)),(h=null!=m?this.filter_.updateChild(c,y,m,path.popFront(),source,r):t.getEventCache().getNode().hasChild(y)?this.filter_.updateChild(c,y,Zt.EMPTY_NODE,path.popFront(),source,r):c).isEmpty()&&t.getServerCache().isFullyInitialized()&&(o=e.calcCompleteEventCache(t.getCompleteServerSnap())).isLeafNode()&&(h=this.filter_.updateFullNode(h,o,r))}return o=t.getServerCache().isFullyInitialized()||null!=e.shadowingWrite(J.Empty),t.updateEventSnap(h,o,this.filter_.filtersNodes())},t}(),xe=function(){function t(t){this.query_=t,this.index_=this.query_.getQueryParams().getIndex()}return t.prototype.generateEventsForChanges=function(t,e,n){var r=this,o=[],c=[];return t.forEach((function(t){t.type===Ne.CHILD_CHANGED&&r.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&c.push(Ne.childMovedChange(t.childName,t.snapshotNode))})),this.generateEventsForType_(o,Ne.CHILD_REMOVED,t,n,e),this.generateEventsForType_(o,Ne.CHILD_ADDED,t,n,e),this.generateEventsForType_(o,Ne.CHILD_MOVED,c,n,e),this.generateEventsForType_(o,Ne.CHILD_CHANGED,t,n,e),this.generateEventsForType_(o,Ne.VALUE,t,n,e),o},t.prototype.generateEventsForType_=function(t,e,n,r,o){var c=this,h=n.filter((function(t){return t.type===e}));h.sort(this.compareChanges_.bind(this)),h.forEach((function(e){var n=c.materializeSingleChange_(e,o);r.forEach((function(r){r.respondsTo(e.type)&&t.push(r.createEvent(n,c.query_))}))}))},t.prototype.materializeSingleChange_=function(t,e){return"value"===t.type||"child_removed"===t.type?t:(t.prevName=e.getPredecessorChildName(t.childName,t.snapshotNode,this.index_),t)},t.prototype.compareChanges_=function(a,b){if(null==a.childName||null==b.childName)throw f.assertionError("Should only compare child_ events.");var t=new Dt(a.childName,a.snapshotNode),e=new Dt(b.childName,b.snapshotNode);return this.index_.compare(t,e)},t}(),Le=function(){function t(t,e){this.query_=t,this.eventRegistrations_=[];var n=this.query_.getQueryParams(),r=new Ae(n.getIndex()),filter=n.getNodeFilter();this.processor_=new Pe(filter);var o=e.getServerCache(),c=e.getEventCache(),h=r.updateFullNode(Zt.EMPTY_NODE,o.getNode(),null),l=filter.updateFullNode(Zt.EMPTY_NODE,c.getNode(),null),f=new Ce(h,o.isFullyInitialized(),r.filtersNodes()),d=new Ce(l,c.isFullyInitialized(),filter.filtersNodes());this.viewCache_=new Ie(d,f),this.eventGenerator_=new xe(this.query_)}return t.prototype.getQuery=function(){return this.query_},t.prototype.getServerCache=function(){return this.viewCache_.getServerCache().getNode()},t.prototype.getCompleteServerCache=function(path){var t=this.viewCache_.getCompleteServerSnap();return t&&(this.query_.getQueryParams().loadsAllData()||!path.isEmpty()&&!t.getImmediateChild(path.getFront()).isEmpty())?t.getChild(path):null},t.prototype.isEmpty=function(){return 0===this.eventRegistrations_.length},t.prototype.addEventRegistration=function(t){this.eventRegistrations_.push(t)},t.prototype.removeEventRegistration=function(t,e){var n=[];if(e){f.assert(null==t,"A cancel should cancel all event registrations.");var r=this.query_.path;this.eventRegistrations_.forEach((function(t){e=e;var o=t.createCancelEvent(e,r);o&&n.push(o)}))}if(t){for(var o=[],i=0;ithis.lastWriteId_,"Stacking an older write on top of newer ones"),void 0===n&&(n=!0),this.allWrites_.push({path:path,snap:t,writeId:e,visible:n}),n&&(this.visibleWrites_=this.visibleWrites_.addWrite(path,t)),this.lastWriteId_=e},t.prototype.addMerge=function(path,t,e){f.assert(e>this.lastWriteId_,"Stacking an older merge on top of newer ones"),this.allWrites_.push({path:path,children:t,writeId:e,visible:!0}),this.visibleWrites_=this.visibleWrites_.addWrites(path,t),this.lastWriteId_=e},t.prototype.getWrite=function(t){for(var i=0;i=0,"removeWrite called with nonexistent writeId.");var r=this.allWrites_[n];this.allWrites_.splice(n,1);for(var o=r.visible,c=!1,i=this.allWrites_.length-1;o&&i>=0;){var h=this.allWrites_[i];h.visible&&(i>=n&&this.recordContainsPath_(h,r.path)?o=!1:r.path.contains(h.path)&&(c=!0)),i--}if(o){if(c)return this.resetTree_(),!0;r.snap?this.visibleWrites_=this.visibleWrites_.removeWrite(r.path):Q(r.children,(function(t){e.visibleWrites_=e.visibleWrites_.removeWrite(r.path.child(t))}));return!0}return!1},t.prototype.getCompleteWriteData=function(path){return this.visibleWrites_.getCompleteNode(path)},t.prototype.calcCompleteEventCache=function(e,n,r,o){if(r||o){var c=this.visibleWrites_.childCompoundWrite(e);if(!o&&c.isEmpty())return n;if(o||null!=n||c.hasCompleteWrite(J.Empty)){var h=t.layerTree_(this.allWrites_,(function(t){return(t.visible||o)&&(!r||!~r.indexOf(t.writeId))&&(t.path.contains(e)||e.contains(t.path))}),e);d=n||Zt.EMPTY_NODE;return h.apply(d)}return null}var l=this.visibleWrites_.getCompleteNode(e);if(null!=l)return l;var f=this.visibleWrites_.childCompoundWrite(e);if(f.isEmpty())return n;if(null!=n||f.hasCompleteWrite(J.Empty)){var d=n||Zt.EMPTY_NODE;return f.apply(d)}return null},t.prototype.calcCompleteEventChildren=function(t,e){var n=Zt.EMPTY_NODE,r=this.visibleWrites_.getCompleteNode(t);if(r)return r.isLeafNode()||r.forEachChild(Bt,(function(t,e){n=n.updateImmediateChild(t,e)})),n;if(e){var o=this.visibleWrites_.childCompoundWrite(t);return e.forEachChild(Bt,(function(t,e){var r=o.childCompoundWrite(new J(t)).apply(e);n=n.updateImmediateChild(t,r)})),o.getCompleteChildren().forEach((function(t){n=n.updateImmediateChild(t.name,t.node)})),n}return this.visibleWrites_.childCompoundWrite(t).getCompleteChildren().forEach((function(t){n=n.updateImmediateChild(t.name,t.node)})),n},t.prototype.calcEventCacheAfterServerOverwrite=function(t,e,n,r){f.assert(n||r,"Either existingEventSnap or existingServerSnap must exist");var path=t.child(e);if(this.visibleWrites_.hasCompleteWrite(path))return null;var o=this.visibleWrites_.childCompoundWrite(path);return o.isEmpty()?r.getChild(e):o.apply(r.getChild(e))},t.prototype.calcCompleteChild=function(t,e,n){var path=t.child(e),r=this.visibleWrites_.getCompleteNode(path);return null!=r?r:n.isCompleteForChild(e)?this.visibleWrites_.childCompoundWrite(path).apply(n.getNode().getImmediateChild(e)):null},t.prototype.shadowingWrite=function(path){return this.visibleWrites_.getCompleteNode(path)},t.prototype.calcIndexedSlice=function(t,e,n,r,o,c){var h,l=this.visibleWrites_.childCompoundWrite(t),f=l.getCompleteNode(J.Empty);if(null!=f)h=f;else{if(null==e)return[];h=l.apply(e)}if((h=h.withIndex(c)).isEmpty()||h.isLeafNode())return[];for(var d=[],y=c.getCompare(),m=o?h.getReverseIteratorFrom(n,c):h.getIteratorFrom(n,c),v=m.getNext();v&&d.length0?this.lastWriteId_=this.allWrites_[this.allWrites_.length-1].writeId:this.lastWriteId_=-1},t.DefaultFilter_=function(t){return t.visible},t.layerTree_=function(t,filter,e){for(var n=Fe.Empty,i=0;i0&&!r)if(d){this.listenProvider_.stopListening(t.queryForListening_(e),null)}else f.forEach((function(e){var n=o.queryToTagMap.get(t.makeQueryKey_(e));o.listenProvider_.stopListening(t.queryForListening_(e),n)}));this.removeTags_(f)}return h},t.prototype.calcCompleteEventCache=function(path,t){var e=this.pendingWriteTree_,n=this.syncPointTree_.findOnPath(path,(function(t,e){var n=J.relativePath(t,path),r=e.getCompleteServerCache(n);if(r)return r}));return e.calcCompleteEventCache(path,n,t,!0)},t.prototype.collectDistinctViewsForSubTree_=function(t){return t.fold((function(t,e,n){if(e&&e.hasCompleteView())return[e.getCompleteView()];var r=[];return e&&(r=e.getQueryViews()),Q(n,(function(t,e){r=r.concat(e)})),r}))},t.prototype.removeTags_=function(e){for(var n=0;n0&&f.contains(t.statsToReport_,e)&&(n[e]=o,r=!0)})),r&&this.server_.reportStats(n),X(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))},t}(),Je=function(){function t(){this.eventLists_=[],this.recursionDepth_=0}return t.prototype.queueEvents=function(t){for(var e=null,i=0;i0,"Requires a non-empty array")}return t.prototype.trigger=function(t){for(var e=[],n=1;ndocument.domain="'+document.domain+'";<\/script>';var c=""+script+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(c),this.myIFrame.doc.close()}catch(t){k("frame writing exception"),t.stack&&k(t.stack),k(t)}}}return t.createIFrame_=function(){var iframe=document.createElement("iframe");if(iframe.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(iframe);try{iframe.contentWindow.document||k("No IE domain setting required")}catch(e){var t=document.domain;iframe.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}return iframe.contentDocument?iframe.doc=iframe.contentDocument:iframe.contentWindow?iframe.doc=iframe.contentWindow.document:iframe.document&&(iframe.doc=iframe.document),iframe},t.prototype.close=function(){var t=this;this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout((function(){null!==t.myIFrame&&(document.body.removeChild(t.myIFrame),t.myIFrame=null)}),Math.floor(0)));var e=this.onDisconnect;e&&(this.onDisconnect=null,e())},t.prototype.startLongPoll=function(t,e){for(this.myID=t,this.myPW=e,this.alive=!0;this.newRequest_(););},t.prototype.newRequest_=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var t={};t.id=this.myID,t.pw=this.myPW,t.ser=this.currentSerial;for(var e=this.urlFn(t),n="",i=0;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;var r=this.pendingSegs.shift();n=n+"&seg"+i+"="+r.seg+"&ts"+i+"="+r.ts+"&d"+i+"="+r.d,i++}return e+=n,this.addLongPollTag_(e,this.currentSerial),!0}return!1},t.prototype.enqueueSegment=function(t,e,data){this.pendingSegs.push({seg:t,ts:e,d:data}),this.alive&&this.newRequest_()},t.prototype.addLongPollTag_=function(t,e){var n=this;this.outstandingRequests.add(e);var r=function(){n.outstandingRequests.delete(e),n.newRequest_()},o=setTimeout(r,Math.floor(25e3));this.addTag(t,(function(){clearTimeout(o),r()}))},t.prototype.addTag=function(t,e){var n=this;f.isNodeSdk()?this.doNodeLongPoll(t,e):setTimeout((function(){try{if(!n.sendNewPolls)return;var r=n.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=t,r.onload=r.onreadystatechange=function(){var t=r.readyState;t&&"loaded"!==t&&"complete"!==t||(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),e())},r.onerror=function(){k("Long-poll script failed to load: "+t),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(r)}catch(t){}}),Math.floor(1))},t}(),un="";var cn=null;"undefined"!=typeof MozWebSocket?cn=MozWebSocket:"undefined"!=typeof WebSocket&&(cn=WebSocket);var hn=function(){function t(e,n,r,o){this.connId=e,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=R(this.connId),this.stats_=He.getCollection(n),this.connURL=t.connectionURL_(n,r,o)}return t.connectionURL_=function(t,e,n){var r={v:"5"};return!f.isNodeSdk()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf("firebaseio.com")&&(r.r="f"),e&&(r.s=e),n&&(r.ls=n),t.connectionURL("websocket",r)},t.prototype.open=function(t,e){var n=this;this.onDisconnect=e,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,_.set("previous_websocket_failure",!0);try{if(f.isNodeSdk()){var o=f.CONSTANTS.NODE_ADMIN?"AdminNode":"Node",c={headers:{"User-Agent":"Firebase/5/"+un+"/"+r.platform+"/"+o}},h=r.env,l=0==this.connURL.indexOf("wss://")?h.HTTPS_PROXY||h.https_proxy:h.HTTP_PROXY||h.http_proxy;l&&(c.proxy={origin:l}),this.mySock=new cn(this.connURL,[],c)}else this.mySock=new cn(this.connURL)}catch(t){this.log_("Error instantiating WebSocket.");var d=t.message||t.data;return d&&this.log_(d),void this.onClosed_()}this.mySock.onopen=function(){n.log_("Websocket connected."),n.everConnected_=!0},this.mySock.onclose=function(){n.log_("Websocket connection was disconnected."),n.mySock=null,n.onClosed_()},this.mySock.onmessage=function(t){n.handleIncomingFrame(t)},this.mySock.onerror=function(t){n.log_("WebSocket error. Closing connection.");var e=t.message||t.data;e&&n.log_(e),n.onClosed_()}},t.prototype.start=function(){},t.forceDisallow=function(){t.forceDisallow_=!0},t.isAvailable=function(){var e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var n=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==cn&&!t.forceDisallow_},t.previouslyFailed=function(){return _.isInMemoryStorage||!0===_.get("previous_websocket_failure")},t.prototype.markConnectionHealthy=function(){_.remove("previous_websocket_failure")},t.prototype.appendFrame_=function(data){if(this.frames.push(data),this.frames.length==this.totalFrames){var t=this.frames.join("");this.frames=null;var e=f.jsonEval(t);this.onMessage(e)}},t.prototype.handleNewFrameCount_=function(t){this.totalFrames=t,this.frames=[]},t.prototype.extractFrameCount_=function(data){if(f.assert(null===this.frames,"We already have a frame buffer"),data.length<=6){var t=Number(data);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),data},t.prototype.handleIncomingFrame=function(t){if(null!==this.mySock){var data=t.data;if(this.bytesReceived+=data.length,this.stats_.incrementCounter("bytes_received",data.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(data);else{var e=this.extractFrameCount_(data);null!==e&&this.appendFrame_(e)}}},t.prototype.send=function(data){this.resetKeepAlive();var t=f.stringify(data);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var e=W(t,16384);e.length>1&&this.sendString_(String(e.length));for(var i=0;i0)return this.transports_[0];throw new Error("No transports available")},t.prototype.upgradeTransport=function(){return this.transports_.length>1?this.transports_[1]:null},t}(),fn=function(){function t(t,e,n,r,o,c,h){this.id=t,this.repoInfo_=e,this.onMessage_=n,this.onReady_=r,this.onDisconnect_=o,this.onKill_=c,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=R("c:"+this.id+":"),this.transportManager_=new ln(e),this.log_("Connection created"),this.start_()}return t.prototype.start_=function(){var t=this,e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,void 0,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((function(){t.conn_&&t.conn_.open(n,r)}),Math.floor(0));var o=e.healthyTimeout||0;o>0&&(this.healthyTimeout_=X((function(){t.healthyTimeout_=null,t.isHealthy_||(t.conn_&&t.conn_.bytesReceived>102400?(t.log_("Connection exceeded healthy timeout but has received "+t.conn_.bytesReceived+" bytes. Marking connection healthy."),t.isHealthy_=!0,t.conn_.markConnectionHealthy()):t.conn_&&t.conn_.bytesSent>10240?t.log_("Connection exceeded healthy timeout but has sent "+t.conn_.bytesSent+" bytes. Leaving connection alive."):(t.log_("Closing unhealthy connection after timeout."),t.close()))}),Math.floor(o)))},t.prototype.nextTransportId_=function(){return"c:"+this.id+":"+this.connectionCount++},t.prototype.disconnReceiver_=function(t){var e=this;return function(n){t===e.conn_?e.onConnectionLost_(n):t===e.secondaryConn_?(e.log_("Secondary connection lost."),e.onSecondaryConnectionLost_()):e.log_("closing an old connection")}},t.prototype.connReceiver_=function(t){var e=this;return function(n){2!=e.state_&&(t===e.rx_?e.onPrimaryMessageReceived_(n):t===e.secondaryConn_?e.onSecondaryMessageReceived_(n):e.log_("message on old connection"))}},t.prototype.sendRequest=function(t){var e={t:"d",d:t};this.sendData_(e)},t.prototype.tryCleanupConnection=function(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)},t.prototype.onSecondaryControl_=function(t){if("t"in t){var e=t.t;"a"===e?this.upgradeIfSecondaryHealthy_():"r"===e?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===e&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}},t.prototype.onSecondaryMessageReceived_=function(t){var e=B("t",t),data=B("d",t);if("c"==e)this.onSecondaryControl_(data);else{if("d"!=e)throw new Error("Unknown protocol layer: "+e);this.pendingDataMessages.push(data)}},t.prototype.upgradeIfSecondaryHealthy_=function(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))},t.prototype.proceedWithUpgrade_=function(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()},t.prototype.onPrimaryMessageReceived_=function(t){var e=B("t",t),data=B("d",t);"c"==e?this.onControl_(data):"d"==e&&this.onDataMessage_(data)},t.prototype.onDataMessage_=function(t){this.onPrimaryResponse_(),this.onMessage_(t)},t.prototype.onPrimaryResponse_=function(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))},t.prototype.onControl_=function(t){var e=B("t",t);if("d"in t){var n=t.d;if("h"===e)this.onHandshake_(n);else if("n"===e){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(var i=0;i3e4&&(this.reconnectDelay_=dn),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();var t=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-t);e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)},e.prototype.establishConnection_=function(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var t=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),o=this.id+":"+e.nextConnectionId_++,c=this,h=this.lastSessionId,l=!1,d=null,y=function(){d?d.close():(l=!0,r())};this.realtime_={close:y,sendRequest:function(t){f.assert(d,"sendRequest call when we're not connected not allowed."),d.sendRequest(t)}};var m=this.forceTokenRefresh_;this.forceTokenRefresh_=!1,this.authTokenProvider_.getToken(m).then((function(e){l?k("getToken() completed but was canceled"):(k("getToken() completed. Creating connection."),c.authToken_=e&&e.accessToken,d=new fn(o,c.repoInfo_,t,n,r,(function(t){x(t+" ("+c.repoInfo_.toString()+")"),c.interrupt("server_kill")}),h))})).then(null,(function(t){c.log_("Failed to get token: "+t),l||(f.CONSTANTS.NODE_ADMIN&&x(t),y())}))}},e.prototype.interrupt=function(t){k("Interrupting connection for reason: "+t),this.interruptReasons_[t]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())},e.prototype.resume=function(t){k("Resuming connection for reason: "+t),delete this.interruptReasons_[t],f.isEmpty(this.interruptReasons_)&&(this.reconnectDelay_=dn,this.realtime_||this.scheduleConnect_(0))},e.prototype.handleTimestamp_=function(t){var e=t-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:e})},e.prototype.cancelSentTransactions_=function(){for(var i=0;i=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))},e.prototype.onSecurityDebugPacket_=function(body){this.securityDebugCallback_?this.securityDebugCallback_(body):"msg"in body&&console.log("FIREBASE: "+body.msg.replace("\n","\nFIREBASE: "))},e.prototype.restoreState_=function(){var t,e,n,r;this.tryAuth();try{for(var o=l.__values(this.listens.values()),c=o.next();!c.done;c=o.next()){var h=c.value;try{for(var f=(n=void 0,l.__values(h.values())),d=f.next();!d.done;d=f.next()){var y=d.value;this.sendListen_(y)}}catch(t){n={error:t}}finally{try{d&&!d.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}}}catch(e){t={error:e}}finally{try{c&&!c.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}for(var i=0;i=200&&l.status<300){try{t=f.jsonEval(l.responseText)}catch(t){x("Failed to parse JSON response for "+h+": "+l.responseText)}n(null,t)}else 401!==l.status&&404!==l.status&&x("Got unsuccessful REST response for "+h+" Status: "+l.status),n(l.status);n=null}},l.open("GET",h,!0),l.send()}))},e}(pn),vn=function(){function t(t,e,n){var o,c=this;if(this.repoInfo_=t,this.app=n,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Je,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=new pe,this.persistentConnection_=null,o=void 0!==r&&r.env[T]?new Qe(n):new je(n),this.stats_=He.getCollection(t),e||Y())this.server_=new gn(this.repoInfo_,this.onDataUpdate_.bind(this),o),setTimeout(this.onConnectStatus_.bind(this,!0),0);else{var h=n.options.databaseAuthVariableOverride;if(null!=h){if("object"!=typeof h)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{f.stringify(h)}catch(t){throw new Error("Invalid authOverride provided: "+t)}}this.persistentConnection_=new mn(this.repoInfo_,this.onDataUpdate_.bind(this),this.onConnectStatus_.bind(this),this.onServerInfoUpdate_.bind(this),o,h),this.server_=this.persistentConnection_}o.addTokenChangeListener((function(t){c.server_.refreshAuthToken(t)})),this.statsReporter_=He.getOrCreateReporter(t,(function(){return new Xe(c.stats_,c.server_)})),this.transactions_init_(),this.infoData_=new Be,this.infoSyncTree_=new Ve({startListening:function(t,e,n,r){var o=[],h=c.infoData_.getNode(t.path);return h.isEmpty()||(o=c.infoSyncTree_.applyServerOverwrite(t.path,h),setTimeout((function(){r("ok")}),0)),o},stopListening:function(){}}),this.updateInfo_("connected",!1),this.serverSyncTree_=new Ve({startListening:function(t,e,n,r){return c.server_.listen(t,n,e,(function(e,data){var n=r(e,data);c.eventQueue_.raiseEventsForChangedPath(t.path,n)})),[]},stopListening:function(t,e){c.server_.unlisten(t,e)}})}return t.prototype.toString=function(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host},t.prototype.name=function(){return this.repoInfo_.namespace},t.prototype.serverTime=function(){var t=this.infoData_.getNode(new J(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t},t.prototype.generateServerValues=function(){return(t=(t={timestamp:this.serverTime()})||{}).timestamp=t.timestamp||(new Date).getTime(),t;var t},t.prototype.onDataUpdate_=function(t,data,e,n){this.dataUpdateCount++;var path=new J(t);data=this.interceptServerDataCallback_?this.interceptServerDataCallback_(t,data):data;var r=[];if(n)if(e){var o=f.map(data,(function(t){return ne(t)}));r=this.serverSyncTree_.applyTaggedQueryMerge(path,o,n)}else{var c=ne(data);r=this.serverSyncTree_.applyTaggedQueryOverwrite(path,c,n)}else if(e){var h=f.map(data,(function(t){return ne(t)}));r=this.serverSyncTree_.applyServerMerge(path,h)}else{var l=ne(data);r=this.serverSyncTree_.applyServerOverwrite(path,l)}var d=path;r.length>0&&(d=this.rerunTransactions_(path)),this.eventQueue_.raiseEventsForChangedPath(d,r)},t.prototype.interceptServerData_=function(t){this.interceptServerDataCallback_=t},t.prototype.onConnectStatus_=function(t){this.updateInfo_("connected",t),!1===t&&this.runOnDisconnectEvents_()},t.prototype.onServerInfoUpdate_=function(t){var e=this;Q(t,(function(t,n){e.updateInfo_(t,n)}))},t.prototype.updateInfo_=function(t,e){var path=new J("/.info/"+t),n=ne(e);this.infoData_.updateSnapshot(path,n);var r=this.infoSyncTree_.applyServerOverwrite(path,n);this.eventQueue_.raiseEventsForChangedPath(path,r)},t.prototype.getNextWriteId_=function(){return this.nextWriteId_++},t.prototype.setWithPriority=function(path,t,e,n){var r=this;this.log_("set",{path:path.toString(),value:t,priority:e});var o=this.generateServerValues(),c=ne(t,e),h=ye(c,o),l=this.getNextWriteId_(),f=this.serverSyncTree_.applyUserOverwrite(path,h,l,!0);this.eventQueue_.queueEvents(f),this.server_.put(path.toString(),c.val(!0),(function(t,e){var o="ok"===t;o||x("set at "+path+" failed: "+t);var c=r.serverSyncTree_.ackUserWrite(l,!o);r.eventQueue_.raiseEventsForChangedPath(path,c),r.callOnCompleteCallback(n,t,e)}));var d=this.abortTransactions_(path);this.rerunTransactions_(d),this.eventQueue_.raiseEventsForChangedPath(d,[])},t.prototype.update=function(path,t,e){var n=this;this.log_("update",{path:path.toString(),value:t});var r=!0,o=this.generateServerValues(),c={};if(Q(t,(function(t,e){r=!1;var n=ne(e);c[t]=ye(n,o)})),r)k("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(e,"ok");else{var h=this.getNextWriteId_(),l=this.serverSyncTree_.applyUserMerge(path,c,h);this.eventQueue_.queueEvents(l),this.server_.merge(path.toString(),t,(function(t,r){var o="ok"===t;o||x("update at "+path+" failed: "+t);var c=n.serverSyncTree_.ackUserWrite(h,!o),l=c.length>0?n.rerunTransactions_(path):path;n.eventQueue_.raiseEventsForChangedPath(l,c),n.callOnCompleteCallback(e,t,r)})),Q(t,(function(t){var e=n.abortTransactions_(path.child(t));n.rerunTransactions_(e)})),this.eventQueue_.raiseEventsForChangedPath(path,[])}},t.prototype.runOnDisconnectEvents_=function(){var t=this;this.log_("onDisconnectEvents");var e=this.generateServerValues(),n=function(t,e){var n=new pe;return t.forEachTree(new J(""),(function(path,t){n.remember(path,ye(t,e))})),n}(this.onDisconnect_,e),r=[];n.forEachTree(J.Empty,(function(path,e){r=r.concat(t.serverSyncTree_.applyServerOverwrite(path,e));var n=t.abortTransactions_(path);t.rerunTransactions_(n)})),this.onDisconnect_=new pe,this.eventQueue_.raiseEventsForChangedPath(J.Empty,r)},t.prototype.onDisconnectCancel=function(path,t){var e=this;this.server_.onDisconnectCancel(path.toString(),(function(n,r){"ok"===n&&e.onDisconnect_.forget(path),e.callOnCompleteCallback(t,n,r)}))},t.prototype.onDisconnectSet=function(path,t,e){var n=this,r=ne(t);this.server_.onDisconnectPut(path.toString(),r.val(!0),(function(t,o){"ok"===t&&n.onDisconnect_.remember(path,r),n.callOnCompleteCallback(e,t,o)}))},t.prototype.onDisconnectSetWithPriority=function(path,t,e,n){var r=this,o=ne(t,e);this.server_.onDisconnectPut(path.toString(),o.val(!0),(function(t,e){"ok"===t&&r.onDisconnect_.remember(path,o),r.callOnCompleteCallback(n,t,e)}))},t.prototype.onDisconnectUpdate=function(path,t,e){var n=this;if(f.isEmpty(t))return k("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(e,"ok");this.server_.onDisconnectMerge(path.toString(),t,(function(r,o){"ok"===r&&Q(t,(function(t,e){var r=ne(e);n.onDisconnect_.remember(path.child(t),r)})),n.callOnCompleteCallback(e,r,o)}))},t.prototype.addEventCallbackForQuery=function(t,e){var n;n=".info"===t.path.getFront()?this.infoSyncTree_.addEventRegistration(t,e):this.serverSyncTree_.addEventRegistration(t,e),this.eventQueue_.raiseEventsAtPath(t.path,n)},t.prototype.removeEventCallbackForQuery=function(t,e){var n;n=".info"===t.path.getFront()?this.infoSyncTree_.removeEventRegistration(t,e):this.serverSyncTree_.removeEventRegistration(t,e),this.eventQueue_.raiseEventsAtPath(t.path,n)},t.prototype.interrupt=function(){this.persistentConnection_&&this.persistentConnection_.interrupt("repo_interrupt")},t.prototype.resume=function(){this.persistentConnection_&&this.persistentConnection_.resume("repo_interrupt")},t.prototype.stats=function(t){if(void 0===t&&(t=!1),"undefined"!=typeof console){var e;t?(this.statsListener_||(this.statsListener_=new Ge(this.stats_)),e=this.statsListener_.get()):e=this.stats_.get();var n=Object.keys(e).reduce((function(t,e){return Math.max(e.length,t)}),0);Q(e,(function(t,e){for(var r=t,i=t.length;i=0)return null!=r&&r.trackChildChange(Ne.childChangedChange(e,n,m)),h.updateImmediateChild(e,n);null!=r&&r.trackChildChange(Ne.childRemovedChange(e,m));var w=h.updateImmediateChild(e,Zt.EMPTY_NODE);return null!=v&&this.rangedFilter_.matches(v)?(null!=r&&r.trackChildChange(Ne.childAddedChange(v.name,v.node)),w.updateImmediateChild(v.name,v.node)):w}return n.isEmpty()?t:y&&o(d,l)>=0?(null!=r&&(r.trackChildChange(Ne.childRemovedChange(d.name,d.node)),r.trackChildChange(Ne.childAddedChange(e,n))),h.updateImmediateChild(e,n).updateImmediateChild(d.name,Zt.EMPTY_NODE)):t},t}(),wn=function(){function t(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=Bt}return t.prototype.hasStart=function(){return this.startSet_},t.prototype.isViewFromLeft=function(){return""===this.viewFrom_?this.startSet_:this.viewFrom_===t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT},t.prototype.getIndexStartValue=function(){return f.assert(this.startSet_,"Only valid if start has been set"),this.indexStartValue_},t.prototype.getIndexStartName=function(){return f.assert(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:M},t.prototype.hasEnd=function(){return this.endSet_},t.prototype.getIndexEndValue=function(){return f.assert(this.endSet_,"Only valid if end has been set"),this.indexEndValue_},t.prototype.getIndexEndName=function(){return f.assert(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:F},t.prototype.hasLimit=function(){return this.limitSet_},t.prototype.hasAnchoredLimit=function(){return this.limitSet_&&""!==this.viewFrom_},t.prototype.getLimit=function(){return f.assert(this.limitSet_,"Only valid if limit has been set"),this.limit_},t.prototype.getIndex=function(){return this.index_},t.prototype.copy_=function(){var e=new t;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e},t.prototype.limit=function(t){var e=this.copy_();return e.limitSet_=!0,e.limit_=t,e.viewFrom_="",e},t.prototype.limitToFirst=function(e){var n=this.copy_();return n.limitSet_=!0,n.limit_=e,n.viewFrom_=t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT,n},t.prototype.limitToLast=function(e){var n=this.copy_();return n.limitSet_=!0,n.limit_=e,n.viewFrom_=t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT,n},t.prototype.startAt=function(t,e){var n=this.copy_();return n.startSet_=!0,void 0===t&&(t=null),n.indexStartValue_=t,null!=e?(n.startNameSet_=!0,n.indexStartName_=e):(n.startNameSet_=!1,n.indexStartName_=""),n},t.prototype.endAt=function(t,e){var n=this.copy_();return n.endSet_=!0,void 0===t&&(t=null),n.indexEndValue_=t,void 0!==e?(n.endNameSet_=!0,n.indexEndName_=e):(n.endNameSet_=!1,n.indexEndName_=""),n},t.prototype.orderBy=function(t){var e=this.copy_();return e.index_=t,e},t.prototype.getQueryObject=function(){var e=t.WIRE_PROTOCOL_CONSTANTS_,n={};if(this.startSet_&&(n[e.INDEX_START_VALUE]=this.indexStartValue_,this.startNameSet_&&(n[e.INDEX_START_NAME]=this.indexStartName_)),this.endSet_&&(n[e.INDEX_END_VALUE]=this.indexEndValue_,this.endNameSet_&&(n[e.INDEX_END_NAME]=this.indexEndName_)),this.limitSet_){n[e.LIMIT]=this.limit_;var r=this.viewFrom_;""===r&&(r=this.isViewFromLeft()?e.VIEW_FROM_LEFT:e.VIEW_FROM_RIGHT),n[e.VIEW_FROM]=r}return this.index_!==Bt&&(n[e.INDEX]=this.index_.toString()),n},t.prototype.loadsAllData=function(){return!(this.startSet_||this.endSet_||this.limitSet_)},t.prototype.isDefault=function(){return this.loadsAllData()&&this.index_==Bt},t.prototype.getNodeFilter=function(){return this.loadsAllData()?new Ae(this.getIndex()):this.hasLimit()?new _n(this):new bn(this)},t.prototype.toRestQueryStringParameters=function(){var e,n=t.REST_QUERY_CONSTANTS_,r={};return this.isDefault()?r:(this.index_===Bt?e=n.PRIORITY_INDEX:this.index_===oe?e=n.VALUE_INDEX:this.index_===Ot?e=n.KEY_INDEX:(f.assert(this.index_ instanceof ae,"Unrecognized index type!"),e=this.index_.toString()),r[n.ORDER_BY]=f.stringify(e),this.startSet_&&(r[n.START_AT]=f.stringify(this.indexStartValue_),this.startNameSet_&&(r[n.START_AT]+=","+f.stringify(this.indexStartName_))),this.endSet_&&(r[n.END_AT]=f.stringify(this.indexEndValue_),this.endNameSet_&&(r[n.END_AT]+=","+f.stringify(this.indexEndName_))),this.limitSet_&&(this.isViewFromLeft()?r[n.LIMIT_TO_FIRST]=this.limit_:r[n.LIMIT_TO_LAST]=this.limit_),r)},t.WIRE_PROTOCOL_CONSTANTS_={INDEX_START_VALUE:"sp",INDEX_START_NAME:"sn",INDEX_END_VALUE:"ep",INDEX_END_NAME:"en",LIMIT:"l",VIEW_FROM:"vf",VIEW_FROM_LEFT:"l",VIEW_FROM_RIGHT:"r",INDEX:"i"},t.REST_QUERY_CONSTANTS_={ORDER_BY:"orderBy",PRIORITY_INDEX:"$priority",VALUE_INDEX:"$value",KEY_INDEX:"$key",START_AT:"startAt",END_AT:"endAt",LIMIT_TO_FIRST:"limitToFirst",LIMIT_TO_LAST:"limitToLast"},t.DEFAULT=new t,t}(),En=function(t){function e(e,path){if(!(e instanceof vn))throw new Error("new Reference() no longer supported - use app.database().");return t.call(this,e,path,wn.DEFAULT,!1)||this}return l.__extends(e,t),e.prototype.getKey=function(){return f.validateArgCount("Reference.key",0,0,arguments.length),this.path.isEmpty()?null:this.path.getBack()},e.prototype.child=function(t){return f.validateArgCount("Reference.child",1,1,arguments.length),"number"==typeof t?t=String(t):t instanceof J||(null===this.path.getFront()?Et("Reference.child",1,t,!1):wt("Reference.child",1,t,!1)),new e(this.repo,this.path.child(t))},e.prototype.getParent=function(){f.validateArgCount("Reference.parent",0,0,arguments.length);var t=this.path.parent();return null===t?null:new e(this.repo,t)},e.prototype.getRoot=function(){f.validateArgCount("Reference.root",0,0,arguments.length);for(var t=this;null!==t.getParent();)t=t.getParent();return t},e.prototype.databaseProp=function(){return this.repo.database},e.prototype.set=function(t,e){f.validateArgCount("Reference.set",1,2,arguments.length),Tt("Reference.set",this.path),yt("Reference.set",1,t,this.path,!1),f.validateCallback("Reference.set",2,e,!0);var n=new f.Deferred;return this.repo.setWithPriority(this.path,t,null,n.wrapCallback(e)),n.promise},e.prototype.update=function(t,e){if(f.validateArgCount("Reference.update",1,2,arguments.length),Tt("Reference.update",this.path),Array.isArray(t)){for(var n={},i=0;i0},t.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},t.prototype.forEachChild=function(e){var n=this;Q(this.node_.children,(function(r,o){e(new t(r,n,o))}))},t.prototype.forEachDescendant=function(t,e,n){e&&!n&&t(this),this.forEachChild((function(e){e.forEachDescendant(t,!0,n)})),e&&n&&t(this)},t.prototype.forEachAncestor=function(t,e){for(var n=e?this:this.parent();null!==n;){if(t(n))return!0;n=n.parent()}return!1},t.prototype.forEachImmediateDescendantWithValue=function(t){this.forEachChild((function(e){null!==e.getValue()?t(e):e.forEachImmediateDescendantWithValue(t)}))},t.prototype.path=function(){return new J(null===this.parent_?this.name_:this.parent_.path()+"/"+this.name_)},t.prototype.name=function(){return this.name_},t.prototype.parent=function(){return this.parent_},t.prototype.updateParents_=function(){null!==this.parent_&&this.parent_.updateChild_(this.name_,this)},t.prototype.updateChild_=function(t,e){var n=e.isEmpty(),r=f.contains(this.node_.children,t);n&&r?(delete this.node_.children[t],this.node_.childCount--,this.updateParents_()):n||r||(this.node_.children[t]=e.node_,this.node_.childCount++,this.updateParents_())},t}();!function(t){t[t.RUN=0]="RUN",t[t.SENT=1]="SENT",t[t.COMPLETED=2]="COMPLETED",t[t.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",t[t.NEEDS_ABORT=4]="NEEDS_ABORT"}(Tn||(Tn={})),vn.MAX_TRANSACTION_RETRIES_=25,vn.prototype.transactions_init_=function(){this.transactionQueueTree_=new Cn},vn.prototype.startTransaction=function(path,t,e,n){this.log_("transaction on "+path);var r=function(){},o=new En(this,path);o.on("value",r);var c={path:path,update:t,onComplete:e,status:null,order:S(),applyLocally:n,retryCount:0,unwatcher:function(){o.off("value",r)},abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},h=this.getLatestState_(path);c.currentInputSnapshot=h;var l=c.update(h.val());if(void 0===l){if(c.unwatcher(),c.currentOutputSnapshotRaw=null,c.currentOutputSnapshotResolved=null,c.onComplete){var d=new se(c.currentInputSnapshot,new En(this,c.path),Bt);c.onComplete(null,!1,d)}}else{mt("transaction failed: Data returned ",l,c.path),c.status=Tn.RUN;var y=this.transactionQueueTree_.subTree(path),m=y.getValue()||[];m.push(c),y.setValue(m);var v=void 0;if("object"==typeof l&&null!==l&&f.contains(l,".priority"))v=f.safeGet(l,".priority"),f.assert(pt(v),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else v=(this.serverSyncTree_.calcCompleteEventCache(path)||Zt.EMPTY_NODE).getPriority().val();v=v;var _=this.generateServerValues(),w=ne(l,v),E=ye(w,_);c.currentOutputSnapshotRaw=w,c.currentOutputSnapshotResolved=E,c.currentWriteId=this.getNextWriteId_();var T=this.serverSyncTree_.applyUserOverwrite(path,E,c.currentWriteId,c.applyLocally);this.eventQueue_.raiseEventsForChangedPath(path,T),this.sendReadyTransactions_()}},vn.prototype.getLatestState_=function(path,t){return this.serverSyncTree_.calcCompleteEventCache(path,t)||Zt.EMPTY_NODE},vn.prototype.sendReadyTransactions_=function(t){var e=this;if(void 0===t&&(t=this.transactionQueueTree_),t||this.pruneCompletedTransactionsBelowNode_(t),null!==t.getValue()){var n=this.buildTransactionQueue_(t);f.assert(n.length>0,"Sending zero length transaction queue"),n.every((function(t){return t.status===Tn.RUN}))&&this.sendTransactionQueue_(t.path(),n)}else t.hasChildren()&&t.forEachChild((function(t){e.sendReadyTransactions_(t)}))},vn.prototype.sendTransactionQueue_=function(path,t){for(var e=this,n=t.map((function(t){return t.currentWriteId})),r=this.getLatestState_(path,n),o=r,c=r.hash(),i=0;i=vn.MAX_TRANSACTION_RETRIES_)l=!0,d="maxretry",r=r.concat(this.serverSyncTree_.ackUserWrite(c.currentWriteId,!0));else{var y=this.getLatestState_(c.path,o);c.currentInputSnapshot=y;var m=t[i].update(y.val());if(void 0!==m){mt("transaction failed: Data returned ",m,c.path);var v=ne(m);"object"==typeof m&&null!=m&&f.contains(m,".priority")||(v=v.updatePriority(y.getPriority()));var _=c.currentWriteId,w=this.generateServerValues(),E=ye(v,w);c.currentOutputSnapshotRaw=v,c.currentOutputSnapshotResolved=E,c.currentWriteId=this.getNextWriteId_(),o.splice(o.indexOf(_),1),r=(r=r.concat(this.serverSyncTree_.applyUserOverwrite(c.path,E,c.currentWriteId,c.applyLocally))).concat(this.serverSyncTree_.ackUserWrite(_,!0))}else l=!0,d="nodata",r=r.concat(this.serverSyncTree_.ackUserWrite(c.currentWriteId,!0))}if(this.eventQueue_.raiseEventsForChangedPath(path,r),r=[],l&&(t[i].status=Tn.COMPLETED,e=t[i].unwatcher,setTimeout(e,Math.floor(0)),t[i].onComplete))if("nodata"===d){var T=new En(this,t[i].path),S=t[i].currentInputSnapshot,C=new se(S,T,Bt);n.push(t[i].onComplete.bind(null,null,!1,C))}else n.push(t[i].onComplete.bind(null,new Error(d),!1,null))}this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);for(i=0;i0?n:null)}t.forEachChild((function(t){e.pruneCompletedTransactionsBelowNode_(t)}))},vn.prototype.abortTransactions_=function(path){var t=this,e=this.getAncestorTransactionNode_(path).path(),n=this.transactionQueueTree_.subTree(path);return n.forEachAncestor((function(e){t.abortTransactionsOnNode_(e)})),this.abortTransactionsOnNode_(n),n.forEachDescendant((function(e){t.abortTransactionsOnNode_(e)})),e},vn.prototype.abortTransactionsOnNode_=function(t){var e=t.getValue();if(null!==e){for(var n=[],r=[],o=-1,i=0;i>>0),N=0;function A(a,b,t){return a.call.apply(a.bind,arguments)}function D(a,b,t){if(!a)throw Error();if(2a.b&&(a.b++,b.next=a.a,a.a=b)}function B(){this.b=this.a=null}P(L,Error),L.prototype.name="CustomError",P(M,L),M.prototype.name="AssertionError",U.prototype.get=function(){if(0"}else r=void 0===a?"undefined":null===a?"null":typeof a;F("Argument is not a %s (or a non-Element, non-Location mock); got: %s",b,r)}}B.prototype.add=function(a,b){var t=j.get();t.set(a,b),this.b?this.b.next=t:this.a=t,this.b=t},Q.prototype.set=function(a,b){this.a=a,this.b=b,this.next=null},Q.prototype.reset=function(){this.next=this.b=this.a=null};var H=Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b,void 0)}:function(a,b){if(d(a))return d(b)&&1==b.length?a.indexOf(b,0):-1;for(var t=0;t/g,St=/"/g,Ct=/'/g,It=/\x00/g,Nt=/[\x00&<>"']/;function At(a,b){return-1!=a.indexOf(b)}function Dt(a,b){return ab?1:0}function kt(){this.a="",this.b=Lt}function Rt(a){return a instanceof kt&&a.constructor===kt&&a.b===Lt?a.a:(F("expected object of type SafeUrl, got '"+a+"' of type "+w(a)),"type_error:SafeUrl")}kt.prototype.qa=!0,kt.prototype.pa=function(){return this.a.toString()},kt.prototype.toString=function(){return"SafeUrl{"+this.a+"}"};var Ot=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;function Pt(a){return a instanceof kt?a:(a="object"==typeof a&&a.qa?a.pa():String(a),Ot.test(a)||(a="about:invalid#zClosurez"),Mt(a))}var xt,Lt={};function Mt(a){var b=new kt;return b.a=a,b}Mt("about:blank");t:{var Ft=f.navigator;if(Ft){var Ut=Ft.userAgent;if(Ut){xt=Ut;break t}}xt=""}function qt(a){return At(xt,a)}function Vt(){this.a="",this.b=jt}function Bt(a){return a instanceof Vt&&a.constructor===Vt&&a.b===jt?a.a:(F("expected object of type SafeHtml, got '"+a+"' of type "+w(a)),"type_error:SafeHtml")}Vt.prototype.qa=!0,Vt.prototype.pa=function(){return this.a.toString()},Vt.prototype.toString=function(){return"SafeHtml{"+this.a+"}"};var jt={};function Wt(a){var b=new Vt;return b.a=a,b}Wt("");var Qt,Kt,Ht=Wt("");function Gt(a,b){for(var t=a.split("%s"),e="",n=Array.prototype.slice.call(arguments,1);n.length&&1")&&(a=a.replace(Tt,">")),-1!=a.indexOf('"')&&(a=a.replace(St,""")),-1!=a.indexOf("'")&&(a=a.replace(Ct,"'")),-1!=a.indexOf("\0")&&(a=a.replace(It,"�"))),a}function Yt(a){f.setTimeout((function(){throw a}),0)}function Xt(){var a=f.MessageChannel;if(void 0===a&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!qt("Presto")&&(a=function(){var t=document.createElement("IFRAME");t.style.display="none",function(a){var b=bt(ut(lt));K(a,"HTMLIFrameElement"),a.src=pt(b).toString()}(t),document.documentElement.appendChild(t);var e=t.contentWindow;(t=e.document).open(),t.write(Bt(Ht)),t.close();var g="callImmediate"+Math.random(),n="file:"==e.location.protocol?"*":e.location.protocol+"//"+e.location.host;t=k((function(t){"*"!=n&&t.origin!=n||t.data!=g||this.port1.onmessage()}),this),e.addEventListener("message",t,!1),this.port1={},this.port2={postMessage:function(){e.postMessage(g,n)}}}),void 0!==a&&!qt("Trident")&&!qt("MSIE")){var b=new a,t={},e=t;return b.port1.onmessage=function(){if(void 0!==t.next){var e=(t=t.next).yb;t.yb=null,e()}},function(t){e.next={yb:t},e=e.next,b.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(t){var e=document.createElement("SCRIPT");e.onreadystatechange=function(){e.onreadystatechange=null,e.parentNode.removeChild(e),e=null,t(),t=null},document.documentElement.appendChild(e)}:function(t){f.setTimeout(t,0)}}function Jt(a,b){Kt||function(){if(f.Promise&&f.Promise.resolve){var a=f.Promise.resolve(void 0);Kt=function(){a.then(te)}}else Kt=function(){var b=te;!q(f.setImmediate)||f.Window&&f.Window.prototype&&!qt("Edge")&&f.Window.prototype.setImmediate==f.setImmediate?(Qt||(Qt=Xt()),Qt(b)):f.setImmediate(b)}}(),$t||(Kt(),$t=!0),Zt.add(a,b)}Wt("
");var $t=!1,Zt=new B;function te(){for(var a;a=W();){try{a.a.call(a.b)}catch(t){Yt(t)}V(j,a)}$t=!1}function ee(a,b){if(this.a=ne,this.i=void 0,this.f=this.b=this.c=null,this.g=this.h=!1,a!=_)try{var t=this;a.call(b,(function(e){de(t,re,e)}),(function(e){if(!(e instanceof we))try{if(e instanceof Error)throw e;throw Error("Promise rejected.")}catch(t){}de(t,ie,e)}))}catch(t){de(this,ie,t)}}var ne=0,re=2,ie=3;function oe(){this.next=this.f=this.b=this.g=this.a=null,this.c=!1}oe.prototype.reset=function(){this.f=this.b=this.g=this.a=null,this.c=!1};var ae=new U((function(){return new oe}),(function(a){a.reset()}));function se(a,b,t){var e=ae.get();return e.g=a,e.b=b,e.f=t,e}function ue(a){if(a instanceof ee)return a;var b=new ee(_);return de(b,re,a),b}function ce(a){return new ee((function(b,t){t(a)}))}function he(a,b,t){ye(a,b,t,null)||Jt(R(b,a))}function le(a){return new ee((function(b){var t=a.length,e=[];if(t)for(var n=function(n,r,p){t--,e[n]=r?{Gb:!0,value:p}:{Gb:!1,reason:p},0==t&&b(e)},r=0;rparseFloat(Le)){Ne=String(Fe);break t}}Ne=Le}var Ue,qe={};function Ve(a){return function(a,b){var t=qe;return Object.prototype.hasOwnProperty.call(t,a)?t[a]:t[a]=b(a)}(a,(function(){for(var b=0,t=_t(String(Ne)).split("."),e=_t(String(a)).split("."),n=Math.max(t.length,e.length),r=0;0==b&&r=a.keyCode)&&(a.keyCode=-1)}catch(t){}},He.prototype.f=function(){return this.a};var ze="closure_listenable_"+(1e6*Math.random()|0),Ye=0;function Xe(a,b,t,e,n){this.listener=a,this.proxy=null,this.src=b,this.type=t,this.capture=!!e,this.Na=n,this.key=++Ye,this.ra=this.Ia=!1}function Je(a){a.ra=!0,a.listener=null,a.proxy=null,a.src=null,a.Na=null}function $e(a){this.src=a,this.a={},this.b=0}function Ze(a,b){var t=b.type;t in a.a&&J(a.a[t],b)&&(Je(b),0==a.a[t].length&&(delete a.a[t],a.b--))}function tn(a,b,t,e){for(var n=0;ne.keyCode||null!=e.returnValue)){t:{var n=!1;if(0==e.keyCode)try{e.keyCode=-1;break t}catch(t){n=!0}(n||null==e.returnValue)&&(e.returnValue=!0)}for(e=[],n=b.b;n;n=n.parentNode)e.push(n);for(a=a.type,n=e.length-1;0<=n;n--){b.b=e[n];var r=hn(e[n],a,!0,b);t=t&&r}for(n=0;n>>0);function dn(a){return q(a)?a:(a[pn]||(a[pn]=function(b){return a.handleEvent(b)}),a[pn])}function yn(){Ee.call(this),this.u=new $e(this),this.Sb=this,this.Wa=null}function mn(a,b,t,e,n){a.u.add(String(b),t,!1,e,n)}function gn(a,b,t,e,n){a.u.add(String(b),t,!0,e,n)}function vn(a,b,t,e){if(!(b=a.u.a[String(b)]))return!0;b=b.concat();for(var n=!0,r=0;rb)throw Error("Bad port number "+b);a.l=b}else a.l=null}function Dn(a,b,t){b instanceof jn?(a.a=b,function(a,b){b&&!a.f&&(Wn(a),a.c=null,a.a.forEach((function(t,e){var n=e.toLowerCase();e!=n&&(Kn(this,e),Gn(this,n,t))}),a)),a.f=b}(a.a,a.h)):(t||(b=Ln(b,Vn)),a.a=new jn(b,a.h))}function kn(a,b,t){a.a.set(b,t)}function Rn(a,b){return a.a.get(b)}function On(a){return a instanceof In?new In(a):new In(a,void 0)}function Pn(a,b){var t=new In(null,void 0);return Nn(t,"https"),a&&(t.b=a),b&&(t.c=b),t}function xn(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function Ln(a,b,t){return d(a)?(a=encodeURI(a).replace(b,Mn),t&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null}function Mn(a){return"%"+((a=a.charCodeAt(0))>>4&15).toString(16)+(15&a).toString(16)}In.prototype.toString=function(){var a=[],b=this.f;b&&a.push(Ln(b,Fn,!0),":");var t=this.b;return(t||"file"==b)&&(a.push("//"),(b=this.i)&&a.push(Ln(b,Fn,!0),"@"),a.push(encodeURIComponent(String(t)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(t=this.l)&&a.push(":",String(t))),(t=this.c)&&(this.b&&"/"!=t.charAt(0)&&a.push("/"),a.push(Ln(t,"/"==t.charAt(0)?qn:Un,!0))),(t=this.a.toString())&&a.push("?",t),(t=this.g)&&a.push("#",Ln(t,Bn)),a.join("")},In.prototype.resolve=function(a){var b=new In(this),t=!!a.f;t?Nn(b,a.f):t=!!a.i,t?b.i=a.i:t=!!a.b,t?b.b=a.b:t=null!=a.l;var e=a.c;if(t)An(b,a.l);else if(t=!!a.c){if("/"!=e.charAt(0))if(this.b&&!this.c)e="/"+e;else{var n=b.c.lastIndexOf("/");-1!=n&&(e=b.c.substr(0,n+1)+e)}if(".."==(n=e)||"."==n)e="";else if(At(n,"./")||At(n,"/.")){e=0==n.lastIndexOf("/",0),n=n.split("/");for(var r=[],g=0;g2*a.c&&Sn(a)))}function Hn(a,b){return Wn(a),b=Yn(a,b),td(a.a.b,b)}function Gn(a,b,t){Kn(a,b),0"),r=r.join("")}return r=n.createElement(r),g&&(d(g)?r.className=g:T(g)?r.className=g.join(" "):$n(r,g)),2'),g.document.write(Bt(a)),g.document.close())):(g=e.open(Rt(b).toString(),t,g))&&a.noopener&&(g.opener=null),g)try{g.focus()}catch(t){}return g}var yr=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,mr=/^[^@]+@[^@]+$/;function gr(){var a=null;return new ee((function(b){"complete"==f.document.readyState?b():(a=function(){b()},an(window,"load",a))})).s((function(b){throw sn(window,"load",a),b}))}function vr(a){return a=a||Dr(),!("file:"!==xr()||!a.toLowerCase().match(/iphone|ipad|ipod|android/))}function _r(){var a=f.window;try{return!(!a||a==a.top)}catch(t){return!1}}function wr(){return void 0!==f.WorkerGlobalScope&&"function"==typeof f.importScripts}function Er(){return r.a.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":r.a.INTERNAL.hasOwnProperty("node")?"Node":wr()?"Worker":"Browser"}function Tr(){var a=Er();return"ReactNative"===a||"Node"===a}var Sr="Firefox",Cr="Chrome";function Ir(a){var b=a.toLowerCase();return At(b,"opera/")||At(b,"opr/")||At(b,"opios/")?"Opera":At(b,"iemobile")?"IEMobile":At(b,"msie")||At(b,"trident/")?"IE":At(b,"edge/")?"Edge":At(b,"firefox/")?Sr:At(b,"silk/")?"Silk":At(b,"blackberry")?"Blackberry":At(b,"webos")?"Webos":!At(b,"safari/")||At(b,"chrome/")||At(b,"crios/")||At(b,"android")?!At(b,"chrome/")&&!At(b,"crios/")||At(b,"edge/")?At(b,"android")?"Android":(a=a.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==a.length?a[1]:"Other":Cr:"Safari"}var Nr={Vc:"FirebaseCore-web",Xc:"FirebaseUI-web"};function Ar(a,b){b=b||[];var t,e=[],n={};for(t in Nr)n[Nr[t]]=!0;for(t=0;tb)throw Error("Short delay should be less than long delay!");this.a=a,this.c=b,a=Dr(),b=Er(),this.b=fr(a)||"ReactNative"===b}function Wr(){var a=f.document;return!a||void 0===a.visibilityState||"visible"==a.visibilityState}function Qr(a){try{var b=new Date(parseInt(a,10));if(!isNaN(b.getTime())&&!/[^0-9]/.test(a))return b.toUTCString()}catch(t){}return null}function Kr(){return!(!kr("fireauth.oauthhelper",f)&&!kr("fireauth.iframe",f))}jr.prototype.get=function(){var a=f.navigator;return!a||"boolean"!=typeof a.onLine||!Pr()&&"chrome-extension:"!==xr()&&void 0===a.connection||a.onLine?this.b?this.c:this.a:Math.min(5e3,this.a)};var Hr,Gr={};function zr(a){Gr[a]||(Gr[a]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(a))}try{var Yr={};Object.defineProperty(Yr,"abcd",{configurable:!0,enumerable:!0,value:1}),Object.defineProperty(Yr,"abcd",{configurable:!0,enumerable:!0,value:2}),Hr=2==Yr.abcd}catch(a){Hr=!1}function Xr(a,b,t){Hr?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:t}):a[b]=t}function Jr(a,b){if(b)for(var t in b)b.hasOwnProperty(t)&&Xr(a,t,b[t])}function $r(a){var b={};return Jr(b,a),b}function Zr(a){var b=a;if("object"==typeof a&&null!=a)for(var t in b="length"in a?[]:{},a)Xr(b,t,Zr(a[t]));return b}function ti(a){var b={},t=a[ni],e=a[ri];if(!(a=a[ii])||a!=ei&&!t)throw Error("Invalid provider user info!");b[ai]=e||null,b[oi]=t||null,Xr(this,ui,a),Xr(this,si,Zr(b))}var ei="EMAIL_SIGNIN",ni="email",ri="newEmail",ii="requestType",oi="email",ai="fromEmail",si="data",ui="operation";function ci(a,b){this.code=fi+a,this.message=b||pi[a]||""}function hi(a){var b=a&&a.code;return b?new ci(b.substring(fi.length),a.message):null}P(ci,Error),ci.prototype.A=function(){return{code:this.code,message:this.message}},ci.prototype.toJSON=function(){return this.A()};var fi="auth/",pi={"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-already-in-use":"The email address is already in use by another account.","expired-action-code":"The action code has expired. ","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal error has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal error has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal error has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The OIDC ID token requires a valid unhashed nonce.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network error (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal error has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","user-cancelled":"User did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled."};function di(a){var b=Rn(a=On(a),yi)||null,t=Rn(a,mi)||null,e=Rn(a,bi)||null;if(e=e&&wi[e]||null,!b||!t||!e)throw new ci("argument-error",yi+", "+mi+"and "+bi+" are required in a valid action code URL.");Jr(this,{apiKey:b,operation:e,code:t,continueUrl:Rn(a,gi)||null,languageCode:Rn(a,vi)||null,tenantId:Rn(a,_i)||null})}var yi="apiKey",mi="oobCode",gi="continueUrl",vi="languageCode",bi="mode",_i="tenantId",wi={recoverEmail:"RECOVER_EMAIL",resetPassword:"PASSWORD_RESET",signIn:ei,verifyEmail:"VERIFY_EMAIL"};function Ei(a){try{return new di(a)}catch(t){return null}}function Ti(a){var b=a[Ai];if(void 0===b)throw new ci("missing-continue-uri");if("string"!=typeof b||"string"==typeof b&&!b.length)throw new ci("invalid-continue-uri");this.h=b,this.b=this.a=null,this.g=!1;var t=a[Si];if(t&&"object"==typeof t){b=t[Ri];var e=t[Di];if(t=t[ki],"string"==typeof b&&b.length){if(this.a=b,void 0!==e&&"boolean"!=typeof e)throw new ci("argument-error",Di+" property must be a boolean when specified.");if(this.g=!!e,void 0!==t&&("string"!=typeof t||"string"==typeof t&&!t.length))throw new ci("argument-error",ki+" property must be a non empty string when specified.");this.b=t||null}else{if(void 0!==b)throw new ci("argument-error",Ri+" property must be a non empty string when specified.");if(void 0!==e||void 0!==t)throw new ci("missing-android-pkg-name")}}else if(void 0!==t)throw new ci("argument-error",Si+" property must be a non null object when specified.");if(this.f=null,(b=a[Ni])&&"object"==typeof b){if("string"==typeof(b=b[Oi])&&b.length)this.f=b;else if(void 0!==b)throw new ci("argument-error",Oi+" property must be a non empty string when specified.")}else if(void 0!==b)throw new ci("argument-error",Ni+" property must be a non null object when specified.");if(void 0!==(b=a[Ii])&&"boolean"!=typeof b)throw new ci("argument-error",Ii+" property must be a boolean when specified.");if(this.c=!!b,void 0!==(a=a[Ci])&&("string"!=typeof a||"string"==typeof a&&!a.length))throw new ci("argument-error",Ci+" property must be a non empty string when specified.");this.i=a||null}var Si="android",Ci="dynamicLinkDomain",Ii="handleCodeInApp",Ni="iOS",Ai="url",Di="installApp",ki="minimumVersion",Ri="packageName",Oi="bundleId";function Pi(a){var b={};for(var t in b.continueUrl=a.h,b.canHandleCodeInApp=a.c,(b.androidPackageName=a.a)&&(b.androidMinimumVersion=a.b,b.androidInstallApp=a.g),b.iOSBundleId=a.f,b.dynamicLinkDomain=a.i,b)null===b[t]&&delete b[t];return b}var xi=null,Li=null;function Mi(a){var b="";return function(a,b){function t(t){for(;ea;a++)xi[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a),Li[xi[a]]=a,62<=a&&(Li["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(a)]=a)}}();for(var e=0;;){var n=t(-1),r=t(0),g=t(64),o=t(64);if(64===o&&-1===n)break;b(n<<2|r>>4),64!=g&&(b(r<<4&240|g>>2),64!=o&&b(g<<6&192|o))}}(a,(function(t){b+=String.fromCharCode(t)})),b}function Fi(a){this.f=a.sub,O(),this.a=a.provider_id||a.firebase&&a.firebase.sign_in_provider||null,this.c=a.firebase&&a.firebase.tenant||null,this.b=!!a.is_anonymous||"anonymous"==this.a}function Ui(a){return(a=qi(a))&&a.sub&&a.iss&&a.aud&&a.exp?new Fi(a):null}function qi(a){if(!a)return null;if(3!=(a=a.split(".")).length)return null;for(var b=(4-(a=a[1]).length%4)%4,t=0;t Auth section -> Sign in method tab.",a):"http"==e||"https"==e?t=Gt("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",a):b="operation-not-supported-in-this-environment",ci.call(this,b,t)}function Bo(a,b,t){ci.call(this,a,t),(a=b||{}).Ab&&Xr(this,"email",a.Ab),a.ba&&Xr(this,"phoneNumber",a.ba),a.credential&&Xr(this,"credential",a.credential),a.Qb&&Xr(this,"tenantId",a.Qb)}function jo(a){if(a.code){var b=a.code||"";0==b.indexOf(fi)&&(b=b.substring(fi.length));var t={credential:Po(a),Qb:a.tenantId};if(a.email)t.Ab=a.email;else if(a.phoneNumber)t.ba=a.phoneNumber;else if(!t.credential)return new ci(b,a.message||void 0);return new Bo(b,t,a.message)}return null}function Wo(){}function Qo(a){return a.c||(a.c=a.b())}function Ko(){}function Ho(a){if(!a.f&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var b=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],t=0;t=function t(a){return a.c?a.c:a.a?t(a.a):(F("Root logger has no level set."),null)}(this).value)for(q(b)&&(b=b()),a=new Xo(a,String(b),this.f),t&&(a.a=t),t=this;t;)t=t.a};var na={},ra=null;function ia(a){var b;if(ra||(ra=new Jo(""),na[""]=ra,ra.c=th),!(b=na[a])){b=new Jo(a);var t=a.lastIndexOf("."),e=a.substr(t+1);(t=ia(a.substr(0,t))).b||(t.b={}),t.b[e]=b,b.a=t,na[a]=b}return b}function oa(a,b){a&&a.log(ea,b,void 0)}function aa(a){this.f=a}function sa(a){yn.call(this),this.o=a,this.readyState=ua,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.i=new Headers,this.b=null,this.m="GET",this.g="",this.a=!1,this.h=ia("goog.net.FetchXmlHttp"),this.l=this.c=this.f=null}P(aa,Wo),aa.prototype.a=function(){return new sa(this.f)},aa.prototype.b=function(a){return function(){return a}}({}),P(sa,yn);var ua=0;function ca(a){a.c.read().then(a.ec.bind(a)).catch(a.Ma.bind(a))}function ha(a,b){b&&a.f&&(a.status=a.f.status,a.statusText=a.f.statusText),a.readyState=4,a.f=null,a.c=null,a.l=null,la(a)}function la(a){a.onreadystatechange&&a.onreadystatechange.call(a)}function fa(a){yn.call(this),this.headers=new Tn,this.B=a||null,this.c=!1,this.w=this.a=null,this.h=this.O=this.l="",this.f=this.J=this.i=this.I=!1,this.g=0,this.o=null,this.m=pa,this.v=this.P=!1}(e=sa.prototype).open=function(a,b){if(this.readyState!=ua)throw this.abort(),Error("Error reopening a connection");this.m=a,this.g=b,this.readyState=1,la(this)},e.send=function(a){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.a=!0;var b={headers:this.i,method:this.m,credentials:void 0,cache:void 0};a&&(b.body=a),this.o.fetch(new Request(this.g,b)).then(this.jc.bind(this),this.Ma.bind(this))},e.abort=function(){this.response=this.responseText="",this.i=new Headers,this.status=0,this.c&&this.c.cancel("Request was aborted."),1<=this.readyState&&this.a&&4!=this.readyState&&(this.a=!1,ha(this,!1)),this.readyState=ua},e.jc=function(a){this.a&&(this.f=a,this.b||(this.b=a.headers,this.readyState=2,la(this)),this.a&&(this.readyState=3,la(this),this.a&&("arraybuffer"===this.responseType?a.arrayBuffer().then(this.hc.bind(this),this.Ma.bind(this)):void 0!==f.ReadableStream&&"body"in a?(this.response=this.responseText="",this.c=a.body.getReader(),this.l=new TextDecoder,ca(this)):a.text().then(this.ic.bind(this),this.Ma.bind(this)))))},e.ec=function(a){if(this.a){var b=this.l.decode(a.value?a.value:new Uint8Array(0),{stream:!a.done});b&&(this.response=this.responseText+=b),a.done?ha(this,!0):la(this),3==this.readyState&&ca(this)}},e.ic=function(a){this.a&&(this.response=this.responseText=a,ha(this,!0))},e.hc=function(a){this.a&&(this.response=a,ha(this,!0))},e.Ma=function(a){var b=this.h;b&&b.log(ta,"Failed to fetch url "+this.g,a instanceof Error?a:Error(a)),this.a&&ha(this,!0)},e.setRequestHeader=function(a,b){this.i.append(a,b)},e.getResponseHeader=function(a){return this.b?this.b.get(a.toLowerCase())||"":((a=this.h)&&a.log(ta,"Attempting to get response header but no headers have been received for url: "+this.g,void 0),"")},e.getAllResponseHeaders=function(){if(!this.b){var a=this.h;return a&&a.log(ta,"Attempting to get all response headers but no headers have been received for url: "+this.g,void 0),""}a=[];for(var b=this.b.entries(),t=b.next();!t.done;)t=t.value,a.push(t[0]+": "+t[1]),t=b.next();return a.join("\r\n")},P(fa,yn);var pa="";fa.prototype.b=ia("goog.net.XhrIo");var da=/^https?$/i,ya=["POST","PUT"];function ma(a,b,t,e,n){if(a.a)throw Error("[goog.net.XhrIo] Object is active with another request="+a.l+"; newUri="+b);t=t?t.toUpperCase():"GET",a.l=b,a.h="",a.O=t,a.I=!1,a.c=!0,a.a=a.B?a.B.a():Uo.a(),a.w=a.B?Qo(a.B):Qo(Uo),a.a.onreadystatechange=k(a.Lb,a);try{oa(a.b,Ca(a,"Opening Xhr")),a.J=!0,a.a.open(t,String(b),!0),a.J=!1}catch(t){return oa(a.b,Ca(a,"Error opening Xhr: "+t.message)),void va(a,t)}b=e||"";var r=new Tn(a.headers);n&&function(a,b){if(a.forEach&&"function"==typeof a.forEach)a.forEach(b,void 0);else if(S(a)||d(a))G(a,b,void 0);else for(var t=En(a),e=wn(a),n=e.length,r=0;rb?null:d(a)?a.charAt(b):a[b]}(r.X()),e=f.FormData&&b instanceof f.FormData,!X(ya,t)||n||e||r.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),r.forEach((function(g,t){this.a.setRequestHeader(t,g)}),a),a.m&&(a.a.responseType=a.m),"withCredentials"in a.a&&a.a.withCredentials!==a.P&&(a.a.withCredentials=a.P);try{Ea(a),0=b.l&&b.cancel())}this.v?this.v.call(this.o,this):this.u=!0,this.a||(a=new Pa(this),Aa(this),Na(this,!1,a))}},Ia.prototype.m=function(a,b){this.i=!1,Na(this,a,b)},Ia.prototype.then=function(a,b,t){var e,n,r=new ee((function(g,t){e=g,n=t}));return Da(this,e,(function(g){g instanceof Pa?r.cancel():n(g)})),r.then(a,b,t)},Ia.prototype.$goog_Thenable=!0,P(Oa,L),Oa.prototype.message="Deferred has already fired",Oa.prototype.name="AlreadyCalledError",P(Pa,L),Pa.prototype.message="Deferred was canceled",Pa.prototype.name="CanceledError",xa.prototype.c=function(){throw delete La[this.a],this.b};var La={};function Ma(a){var b={},t=b.document||document,e=pt(a).toString(),n=document.createElement("SCRIPT"),r={Nb:n,Ga:void 0},g=new Ia(r),o=null,c=null!=b.timeout?b.timeout:5e3;return 0a)&&(!De||!Ue||9b;b++){n=0|t[b-15],e=0|t[b-2];var r=(0|t[b-16])+((n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3)|0,g=(0|t[b-7])+((e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10)|0;t[b]=r+g|0}e=0|a.a[0],n=0|a.a[1];var o=0|a.a[2],c=0|a.a[3],p=0|a.a[4],u=0|a.a[5],h=0|a.a[6];for(r=0|a.a[7],b=0;64>b;b++){var l=((e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10))+(e&n^e&o^n&o)|0;g=(r=r+((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))|0)+((g=(g=p&u^~p&h)+(0|Wu[b])|0)+(0|t[b])|0)|0,r=h,h=u,u=p,p=c+g|0,c=o,o=n,n=e,e=g+l|0}a.a[0]=a.a[0]+e|0,a.a[1]=a.a[1]+n|0,a.a[2]=a.a[2]+o|0,a.a[3]=a.a[3]+c|0,a.a[4]=a.a[4]+p|0,a.a[5]=a.a[5]+u|0,a.a[6]=a.a[6]+h|0,a.a[7]=a.a[7]+r|0}function Zu(a,b,t){void 0===t&&(t=b.length);var e=0,n=a.c;if(d(b))for(;e=r&&r==(0|r)))throw Error("message must be a byte array");a.f[n++]=r,n==a.b&&($u(a),n=0)}}a.c=n,a.g+=t}Hu.prototype.reset=function(){this.g=this.c=0,this.a=f.Int32Array?new Int32Array(this.h):tt(this.h)};var tc=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ec(){Hu.call(this,8,nc)}P(ec,Hu);var nc=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function rc(a,b,t,e,n){this.u=a,this.i=b,this.l=t,this.m=e||null,this.o=n||null,this.h=b+":"+t,this.v=new Ku,this.g=new ju(this.h),this.f=null,this.b=[],this.a=this.c=null}function ic(a){return new ci("invalid-cordova-configuration",a)}function oc(a){var b=new ec;Zu(b,a),a=[];var t=8*b.g;56>b.c?Zu(b,Ju,56-b.c):Zu(b,Ju,b.b-(b.c-56));for(var e=63;56<=e;e--)b.f[e]=255&t,t/=256;for($u(b),e=t=0;e>n&255;return function(a){return z(a,(function(b){return 1<(b=b.toString(16)).length?b:"0"+b})).join("")}(a)}function ac(a,b){for(var t=0;ta.f&&(a.a=a.f),b)}(a,b)).then((function(){return function(){var a=f.document,b=null;return Wr()||!a?ue():new ee((function(t){b=function(){Wr()&&(a.removeEventListener("visibilitychange",b,!1),t())},a.addEventListener("visibilitychange",b,!1)})).s((function(t){throw a.removeEventListener("visibilitychange",b,!1),t}))}()})).then((function(){return a.h()})).then((function(){t(a,!0)})).s((function(e){a.i(e)&&t(a,!1)}))}(this,!0)},xc.prototype.stop=function(){this.b&&(this.b.cancel(),this.b=null)},Lc.prototype.A=function(){return{apiKey:this.f.c,refreshToken:this.a,accessToken:this.b,expirationTime:this.c}},Lc.prototype.getToken=function(a){return a=!!a,this.b&&!this.a?ce(new ci("user-token-expired")):a||!this.b||O()>this.c-3e4?this.a?Uc(this,{grant_type:"refresh_token",refresh_token:this.a}):ue(null):ue({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},qc.prototype.A=function(){return{lastLoginAt:this.b,createdAt:this.a}},P(Bc,Ke),P(jc,yn),jc.prototype.sa=function(a){this.ga=a,Xa(this.a,a)},jc.prototype.ha=function(){return this.ga},jc.prototype.Aa=function(){return tt(this.P)},jc.prototype.Ha=function(){this.w.b&&(this.w.stop(),this.w.start())},Xr(jc.prototype,"providerId","firebase"),(e=jc.prototype).reload=function(){var a=this;return dh(this,eh(this).then((function(){return ah(a).then((function(){return Xc(a)})).then(Zc)})))},e.dc=function(a){return this.G(a).then((function(b){return new Pc(b)}))},e.G=function(a){var b=this;return dh(this,eh(this).then((function(){return b.b.getToken(a)})).then((function(t){if(!t)throw new ci("internal-error");return t.accessToken!=b.ma&&(Yc(b,t.accessToken),b.dispatchEvent(new Bc("tokenChanged"))),ih(b,"refreshToken",t.refreshToken),t.accessToken})))},e.zc=function(a){if(!(a=a.users)||!a.length)throw new ci("internal-error");$c(this,{uid:(a=a[0]).localId,displayName:a.displayName,photoURL:a.photoUrl,email:a.email,emailVerified:!!a.emailVerified,phoneNumber:a.phoneNumber,lastLoginAt:a.lastLoginAt,createdAt:a.createdAt,tenantId:a.tenantId});for(var b=function(a){return(a=a.providerUserInfo)&&a.length?z(a,(function(b){return new Vc(b.rawId,b.providerId,b.email,b.displayName,b.photoUrl,b.phoneNumber)})):[]}(a),t=0;tthis.o&&(this.o=0),0==this.o&&Mh(this)&&zc(Mh(this)),this.removeAuthTokenListener(a)},e.addAuthTokenListener=function(a){var b=this;this.m.push(a),qh(this,this.i.then((function(){b.l||X(b.m,a)&&a(Fh(b))})))},e.removeAuthTokenListener=function(a){$(this.m,(function(b){return b==a}))},e.delete=function(){this.l=!0;for(var a=0;an||n>=ll.length)throw new ci("internal-error","Argument validator received an unsupported number of arguments.");t=ll[n],e=(e?"":t+" argument ")+(b.name?'"'+b.name+'" ':"")+"must be "+b.M+".";break t}e=null}}if(e)throw new ci("argument-error",a+" failed: "+e)}(e=Zh.prototype).Ba=function(){var a=this;return this.f?this.f:this.f=al(this,ue().then((function(){if(Pr()&&!wr())return gr();throw new ci("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment.")})).then((function(){return a.m.g(a.v())})).then((function(b){return a.g=b,Vs(a.o,Is,{})})).then((function(b){a.a[nl]=b.recaptchaSiteKey})).s((function(b){throw a.f=null,b})))},e.render=function(){sl(this);var a=this;return al(this,this.Ba().then((function(){if(null===a.c){var b=a.u;if(!a.i){var t=Jn(b);b=er("DIV"),t.appendChild(b)}a.c=a.g.render(b,a.a)}return a.c})))},e.verify=function(){sl(this);var a=this;return al(this,this.render().then((function(b){return new ee((function(t){var e=a.g.getResponse(b);if(e)t(e);else{var n=function(e){e&&(function(a,b){$(a.l,(function(t){return t==b}))}(a,n),t(e))};a.l.push(n),a.i&&a.g.execute(a.c)}}))})))},e.reset=function(){sl(this),null!==this.c&&this.g.reset(this.c)},e.clear=function(){sl(this),this.B=!0,this.m.c();for(var a=0;a>6,128|63&e);else if(55296==(64512&e))if(i>18,128|e>>12&63,128|e>>6&63,128|63&e);else b.push(239,191,189);else 56320==(64512&e)?b.push(239,191,189):b.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(b)}function x(t,e){switch(t){case D.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw N(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case D.BASE64URL:var o=-1!==e.indexOf("+"),c=-1!==e.indexOf("/");if(o||c)throw N(t,"Invalid character '"+(o?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}var h;try{h=atob(e)}catch(e){throw N(t,"Invalid character found")}for(var l=new Uint8Array(h.length),i=0;i][;base64],");var n=e[1]||null;null!=n&&(this.base64=(s=n,r=";base64",s.length>=r.length&&s.substring(s.length-r.length)===r),this.contentType=this.base64?n.substring(0,n.length-";base64".length):n),this.rest=t.substring(t.indexOf(",")+1);var s,r};var M,F={STATE_CHANGED:"state_changed"},U={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},V={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function B(t){switch(t){case U.RUNNING:case U.PAUSING:case U.CANCELING:return V.RUNNING;case U.PAUSED:return V.PAUSED;case U.SUCCESS:return V.SUCCESS;case U.CANCELED:return V.CANCELED;case U.ERROR:default:return V.ERROR}}function j(p){return null!=p}function W(p){return void 0!==p}function Q(p){return"function"==typeof p}function K(p){return"object"==typeof p}function H(p){return K(p)&&null!==p}function G(p){return"string"==typeof p||p instanceof String}function z(p){return Y(p)&&Number.isInteger(p)}function Y(p){return"number"==typeof p||p instanceof Number}function X(p){return J()&&p instanceof Blob}function J(){return"undefined"!=typeof Blob}!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(M||(M={}));var $=function(){function t(){var t=this;this.sent_=!1,this.xhr_=new XMLHttpRequest,this.errorCode_=M.NO_ERROR,this.sendPromise_=new Promise((function(e){t.xhr_.addEventListener("abort",(function(){t.errorCode_=M.ABORT,e(t)})),t.xhr_.addEventListener("error",(function(){t.errorCode_=M.NETWORK_ERROR,e(t)})),t.xhr_.addEventListener("load",(function(){e(t)}))}))}return t.prototype.send=function(t,e,body,n){if(this.sent_)throw A("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(e,t,!0),j(n))for(var r in n)n.hasOwnProperty(r)&&this.xhr_.setRequestHeader(r,n[r].toString());return j(body)?this.xhr_.send(body):this.xhr_.send(),this.sendPromise_},t.prototype.getErrorCode=function(){if(!this.sent_)throw A("cannot .getErrorCode() before sending");return this.errorCode_},t.prototype.getStatus=function(){if(!this.sent_)throw A("cannot .getStatus() before sending");try{return this.xhr_.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.sent_)throw A("cannot .getResponseText() before sending");return this.xhr_.responseText},t.prototype.abort=function(){this.xhr_.abort()},t.prototype.getResponseHeader=function(header){return this.xhr_.getResponseHeader(header)},t.prototype.addUploadProgressListener=function(t){j(this.xhr_.upload)&&this.xhr_.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){j(this.xhr_.upload)&&this.xhr_.upload.removeEventListener("progress",t)},t}(),Z=function(){function t(){}return t.prototype.createXhrIo=function(){return new $},t}();function tt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function et(){for(var t=[],e=0;e0})).join("/");return 0===path.length?e:path+"/"+e}function st(path){var t=path.lastIndexOf("/",path.length-2);return-1===t?path:path.slice(t+1)}function ut(t){return"https://"+h+"/v0"+t}function ct(t){var e=encodeURIComponent,n="?";for(var r in t){if(t.hasOwnProperty(r))n=n+(e(r)+"="+e(t[r]))+"&"}return n=n.slice(0,-1)}function ht(t,e){return e}var lt=function(t,e,n,r){this.server=t,this.local=e||t,this.writable=!!n,this.xform=r||ht},ft=null;function pt(){if(ft)return ft;var t=[];t.push(new lt("bucket")),t.push(new lt("generation")),t.push(new lt("metageneration")),t.push(new lt("name","fullPath",!0));var e=new lt("name");e.xform=function(t,e){return function(t){return!G(t)||t.length<2?t:st(t)}(e)},t.push(e);var n=new lt("size");return n.xform=function(t,e){return j(e)?Number(e):e},t.push(n),t.push(new lt("timeCreated")),t.push(new lt("updated")),t.push(new lt("md5Hash",null,!0)),t.push(new lt("cacheControl",null,!0)),t.push(new lt("contentDisposition",null,!0)),t.push(new lt("contentEncoding",null,!0)),t.push(new lt("contentLanguage",null,!0)),t.push(new lt("contentType",null,!0)),t.push(new lt("metadata","customMetadata",!0)),ft=t}function yt(t,e,n){for(var r={type:"file"},o=n.length,i=0;i1e3)throw"Expected maxResults to be less than or equal to "+_t+"."}else{if(t!==wt)throw"Unknown option: "+t;if(p[wt]&&!G(p[wt]))throw"Expected pageToken to be string."}}var It=function(t,e,n,r){this.url=t,this.method=e,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]};function Nt(t){if(!t)throw w()}function At(t,e){return function(n,text){var r=mt(t,text,e);return Nt(null!==r),r}}function Dt(t){return function(e,text){var n=function(t,e){var n=ot(e);return null===n?null:St(t,n)}(t,text);return Nt(null!==n),n}}function kt(t,e){return function(n,text){var r=mt(t,text,e);return Nt(null!==r),function(t,e){var n=ot(e);if(null===n)return null;if(!G(n.downloadTokens))return null;var r=n.downloadTokens;if(0===r.length)return null;var o=encodeURIComponent;return r.split(",").map((function(e){var n=t.bucket,path=t.fullPath;return ut("/b/"+o(n)+"/o/"+o(path))+ct({alt:"media",token:e})}))[0]}(r,text)}}function Rt(t){return function(e,n){var r,path,o;return 401===e.getStatus()?r=new m(v.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(o=t.bucket,r=new m(v.QUOTA_EXCEEDED,"Quota for bucket '"+o+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(path=t.path,r=new m(v.UNAUTHORIZED,"User does not have permission to access '"+path+"'.")):r=n,r.setServerResponseProp(n.serverResponseProp()),r}}function Ot(t){var e=Rt(t);return function(n,r){var path,o=e(n,r);return 404===n.getStatus()&&(path=t.path,o=new m(v.OBJECT_NOT_FOUND,"Object '"+path+"' does not exist.")),o.setServerResponseProp(r.serverResponseProp()),o}}function Pt(t,e,n){var r=ut(e.fullServerUrl()),o=t.maxOperationRetryTime(),c=new It(r,"GET",At(t,n),o);return c.errorHandler=Ot(e),c}function xt(t,e,n,r,o){var c={};e.isRoot?c.prefix="":c.prefix=e.path+"/",n&&n.length>0&&(c.delimiter=n),r&&(c.pageToken=r),o&&(c.maxResults=o);var h=ut(e.bucketOnlyServerUrl()),l=t.maxOperationRetryTime(),f=new It(h,"GET",Dt(t),l);return f.urlParams=c,f.errorHandler=Rt(e),f}function Lt(t,e,n){var r=ut(e.fullServerUrl()),o=t.maxOperationRetryTime(),c=new It(r,"GET",kt(t,n),o);return c.errorHandler=Ot(e),c}function Mt(t,e,n,r){var o=ut(e.fullServerUrl()),body=gt(n,r),c=t.maxOperationRetryTime(),h=new It(o,"PATCH",At(t,r),c);return h.headers={"Content-Type":"application/json; charset=utf-8"},h.body=body,h.errorHandler=Ot(e),h}function Ft(t,e){var n=ut(e.fullServerUrl()),r=t.maxOperationRetryTime();var o=new It(n,"DELETE",(function(t,e){}),r);return o.successCodes=[200,204],o.errorHandler=Ot(e),o}function Ut(t,e,n){var r=Object.assign({},n);return r.fullPath=t.path,r.size=e.size(),r.contentType||(r.contentType=function(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}(null,e)),r}var qt=function(t,e,n,r){this.current=t,this.total=e,this.finalized=!!n,this.metadata=r||null};function Vt(t,e){var n=null;try{n=t.getResponseHeader("X-Goog-Upload-Status")}catch(t){Nt(!1)}return Nt(!!n&&-1!==(e||["active"]).indexOf(n)),n}function Bt(t,e,n,r,o,c,h,l){var f=new qt(0,0);if(h?(f.current=h.current,f.total=h.total):(f.current=0,f.total=r.size()),r.size()!==f.total)throw new m(v.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var d=f.total-f.current,y=d;o>0&&(y=Math.min(y,o));var _=f.current,w=_+y,E={"X-Goog-Upload-Command":y===d?"upload, finalize":"upload","X-Goog-Upload-Offset":f.current},body=r.slice(_,w);if(null===body)throw T();var S=e.maxUploadRetryTime(),C=new It(n,"POST",(function(t,text){var n,o=Vt(t,["active","final"]),h=f.current+y,l=r.size();return n="final"===o?At(e,c)(t,text):null,new qt(h,l,"final"===o,n)}),S);return C.headers=E,C.body=body.uploadData(),C.progressCallback=l||null,C.errorHandler=Rt(t),C}var jt=function(t,e,n){if(Q(t)||j(e)||j(n))this.next=t,this.error=e||null,this.complete=n||null;else{var r=t;this.next=r.next||null,this.error=r.error||null,this.complete=r.complete||null}},Wt=function(t,e,n,r,o,c){this.bytesTransferred=t,this.totalBytes=e,this.state=n,this.metadata=r,this.task=o,this.ref=c};function Qt(t,e,n){for(var r=e.length,o=e.length,i=0;i=0))throw"Expected a number 0 or greater."}))}function Jt(t,e){return new Kt((function(p){if(!(null===p||j(p)&&p instanceof Object))throw"Expected an Object.";null!=t&&t(p)}),e)}function $t(t){return new Kt((function(p){if(!(null===p||Q(p)))throw"Expected a Function."}),t)}function Zt(t){return function(){for(var e=[],n=0;n262144},t.prototype.start_=function(){this.state_===U.RUNNING&&null===this.request_&&(this.resumable_?null===this.uploadUrl_?this.createResumable_():this.needToFetchStatus_?this.fetchStatus_():this.needToFetchMetadata_?this.fetchMetadata_():this.continueUpload_():this.oneShotUpload_())},t.prototype.resolveToken_=function(t){var e=this;this.authWrapper_.getAuthToken().then((function(n){switch(e.state_){case U.RUNNING:t(n);break;case U.CANCELING:e.transition_(U.CANCELED);break;case U.PAUSING:e.transition_(U.PAUSED)}}))},t.prototype.createResumable_=function(){var t=this;this.resolveToken_((function(e){var n=function(t,e,n,r,o){var c=e.bucketOnlyServerUrl(),h=Ut(e,r,o),l={name:h.fullPath},f=ut(c),d={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":r.size(),"X-Goog-Upload-Header-Content-Type":h.contentType,"Content-Type":"application/json; charset=utf-8"},body=gt(h,n),y=t.maxUploadRetryTime(),m=new It(f,"POST",(function(t){var e;Vt(t);try{e=t.getResponseHeader("X-Goog-Upload-URL")}catch(t){Nt(!1)}return Nt(G(e)),e}),y);return m.urlParams=l,m.headers=d,m.body=body,m.errorHandler=Rt(e),m}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then((function(e){t.request_=null,t.uploadUrl_=e,t.needToFetchStatus_=!1,t.completeTransitions_()}),t.errorHandler_)}))},t.prototype.fetchStatus_=function(){var t=this,e=this.uploadUrl_;this.resolveToken_((function(n){var r=function(t,e,n,r){var o=t.maxUploadRetryTime(),c=new It(n,"POST",(function(t){var e=Vt(t,["active","final"]),n=null;try{n=t.getResponseHeader("X-Goog-Upload-Size-Received")}catch(t){Nt(!1)}n||Nt(!1);var o=Number(n);return Nt(!isNaN(o)),new qt(o,r.size(),"final"===e)}),o);return c.headers={"X-Goog-Upload-Command":"query"},c.errorHandler=Rt(e),c}(t.authWrapper_,t.location_,e,t.blob_),o=t.authWrapper_.makeRequest(r,n);t.request_=o,o.getPromise().then((function(e){e=e,t.request_=null,t.updateProgress_(e.current),t.needToFetchStatus_=!1,e.finalized&&(t.needToFetchMetadata_=!0),t.completeTransitions_()}),t.errorHandler_)}))},t.prototype.continueUpload_=function(){var t=this,e=262144*this.chunkMultiplier_,n=new qt(this.transferred_,this.blob_.size()),r=this.uploadUrl_;this.resolveToken_((function(o){var c;try{c=Bt(t.location_,t.authWrapper_,r,t.blob_,e,t.mappings_,n,t.makeProgressCallback_())}catch(e){return t.error_=e,void t.transition_(U.ERROR)}var h=t.authWrapper_.makeRequest(c,o);t.request_=h,h.getPromise().then((function(e){t.increaseMultiplier_(),t.request_=null,t.updateProgress_(e.current),e.finalized?(t.metadata_=e.metadata,t.transition_(U.SUCCESS)):t.completeTransitions_()}),t.errorHandler_)}))},t.prototype.increaseMultiplier_=function(){262144*this.chunkMultiplier_<33554432&&(this.chunkMultiplier_*=2)},t.prototype.fetchMetadata_=function(){var t=this;this.resolveToken_((function(e){var n=Pt(t.authWrapper_,t.location_,t.mappings_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then((function(e){t.request_=null,t.metadata_=e,t.transition_(U.SUCCESS)}),t.metadataErrorHandler_)}))},t.prototype.oneShotUpload_=function(){var t=this;this.resolveToken_((function(e){var n=function(t,e,n,r,o){var c=e.bucketOnlyServerUrl(),h={"X-Goog-Upload-Protocol":"multipart"},l=function(){for(var t="",i=0;i<2;i++)t+=Math.random().toString().slice(2);return t}();h["Content-Type"]="multipart/related; boundary="+l;var f=Ut(e,r,o),d="--"+l+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+gt(f,n)+"\r\n--"+l+"\r\nContent-Type: "+f.contentType+"\r\n\r\n",y="\r\n--"+l+"--",body=nt.getBlob(d,r,y);if(null===body)throw T();var m={name:f.fullPath},v=ut(c),_=t.maxUploadRetryTime(),w=new It(v,"POST",At(t,n),_);return w.urlParams=m,w.headers=h,w.body=body.uploadData(),w.errorHandler=Rt(e),w}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then((function(e){t.request_=null,t.metadata_=e,t.updateProgress_(t.blob_.size()),t.transition_(U.SUCCESS)}),t.errorHandler_)}))},t.prototype.updateProgress_=function(t){var e=this.transferred_;this.transferred_=t,this.transferred_!==e&&this.notifyObservers_()},t.prototype.transition_=function(t){if(this.state_!==t)switch(t){case U.CANCELING:case U.PAUSING:this.state_=t,null!==this.request_&&this.request_.cancel();break;case U.RUNNING:var e=this.state_===U.PAUSED;this.state_=t,e&&(this.notifyObservers_(),this.start_());break;case U.PAUSED:this.state_=t,this.notifyObservers_();break;case U.CANCELED:this.error_=E(),this.state_=t,this.notifyObservers_();break;case U.ERROR:case U.SUCCESS:this.state_=t,this.notifyObservers_()}},t.prototype.completeTransitions_=function(){switch(this.state_){case U.PAUSING:this.transition_(U.PAUSED);break;case U.CANCELING:this.transition_(U.CANCELED);break;case U.RUNNING:this.start_()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=B(this.state_);return new Wt(this.transferred_,this.blob_.size(),t,this.metadata_,this,this.ref_)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(){if(t!==F.STATE_CHANGED)throw"Expected one of the event types: ["+F.STATE_CHANGED+"]."}var c="Expected a function or an Object with one of `next`, `error`, `complete` properties.",h=$t(!0).validator,l=Jt(null,!0).validator;function f(p){try{return void h(p)}catch(t){}try{if(l(p),!(W(p.next)||W(p.error)||W(p.complete)))throw"";return}catch(t){throw c}}var d=[Ht(o),Jt(f,!0),$t(!0),$t(!0)];Qt("on",d,arguments);var y=this;function m(t){return function(e,n,o){null!==t&&Qt("on",t,arguments);var c=new jt(e,n,r);return y.addObserver_(c),function(){y.removeObserver_(c)}}}function v(p){if(null===p)throw c;f(p)}var _=[Jt(v),$t(!0),$t(!0)],w=!(W(e)||W(n)||W(r));return w?m(_):m(null)(e,n,r)},t.prototype.then=function(t,e){return this.promise_.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.addObserver_=function(t){this.observers_.push(t),this.notifyObserver_(t)},t.prototype.removeObserver_=function(t){var i=this.observers_.indexOf(t);-1!==i&&this.observers_.splice(i,1)},t.prototype.notifyObservers_=function(){var t=this;this.finishPromise_(),this.observers_.slice().forEach((function(e){t.notifyObserver_(e)}))},t.prototype.finishPromise_=function(){if(null!==this.resolve_){var t=!0;switch(B(this.state_)){case V.SUCCESS:Zt(this.resolve_.bind(null,this.snapshot))();break;case V.CANCELED:case V.ERROR:Zt(this.reject_.bind(null,this.error_))();break;default:t=!1}t&&(this.resolve_=null,this.reject_=null)}},t.prototype.notifyObserver_=function(t){switch(B(this.state_)){case V.RUNNING:case V.PAUSED:t.next&&Zt(t.next.bind(t,this.snapshot))();break;case V.SUCCESS:t.complete&&Zt(t.complete.bind(t))();break;case V.CANCELED:case V.ERROR:t.error&&Zt(t.error.bind(t,this.error_))();break;default:t.error&&Zt(t.error.bind(t,this.error_))()}},t.prototype.resume=function(){Qt("resume",[],arguments);var t=this.state_===U.PAUSED||this.state_===U.PAUSING;return t&&this.transition_(U.RUNNING),t},t.prototype.pause=function(){Qt("pause",[],arguments);var t=this.state_===U.RUNNING;return t&&this.transition_(U.PAUSING),t},t.prototype.cancel=function(){Qt("cancel",[],arguments);var t=this.state_===U.RUNNING||this.state_===U.PAUSING;return t&&this.transition_(U.CANCELING),t},t}(),ee=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof it?e:it.makeFromUrl(e)}return t.prototype.toString=function(){return Qt("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return pt()},t.prototype.child=function(t){Qt("child",[Ht()],arguments);var e=at(this.location.path,t),n=new it(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=function(path){if(0===path.length)return null;var t=path.lastIndexOf("/");return-1===t?"":path.slice(0,t)}(this.location.path);if(null===t)return null;var e=new it(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new it(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return st(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(data,t){return void 0===t&&(t=null),Qt("put",[Gt(),zt(!0)],arguments),this.throwIfRoot_("put"),new te(this,this.authWrapper,this.location,this.mappings(),new nt(data),t)},t.prototype.putString=function(t,e,n){void 0===e&&(e=D.RAW),Qt("putString",[Ht(),Ht(k,!0),zt(!0)],arguments),this.throwIfRoot_("putString");var data=O(e,t),r=Object.assign({},n);return!j(r.contentType)&&j(data.contentType)&&(r.contentType=data.contentType),new te(this,this.authWrapper,this.location,this.mappings(),new nt(data.data,!0),r)},t.prototype.delete=function(){var t=this;return Qt("delete",[],arguments),this.throwIfRoot_("delete"),this.authWrapper.getAuthToken().then((function(e){var n=Ft(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()}))},t.prototype.listAll=function(){Qt("listAll",[],arguments);var t={prefixes:[],items:[]};return this.listAllHelper(t).then((function(){return t}))},t.prototype.listAllHelper=function(t,e){return Object(c.__awaiter)(this,void 0,void 0,(function(){var n,r,o,h;return Object(c.__generator)(this,(function(c){switch(c.label){case 0:return n={pageToken:e},[4,this.list(n)];case 1:return r=c.sent(),(o=t.prefixes).push.apply(o,r.prefixes),(h=t.items).push.apply(h,r.items),null==r.nextPageToken?[3,3]:[4,this.listAllHelper(t,r.nextPageToken)];case 2:c.sent(),c.label=3;case 3:return[2]}}))}))},t.prototype.list=function(t){Qt("list",[Yt(!0)],arguments);var e=this;return this.authWrapper.getAuthToken().then((function(n){var r=t||{},o=xt(e.authWrapper,e.location,"/",r.pageToken,r.maxResults);return e.authWrapper.makeRequest(o,n).getPromise()}))},t.prototype.getMetadata=function(){var t=this;return Qt("getMetadata",[],arguments),this.throwIfRoot_("getMetadata"),this.authWrapper.getAuthToken().then((function(e){var n=Pt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()}))},t.prototype.updateMetadata=function(t){var e=this;return Qt("updateMetadata",[zt()],arguments),this.throwIfRoot_("updateMetadata"),this.authWrapper.getAuthToken().then((function(n){var r=Mt(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()}))},t.prototype.getDownloadURL=function(){var t=this;return Qt("getDownloadURL",[],arguments),this.throwIfRoot_("getDownloadURL"),this.authWrapper.getAuthToken().then((function(e){var n=Lt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise().then((function(t){if(null===t)throw S();return t}))}))},t.prototype.throwIfRoot_=function(t){if(""===this.location.path)throw function(t){return new m(v.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}(t)},t}(),ne=function(){function t(t){this.promise_=Promise.reject(t)}return t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){},t}(),re=function(){function t(){this.map=new Map,this.id=y}return t.prototype.addRequest=function(t){var e=this,n=this.id;this.id++,this.map.set(n,t),t.getPromise().then((function(){return e.map.delete(n)}),(function(){return e.map.delete(n)}))},t.prototype.clear=function(){this.map.forEach((function(t){t&&t.cancel(!0)})),this.map.clear()},t}(),ie=function(){function t(e,n,r,o,c){if(this.bucket_=null,this.deleted_=!1,this.app_=e,null!==this.app_){var h=this.app_.options;j(h)&&(this.bucket_=t.extractBucket_(h))}this.storageRefMaker_=n,this.requestMaker_=r,this.pool_=c,this.service_=o,this.maxOperationRetryTime_=f,this.maxUploadRetryTime_=d,this.requestMap_=new re}return t.extractBucket_=function(t){var e=t[l]||null;return null==e?null:it.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.app_&&j(this.app_.INTERNAL)&&j(this.app_.INTERNAL.getToken)?this.app_.INTERNAL.getToken().then((function(t){return null!==t?t.accessToken:null}),(function(){return null})):Promise.resolve(null)},t.prototype.bucket=function(){if(this.deleted_)throw I();return this.bucket_},t.prototype.service=function(){return this.service_},t.prototype.makeStorageReference=function(t){return this.storageRefMaker_(this,t)},t.prototype.makeRequest=function(t,e){if(this.deleted_)return new ne(I());var n=this.requestMaker_(t,e,this.pool_);return this.requestMap_.addRequest(n),n},t.prototype.deleteApp=function(){this.deleted_=!0,this.app_=null,this.requestMap_.clear()},t.prototype.maxUploadRetryTime=function(){return this.maxUploadRetryTime_},t.prototype.setMaxUploadRetryTime=function(time){this.maxUploadRetryTime_=time},t.prototype.maxOperationRetryTime=function(){return this.maxOperationRetryTime_},t.prototype.setMaxOperationRetryTime=function(time){this.maxOperationRetryTime_=time},t}();var oe=function(){function t(t,e,n,body,r,o,c,h,l,f,d){var y=this;this.pendingXhr_=null,this.backoffId_=null,this.resolve_=null,this.reject_=null,this.canceled_=!1,this.appDelete_=!1,this.url_=t,this.method_=e,this.headers_=n,this.body_=body,this.successCodes_=r.slice(),this.additionalRetryCodes_=o.slice(),this.callback_=c,this.errorCallback_=h,this.progressCallback_=f,this.timeout_=l,this.pool_=d,this.promise_=new Promise((function(t,e){y.resolve_=t,y.reject_=e,y.start_()}))}return t.prototype.start_=function(){var t=this;function e(e,n){var r,o=t.resolve_,c=t.reject_,h=n.xhr;if(n.wasSuccessCode)try{var l=t.callback_(h,h.getResponseText());W(l)?o(l):o()}catch(t){c(t)}else null!==h?((r=w()).setServerResponseProp(h.getResponseText()),t.errorCallback_?c(t.errorCallback_(h,r)):c(r)):n.canceled?c(r=t.appDelete_?I():E()):c(r=new m(v.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again."))}this.canceled_?e(0,new ae(!1,null,!0)):this.backoffId_=function(t,e,n){var r=1,o=null,c=!1,h=0;function l(){return 2===h}var f=!1;function d(){for(var t=[],n=0;n=500&&t<600,n=-1!==[408,429].indexOf(t),r=-1!==this.additionalRetryCodes_.indexOf(t);return e||n||r},t}(),ae=function(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n};function se(t,e,n){var r=ct(t.urlParams),c=t.url+r,h=Object.assign({},t.headers);return function(t,e){null!==e&&e.length>0&&(t.Authorization="Firebase "+e)}(h,e),function(t){var e=void 0!==o.a?o.a.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}(h),new oe(c,t.method,h,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}var ue,ce,he=function(){function t(t,e,n){if(this.bucket_=null,this.authWrapper_=new ie(t,(function(t,e){return new ee(t,e)}),se,this,e),this.app_=t,null!=n)this.bucket_=it.makeFromBucketSpec(n);else{var r=this.authWrapper_.bucket();null!=r&&(this.bucket_=new it(r,""))}this.internals_=new le(this)}return t.prototype.ref=function(path){function t(path){if("string"!=typeof path)throw"Path is not a string.";if(/^[A-Za-z]+:\/\//.test(path))throw"Expected child path but got a URL, use refFromURL instead."}if(Qt("ref",[Ht(t,!0)],arguments),null==this.bucket_)throw new Error("No Storage Bucket defined in Firebase Options.");var e=new ee(this.authWrapper_,this.bucket_);return null!=path?e.child(path):e},t.prototype.refFromURL=function(t){function e(p){if("string"!=typeof p)throw"Path is not a string.";if(!/^[A-Za-z]+:\/\//.test(p))throw"Expected full URL but got a child path, use ref instead.";try{it.makeFromUrl(p)}catch(t){throw"Expected valid full URL but got an invalid one."}}return Qt("refFromURL",[Ht(e,!1)],arguments),new ee(this.authWrapper_,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.authWrapper_.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(time){Qt("setMaxUploadRetryTime",[Xt()],arguments),this.authWrapper_.setMaxUploadRetryTime(time)},t.prototype.setMaxOperationRetryTime=function(time){Qt("setMaxOperationRetryTime",[Xt()],arguments),this.authWrapper_.setMaxOperationRetryTime(time)},Object.defineProperty(t.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.internals_},enumerable:!0,configurable:!0}),t}(),le=function(){function t(t){this.service_=t}return t.prototype.delete=function(){return this.service_.authWrapper_.deleteApp(),Promise.resolve()},t}(),fe="storage";function pe(t,e,n){return new he(t,new Z,n)}ue=o.a,ce={TaskState:V,TaskEvent:F,StringFormat:D,Storage:he,Reference:ee},ue.INTERNAL.registerService(fe,pe,ce,void 0,!0)},24:function(t,e,n){"use strict";var r,o=(r=n(0))&&"object"==typeof r&&"default"in r?r.default:r;t.exports=o},3:function(t,e,n){"use strict";function r(t,e,n,r,o,c,h){try{var l=t[c](h),f=l.value}catch(t){return void n(t)}l.done?e(f):Promise.resolve(f).then(r,o)}function o(t){return function(){var e=this,n=arguments;return new Promise((function(o,c){var h=t.apply(e,n);function l(t){r(h,o,c,l,f,"next",t)}function f(t){r(h,o,c,l,f,"throw",t)}l(void 0)}))}}n.d(e,"a",(function(){return o}))},32:function(t,e,n){"use strict";n.r(e),n.d(e,"__extends",(function(){return o})),n.d(e,"__assign",(function(){return c})),n.d(e,"__rest",(function(){return h})),n.d(e,"__decorate",(function(){return l})),n.d(e,"__param",(function(){return f})),n.d(e,"__metadata",(function(){return d})),n.d(e,"__awaiter",(function(){return y})),n.d(e,"__generator",(function(){return m})),n.d(e,"__exportStar",(function(){return v})),n.d(e,"__values",(function(){return _})),n.d(e,"__read",(function(){return w})),n.d(e,"__spread",(function(){return E})),n.d(e,"__spreadArrays",(function(){return T})),n.d(e,"__await",(function(){return S})),n.d(e,"__asyncGenerator",(function(){return C})),n.d(e,"__asyncDelegator",(function(){return I})),n.d(e,"__asyncValues",(function(){return N})),n.d(e,"__makeTemplateObject",(function(){return A})),n.d(e,"__importStar",(function(){return D})),n.d(e,"__importDefault",(function(){return k}));var r=function(t,b){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,b){t.__proto__=b}||function(t,b){for(var p in b)b.hasOwnProperty(p)&&(t[p]=b[p])})(t,b)};function o(t,b){function e(){this.constructor=t}r(t,b),t.prototype=null===b?Object.create(b):(e.prototype=b.prototype,new e)}var c=function(){return(c=Object.assign||function(t){for(var s,i=1,e=arguments.length;i=0;i--)(r=t[i])&&(c=(o<3?r(c):o>3?r(e,n,c):r(e,n))||c);return o>3&&c&&Object.defineProperty(e,n,c),c}function f(t,e){return function(n,r){e(n,r,t)}}function d(t,e){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function y(t,e,n,r){return new(n||(n=Promise))((function(o,c){function h(t){try{f(r.next(t))}catch(t){c(t)}}function l(t){try{f(r.throw(t))}catch(t){c(t)}}function f(t){t.done?o(t.value):new n((function(e){e(t.value)})).then(h,l)}f((r=r.apply(t,e||[])).next())}))}function m(t,body){var e,n,r,g,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return g={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function c(c){return function(h){return function(c){if(e)throw new TypeError("Generator is already executing.");for(;o;)try{if(e=1,n&&(r=2&c[0]?n.return:c[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,c[1])).done)return r;switch(n=0,r&&(c=[2&c[0],r.value]),c[0]){case 0:case 1:r=c;break;case 4:return o.label++,{value:c[1],done:!1};case 5:o.label++,n=c[1],c=[0];continue;case 7:c=o.ops.pop(),o.trys.pop();continue;default:if(!(r=(r=o.trys).length>0&&r[r.length-1])&&(6===c[0]||2===c[0])){o=0;continue}if(3===c[0]&&(!r||c[1]>r[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}}}function w(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),c=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)c.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return c}function E(){for(var t=[],i=0;i1||o(t,e)}))})}function o(t,e){try{(n=g[t](e)).value instanceof S?Promise.resolve(n.value.v).then(c,h):l(q[0][2],n)}catch(t){l(q[0][3],t)}var n}function c(t){o("next",t)}function h(t){o("throw",t)}function l(t,e){t(e),q.shift(),q.length&&o(q[0][0],q[0][1])}}function I(t){var i,p;return i={},e("next"),e("throw",(function(t){throw t})),e("return"),i[Symbol.iterator]=function(){return this},i;function e(e,n){i[e]=t[e]?function(r){return(p=!p)?{value:S(t[e](r)),done:"return"===e}:n?n(r):r}:n}}function N(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,e=t[Symbol.asyncIterator];return e?e.call(t):(t=_(t),i={},n("next"),n("throw"),n("return"),i[Symbol.asyncIterator]=function(){return this},i);function n(e){i[e]=t[e]&&function(n){return new Promise((function(r,o){(function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)})(r,o,(n=t[e](n)).done,n.value)}))}}}function A(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function D(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function k(t){return t&&t.__esModule?t:{default:t}}},34:function(t,e,n){"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var content=function(t,e){var content=t[1]||"",n=t[3];if(!n)return content;if(e&&"function"==typeof btoa){var r=(c=n,h=btoa(unescape(encodeURIComponent(JSON.stringify(c)))),data="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(h),"/*# ".concat(data," */")),o=n.sources.map((function(source){return"/*# sourceURL=".concat(n.sourceRoot).concat(source," */")}));return[content].concat(o).concat([r]).join("\n")}var c,h,data;return[content].join("\n")}(e,t);return e[2]?"@media ".concat(e[2],"{").concat(content,"}"):content})).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;ie.parts.length&&(n.parts.length=e.parts.length)}else{var o=[];for(r=0;r0?h.map((function(){return t(!1)})):t(!1))}};t.exports=r},51:function(t,e,n){"use strict";function r(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,i){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)){var e=[],n=!0,r=!1,o=void 0;try{for(var c,h=t[Symbol.iterator]();!(n=(c=h.next()).done)&&(e.push(c.value),!i||e.length!==i);n=!0);}catch(t){r=!0,o=t}finally{try{n||null==h.return||h.return()}finally{if(r)throw o}}return e}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}n.d(e,"a",(function(){return r}))},87:function(t,e,n){"use strict";(function(t){Object.defineProperty(e,"__esModule",{value:!0});var r=n(32),o={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},c=function(t,e){if(!t)throw h(e)},h=function(t){return new Error("Firebase Database ("+o.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)},l=function(t){for(var e=[],p=0,i=0;i>6|192,e[p++]=63&n|128):55296==(64512&n)&&i+1>18|240,e[p++]=n>>12&63|128,e[p++]=n>>6&63|128,e[p++]=63&n|128):(e[p++]=n>>12|224,e[p++]=n>>6&63|128,e[p++]=63&n|128)}return e},f={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray:function(input,t){if(!Array.isArray(input))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var e=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,output=[],i=0;i>2,f=(3&n)<<4|o>>4,d=(15&o)<<2|h>>6,y=63&h;c||(y=64,r||(d=64)),output.push(e[l],e[f],e[d],e[y])}return output.join("")},encodeString:function(input,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(input):this.encodeByteArray(l(input),t)},decodeString:function(input,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(input):function(t){for(var e=[],n=0,r=0;n191&&o<224){var c=t[n++];e[r++]=String.fromCharCode((31&o)<<6|63&c)}else if(o>239&&o<365){var u=((7&o)<<18|(63&(c=t[n++]))<<12|(63&(h=t[n++]))<<6|63&t[n++])-65536;e[r++]=String.fromCharCode(55296+(u>>10)),e[r++]=String.fromCharCode(56320+(1023&u))}else{c=t[n++];var h=t[n++];e[r++]=String.fromCharCode((15&o)<<12|(63&c)<<6|63&h)}}return e.join("")}(this.decodeStringToByteArray(input,t))},decodeStringToByteArray:function(input,t){this.init_();for(var e=t?this.charToByteMapWebSafe_:this.charToByteMap_,output=[],i=0;i>4;if(output.push(h),64!==o){var l=r<<4&240|o>>2;if(output.push(l),64!==c){var f=o<<6&192|c;output.push(f)}}}return output},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var i=0;i=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)]=i,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)]=i)}}},d=function(t){try{return f.decodeString(t,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};function y(t,source){if(!(source instanceof Object))return source;switch(source.constructor){case Date:return new Date(source.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return source}for(var e in source)source.hasOwnProperty(e)&&(t[e]=y(t[e],source[e]));return t}var m=function(){function t(){var t=this;this.reject=function(){},this.resolve=function(){},this.promise=new Promise((function(e,n){t.resolve=e,t.reject=n}))}return t.prototype.wrapCallback=function(t){var e=this;return function(n,r){n?e.reject(n):e.resolve(r),"function"==typeof t&&(e.promise.catch((function(){})),1===t.length?t(n):t(n,r))}},t}();function v(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}var _="FirebaseError",w=function(t){function e(code,n){var r=t.call(this,n)||this;return r.code=code,r.name=_,Object.setPrototypeOf(r,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(r,E.prototype.create),r}return r.__extends(e,t),e}(Error),E=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n}return t.prototype.create=function(code){for(var data=[],t=1;t"}))}var S=/\{\$([^}]+)}/g;function C(t){return JSON.parse(t)}var I=function(t){var header={},e={},data={},n="";try{var r=t.split(".");header=C(d(r[0])||""),e=C(d(r[1])||""),n=r[2],data=e.d||{},delete e.d}catch(t){}return{header:header,claims:e,data:data,signature:n}};var N=function(){function t(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(var i=1;i>>31)}var o,c,a=this.chain_[0],b=this.chain_[1],h=this.chain_[2],l=this.chain_[3],f=this.chain_[4];for(i=0;i<80;i++){i<40?i<20?(o=l^b&(h^l),c=1518500249):(o=b^h^l,c=1859775393):i<60?(o=b&h|l&(b|h),c=2400959708):(o=b^h^l,c=3395469782);r=(a<<5|a>>>27)+o+f+c+n[i]&4294967295;f=l,l=h,h=4294967295&(b<<30|b>>>2),b=a,a=r}this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+b&4294967295,this.chain_[2]=this.chain_[2]+h&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+f&4294967295},t.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,o=this.buf_,c=this.inbuf_;r=56;i--)this.buf_[i]=255&e,e/=256;this.compress_(this.buf_);var n=0;for(i=0;i<5;i++)for(var r=24;r>=0;r-=8)t[n]=this.chain_[i]>>r&255,++n;return t},t}();var A=function(){function t(t,e){var n=this;this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then((function(){t(n)})).catch((function(t){n.error(t)}))}return t.prototype.next=function(t){this.forEachObserver((function(e){e.next(t)}))},t.prototype.error=function(t){this.forEachObserver((function(e){e.error(t)})),this.close(t)},t.prototype.complete=function(){this.forEachObserver((function(t){t.complete()})),this.close()},t.prototype.subscribe=function(t,e,n){var r,o=this;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");void 0===(r=function(t,e){if("object"!=typeof t||null===t)return!1;for(var n=0,r=e;n 4. Need to update it?")}var o=t+" failed: ";return o+=r+" argument "}e.CONSTANTS=o,e.Deferred=m,e.ErrorFactory=E,e.FirebaseError=w,e.Sha1=N,e.assert=c,e.assertionError=h,e.async=function(t,e){return function(){for(var n=[],r=0;r=r&&n<=o},e.issuedAtTime=function(t){var e=I(t).claims;return"object"==typeof e&&e.hasOwnProperty("iat")?e.iat:null},e.jsonEval=C,e.map=function(t,e,n){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=e.call(n,t[o],o,t));return r},e.querystring=function(t){for(var e=[],n=function(t,n){Array.isArray(n)?n.forEach((function(n){e.push(encodeURIComponent(t)+"="+encodeURIComponent(n))})):e.push(encodeURIComponent(t)+"="+encodeURIComponent(n))},r=0,o=Object.entries(t);r=55296&&e<=56319?(p+=4,i++):p+=3}return p},e.stringToByteArray=function(t){for(var e=[],p=0,i=0;i=55296&&n<=56319){var r=n-55296;c(++i>6|192,e[p++]=63&n|128):n<65536?(e[p++]=n>>12|224,e[p++]=n>>6&63|128,e[p++]=63&n|128):(e[p++]=n>>18|240,e[p++]=n>>12&63|128,e[p++]=n>>6&63|128,e[p++]=63&n|128)}return e},e.stringify=function(data){return JSON.stringify(data)},e.validateArgCount=function(t,e,n,r){var o;if(rn&&(o=0===n?"none":"no more than "+n),o)throw new Error(t+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+o+".")},e.validateCallback=function(t,e,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(k(t,e,r)+"must be a valid function.")},e.validateContextObject=function(t,e,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(k(t,e,r)+"must be a valid context object.")},e.validateNamespace=function(t,e,n,r){if((!r||n)&&"string"!=typeof n)throw new Error(k(t,e,r)+"must be a valid firebase namespace.")}}).call(this,n(17))},88:function(t,e,n){"use strict";n.r(e),n.d(e,"LogLevel",(function(){return r})),n.d(e,"Logger",(function(){return l})),n.d(e,"setLogLevel",(function(){return f}));var r,o=[];!function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(r||(r={}));var c=r.INFO,h=function(t,e){for(var n=[],o=2;o0?h.map((function(){return t(!1)})):t(!1))}};t.exports=r}}]);