firebase 9.6.11 → 9.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.esm.js +1 -1
  4. package/app/dist/index.mjs +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.esm.js +1 -1
  7. package/compat/app/dist/index.mjs +1 -1
  8. package/compat/dist/index.esm.js +2 -2
  9. package/compat/dist/index.node.cjs +2 -2
  10. package/compat/dist/index.rn.cjs.js +2 -2
  11. package/firebase-analytics.js +3 -3
  12. package/firebase-app-check-compat.js +2 -2
  13. package/firebase-app-check-compat.js.map +1 -1
  14. package/firebase-app-check.js +9 -9
  15. package/firebase-app-check.js.map +1 -1
  16. package/firebase-app-compat.js +2 -2
  17. package/firebase-app-compat.js.map +1 -1
  18. package/firebase-app.js +9 -9
  19. package/firebase-auth-cordova.js +1 -1
  20. package/firebase-auth-react-native.js +1 -1
  21. package/firebase-auth.js +2 -2
  22. package/firebase-compat.js +4 -4
  23. package/firebase-compat.js.map +1 -1
  24. package/firebase-database.js +4 -4
  25. package/firebase-firestore-compat.js +1 -1
  26. package/firebase-firestore-compat.js.map +1 -1
  27. package/firebase-firestore-lite.js +127 -121
  28. package/firebase-firestore-lite.js.map +1 -1
  29. package/firebase-firestore.js +4115 -4023
  30. package/firebase-firestore.js.map +1 -1
  31. package/firebase-functions-compat.js +1 -1
  32. package/firebase-functions-compat.js.map +1 -1
  33. package/firebase-functions.js +31 -5
  34. package/firebase-functions.js.map +1 -1
  35. package/firebase-messaging-sw.js +1 -1
  36. package/firebase-messaging.js +1 -1
  37. package/firebase-performance-standalone-compat.es2017.js +5 -5
  38. package/firebase-performance-standalone-compat.es2017.js.map +1 -1
  39. package/firebase-performance-standalone-compat.js +1 -1
  40. package/firebase-performance-standalone-compat.js.map +1 -1
  41. package/firebase-performance.js +3 -3
  42. package/firebase-remote-config.js +2 -2
  43. package/firebase-storage.js +1 -1
  44. package/package.json +7 -7
@@ -1,10 +1,10 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";!function(e){var t,n,o,r,i,s,a,c,l,u;function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function d(e){return e="string"!=typeof e?String(e):e}function f(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function p(t){this.map={},t instanceof p?t.forEach(function(e,t){this.append(t,e)},this):Array.isArray(t)?t.forEach(function(e){this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function g(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function m(n){return new Promise(function(e,t){n.onload=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function v(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function _(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e)if("string"==typeof e)this._bodyText=e;else if(o&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(r&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(i&&o&&a(e))this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!i||!ArrayBuffer.prototype.isPrototypeOf(e)&&!c(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=y(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=g(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(v)}),this.text=function(){var e,t,n=g(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}function w(e,t){var n,r=(t=t||{}).body;if(e instanceof w){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,r||null==e._bodyInit||(r=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"omit",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(e=t.method||this.method||"GET",n=e.toUpperCase(),-1<l.indexOf(n)?n:e),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function b(e){var r=new FormData;return e.trim().split("&").forEach(function(e){var t,n;e&&(t=(n=e.split("=")).shift().replace(/\+/g," "),n=n.join("=").replace(/\+/g," "),r.append(decodeURIComponent(t),decodeURIComponent(n)))}),r}function I(e,t){t=t||{},this.type="default",this.status=void 0===t.status?200:t.status,this.ok=200<=this.status&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}e.fetch||(t="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,o="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),r="FormData"in e,(i="ArrayBuffer"in e)&&(s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=function(e){return e&&DataView.prototype.isPrototypeOf(e)},c=ArrayBuffer.isView||function(e){return e&&-1<s.indexOf(Object.prototype.toString.call(e))}),p.prototype.append=function(e,t){e=h(e),t=d(t);var n=this.map[e];this.map[e]=n?n+","+t:t},p.prototype.delete=function(e){delete this.map[h(e)]},p.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},p.prototype.set=function(e,t){this.map[h(e)]=d(t)},p.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},p.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),f(n)},p.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),f(t)},p.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),f(n)},n&&(p.prototype[Symbol.iterator]=p.prototype.entries),l=["DELETE","GET","HEAD","OPTIONS","POST","PUT"],w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},_.call(w.prototype),_.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},I.error=function(){var e=new I(null,{status:0,statusText:""});return e.type="error",e},u=[301,302,303,307,308],I.redirect=function(e,t){if(-1===u.indexOf(t))throw new RangeError("Invalid status code");return new I(null,{status:t,headers:{location:e}})},e.Headers=p,e.Request=w,e.Response=I,e.fetch=function(n,r){return new Promise(function(i,e){var t=new w(n,r),s=new XMLHttpRequest;s.onload=function(){var e,r,t={status:s.status,statusText:s.statusText,headers:(e=s.getAllResponseHeaders()||"",r=new p,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var t=e.split(":"),n=t.shift().trim();n&&(t=t.join(":").trim(),r.append(n,t))}),r)};t.url="responseURL"in s?s.responseURL:t.headers.get("X-Request-URL");var n="response"in s?s.response:s.responseText;i(new I(n,t))},s.onerror=function(){e(new TypeError("Network request failed"))},s.ontimeout=function(){e(new TypeError("Network request failed"))},s.open(t.method,t.url,!0),"include"===t.credentials?s.withCredentials=!0:"omit"===t.credentials&&(s.withCredentials=!1),"responseType"in s&&o&&(s.responseType="blob"),t.headers.forEach(function(e,t){s.setRequestHeader(t,e)}),s.send(void 0===t._bodyInit?null:t._bodyInit)})},e.fetch.polyfill=!0)}("undefined"!=typeof self?self:void 0);function e(e){try{return!!e()}catch(e){return!0}}function t(e){if(!g(e))throw TypeError(String(e)+" is not an object");return e}var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r=function(e){return e&&e.Math==Math&&e},i=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n&&n)||Function("return this")(),s={exports:{}},o=!e(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}),a={},c=function(e){return"object"==typeof e?null!==e:"function"==typeof e},l=c,u=i.document,h=l(u)&&l(u.createElement),d=function(e){return h?u.createElement(e):{}},f=d,p=!o&&!e(function(){return 7!=Object.defineProperty(f("div"),"a",{get:function(){return 7}}).a}),g=c,m=c,v=function(e,t){if(!m(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!m(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!m(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!m(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")},y=p,_=t,w=v,b=Object.defineProperty;a.f=o?b:function(e,t,n){if(_(e),t=w(t,!0),_(n),y)try{return b(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var I=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},T=a,E=I,S=o?function(e,t,n){return T.f(e,t,E(1,n))}:function(e,t,n){return e[t]=n,e},k=i,C=S,A=function(t,n){try{C(k,t,n)}catch(e){k[t]=n}return n},N=A,R="__core-js_shared__",x=i[R]||N(R,{}),P=x;(s.exports=function(e,t){return P[e]||(P[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"});function D(e,t){return M.call(e,t)}function O(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++L+F).toString(36)}var M={}.hasOwnProperty,L=0,F=Math.random(),U=e,q=!!Object.getOwnPropertySymbols&&!U(function(){return!String(Symbol())}),j=q&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,V=i,B=s.exports,K=D,$=O,W=q,z=j,G=B("wks"),H=V.Symbol,Q=z?H:H&&H.withoutSetter||$,Y=function(e){return K(G,e)||(W&&K(H,e)?G[e]=H[e]:G[e]=Q("Symbol."+e)),G[e]},J={};J[Y("toStringTag")]="z";var X="[object z]"===String(J),Z={exports:{}},ee=x,te=Function.toString;"function"!=typeof ee.inspectSource&&(ee.inspectSource=function(e){return te.call(e)});var ne,re,ie,se,oe,ae,ce,le,ue=ee.inspectSource,he=ue,de=i.WeakMap,fe="function"==typeof de&&/native code/.test(he(de)),pe=s.exports,ge=O,me=pe("keys"),ve=function(e){return me[e]||(me[e]=ge(e))},ye={},_e=c,we=S,be=D,Ie=ve,Te=ye,Ee=i.WeakMap;ce=fe?(ne=new Ee,re=ne.get,ie=ne.has,se=ne.set,oe=function(e,t){return se.call(ne,e,t),t},ae=function(e){return re.call(ne,e)||{}},function(e){return ie.call(ne,e)}):(Te[le=Ie("state")]=!0,oe=function(e,t){return we(e,le,t),t},ae=function(e){return be(e,le)?e[le]:{}},function(e){return be(e,le)});var Se={set:oe,get:ae,has:ce,enforce:function(e){return ce(e)?ae(e):oe(e,{})},getterFor:function(n){return function(e){var t;if(!_e(e)||(t=ae(e)).type!==n)throw TypeError("Incompatible receiver, "+n+" required");return t}}},ke=i,Ce=S,Ae=D,Ne=A,Re=ue,xe=Se.get,Pe=Se.enforce,De=String(String).split("String");(Z.exports=function(e,t,n,r){var i=!!r&&!!r.unsafe,s=!!r&&!!r.enumerable,o=!!r&&!!r.noTargetGet;"function"==typeof n&&("string"!=typeof t||Ae(n,"name")||Ce(n,"name",t),Pe(n).source=De.join("string"==typeof t?t:"")),e!==ke?(i?!o&&e[t]&&(s=!0):delete e[t],s?e[t]=n:Ce(e,t,n)):s?e[t]=n:Ne(t,n)})(Function.prototype,"toString",function(){return"function"==typeof this&&xe(this).source||Re(this)});var Oe={}.toString,Me=function(e){return Oe.call(e).slice(8,-1)},Le=X,Fe=Me,Ue=Y("toStringTag"),qe="Arguments"==Fe(function(){return arguments}()),je=Le?Fe:function(e){var t,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),Ue))?n:qe?Fe(t):"Object"==(n=Fe(t))&&"function"==typeof t.callee?"Arguments":n},Ve=je,Be=Z.exports;X||Be(Object.prototype,"toString",X?{}.toString:function(){return"[object "+Ve(this)+"]"},{unsafe:!0});var Ke=Math.ceil,$e=Math.floor,We=function(e){return isNaN(e=+e)?0:(0<e?$e:Ke)(e)},ze=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e},Ge=We,He=ze,Qe=function(a){return function(e,t){var n,r,i=String(He(e)),s=Ge(t),o=i.length;return s<0||o<=s?a?"":void 0:(n=i.charCodeAt(s))<55296||56319<n||s+1===o||(r=i.charCodeAt(s+1))<56320||57343<r?a?i.charAt(s):n:a?i.slice(s,s+2):r-56320+(n-55296<<10)+65536}},Ye={codeAt:Qe(!1),charAt:Qe(!0)},Je={},Xe={},Ze={}.propertyIsEnumerable,et=Object.getOwnPropertyDescriptor,tt=et&&!Ze.call({1:2},1);Xe.f=tt?function(e){var t=et(this,e);return!!t&&t.enumerable}:Ze;function nt(e){return at(ct(e))}var rt=e,it=Me,st="".split,ot=rt(function(){return!Object("z").propertyIsEnumerable(0)})?function(e){return"String"==it(e)?st.call(e,""):Object(e)}:Object,at=ot,ct=ze,lt=Xe,ut=I,ht=nt,dt=v,ft=D,pt=p,gt=Object.getOwnPropertyDescriptor;Je.f=o?gt:function(e,t){if(e=ht(e),t=dt(t,!0),pt)try{return gt(e,t)}catch(e){}if(ft(e,t))return ut(!lt.f.call(e,t),e[t])};function mt(e){return"function"==typeof e?e:void 0}function vt(e,t){return arguments.length<2?mt(_t[e])||mt(wt[e]):_t[e]&&_t[e][t]||wt[e]&&wt[e][t]}var yt=i,_t=yt,wt=i,bt={},It=We,Tt=Math.min,Et=function(e){return 0<e?Tt(It(e),9007199254740991):0},St=We,kt=Math.max,Ct=Math.min,At=nt,Nt=Et,Rt=function(e,t){var n=St(e);return n<0?kt(n+t,0):Ct(n,t)},xt=function(a){return function(e,t,n){var r,i=At(e),s=Nt(i.length),o=Rt(n,s);if(a&&t!=t){for(;o<s;)if((r=i[o++])!=r)return!0}else for(;o<s;o++)if((a||o in i)&&i[o]===t)return a||o||0;return!a&&-1}},r={includes:xt(!0),indexOf:xt(!1)},Pt=D,Dt=nt,Ot=r.indexOf,Mt=ye,n=function(e,t){var n,r=Dt(e),i=0,s=[];for(n in r)!Pt(Mt,n)&&Pt(r,n)&&s.push(n);for(;t.length>i;)Pt(r,n=t[i++])&&(~Ot(s,n)||s.push(n));return s},l=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Lt=n,Ft=l.concat("length","prototype");bt.f=Object.getOwnPropertyNames||function(e){return Lt(e,Ft)};N={};N.f=Object.getOwnPropertySymbols;var Ut=bt,qt=N,jt=t,R=vt("Reflect","ownKeys")||function(e){var t=Ut.f(jt(e)),n=qt.f;return n?t.concat(n(e)):t},Vt=D,Bt=R,Kt=Je,$t=a,U=function(e,t){for(var n=Bt(t),r=$t.f,i=Kt.f,s=0;s<n.length;s++){var o=n[s];Vt(e,o)||r(e,o,i(t,o))}},Wt=e,zt=/#|\.prototype\./,B=function(e,t){var n=Ht[Gt(e)];return n==Yt||n!=Qt&&("function"==typeof t?Wt(t):!!t)},Gt=B.normalize=function(e){return String(e).replace(zt,".").toLowerCase()},Ht=B.data={},Qt=B.NATIVE="N",Yt=B.POLYFILL="P",V=B,Jt=i,Xt=Je.f,Zt=S,en=Z.exports,tn=A,nn=U,rn=V,z=function(e,t){var n,r,i,s=e.target,o=e.global,a=e.stat,c=o?Jt:a?Jt[s]||tn(s,{}):(Jt[s]||{}).prototype;if(c)for(n in t){if(r=t[n],i=e.noTargetGet?(i=Xt(c,n))&&i.value:c[n],!rn(o?n:s+(a?".":"#")+n,e.forced)&&void 0!==i){if(typeof r==typeof i)continue;nn(r,i)}(e.sham||i&&i.sham)&&Zt(r,"sham",!0),en(c,n,r,e)}},sn=ze,$=function(e){return Object(sn(e))},J=!e(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),on=D,an=$,x=J,cn=ve("IE_PROTO"),ln=Object.prototype,ee=x?Object.getPrototypeOf:function(e){return e=an(e),on(e,cn)?e[cn]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ln:null},he=ee,de=S,pe=D,fe=Y("iterator"),Ee=!1;[].keys&&("next"in(or=[].keys())?(ar=he(he(or)))!==Object.prototype&&(Er=ar):Ee=!0),pe(Er=null==Er?{}:Er,fe)||de(Er,fe,function(){return this});function un(){}var hn,Te={IteratorPrototype:Er,BUGGY_SAFARI_ITERATORS:Ee},dn=n,fn=l,Ie=Object.keys||function(e){return dn(e,fn)},pn=a,gn=t,mn=Ie,Le=o?Object.defineProperties:function(e,t){gn(e);for(var n,r=mn(t),i=r.length,s=0;s<i;)pn.f(e,n=r[s++],t[n]);return e},Be=vt("document","documentElement"),vn=t,yn=Le,_n=l,X=ye,wn=Be,bn=d,In="prototype",Tn="script",En=ve("IE_PROTO"),Sn=function(e){return"<"+Tn+">"+e+"</"+Tn+">"},kn=function(){try{hn=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;kn=hn?function(e){e.write(Sn("")),e.close();var t=e.parentWindow.Object;return e=null,t}(hn):(e=bn("iframe"),t="java"+Tn+":",e.style.display="none",wn.appendChild(e),e.src=String(t),(e=e.contentWindow.document).open(),e.write(Sn("document.F=Object")),e.close(),e.F);for(var n=_n.length;n--;)delete kn[In][_n[n]];return kn()};X[En]=!0;function Cn(){return this}function An(){return this}var Qe=Object.create||function(e,t){var n;return null!==e?(un[In]=vn(e),n=new un,un[In]=null,n[En]=e):n=kn(),void 0===t?n:yn(n,t)},Nn=a.f,Rn=D,xn=Y("toStringTag"),tt=function(e,t,n){e&&!Rn(e=n?e:e.prototype,xn)&&Nn(e,xn,{configurable:!0,value:t})},Ze={},Pn=Te.IteratorPrototype,Dn=Qe,On=I,Mn=tt,Ln=Ze,Fn=c,Un=t,qn=function(e){if(!Fn(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e},rt=Object.setPrototypeOf||("__proto__"in{}?function(){var n,r=!1,e={};try{(n=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),r=e instanceof Array}catch(e){}return function(e,t){return Un(e),qn(t),r?n.call(e,t):e.__proto__=t,e}}():void 0),jn=z,Vn=function(e,t,n){var r=t+" Iterator";return e.prototype=Dn(Pn,{next:On(1,n)}),Mn(e,r,!1),Ln[r]=Cn,e},Bn=ee,Kn=rt,$n=tt,Wn=S,zn=Z.exports,p=Y,Gn=Ze,Hn=Te.IteratorPrototype,Qn=Te.BUGGY_SAFARI_ITERATORS,Yn=p("iterator"),Jn="values",Xn="entries",xt=function(e,t,n,r,i,s,o){Vn(n,t,r);function a(e){if(e===i&&p)return p;if(!Qn&&e in d)return d[e];switch(e){case"keys":case Jn:case Xn:return function(){return new n(this,e)}}return function(){return new n(this)}}var c,l,u=t+" Iterator",h=!1,d=e.prototype,f=d[Yn]||d["@@iterator"]||i&&d[i],p=!Qn&&f||a(i),g="Array"==t&&d.entries||f;if(g&&(g=Bn(g.call(new e)),Hn!==Object.prototype&&g.next&&(Bn(g)!==Hn&&(Kn?Kn(g,Hn):"function"!=typeof g[Yn]&&Wn(g,Yn,An)),$n(g,u,!0))),i==Jn&&f&&f.name!==Jn&&(h=!0,p=function(){return f.call(this)}),d[Yn]!==p&&Wn(d,Yn,p),Gn[t]=p,i)if(c={values:a(Jn),keys:s?p:a("keys"),entries:a(Xn)},o)for(l in c)!Qn&&!h&&l in d||zn(d,l,c[l]);else jn({target:t,proto:!0,forced:Qn||h},c);return c},Zn=Ye.charAt,r=Se,R=xt,er="String Iterator",tr=r.set,nr=r.getterFor(er);R(String,"String",function(e){tr(this,{type:er,string:String(e),index:0})},function(){var e=nr(this),t=e.string,n=e.index;return n>=t.length?{value:void 0,done:!0}:(n=Zn(t,n),e.index+=n.length,{value:n,done:!1})});var B=Qe,A=a,rr=Y("unscopables"),ir=Array.prototype;null==ir[rr]&&A.f(ir,rr,{configurable:!0,value:B(null)});var J=function(e){ir[rr][e]=!0},sr=nt,x=J,he=Ze,or=Se,ar=xt,cr="Array Iterator",lr=or.set,ur=or.getterFor(cr),pe=ar(Array,"Array",function(e,t){lr(this,{type:cr,target:sr(e),index:0,kind:t})},function(){var e=ur(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?{value:e.target=void 0,done:!0}:"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}},"values");he.Arguments=he.Array,x("keys"),x("values"),x("entries");var hr,dr=i,fr={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},pr=pe,gr=S,de=Y,mr=de("iterator"),vr=de("toStringTag"),yr=pr.values;for(hr in fr){var _r=dr[hr],wr=_r&&_r.prototype;if(wr){if(wr[mr]!==yr)try{gr(wr,mr,yr)}catch(_b){wr[mr]=yr}if(wr[vr]||gr(wr,vr,hr),fr[hr])for(var br in pr)if(wr[br]!==pr[br])try{gr(wr,br,pr[br])}catch(_b){wr[br]=pr[br]}}}function Ir(e,t){this.stopped=e,this.result=t}var fe=i.Promise,Tr=Z.exports,Er=function(e,t,n){for(var r in t)Tr(e,r,t[r],n);return e},Sr=vt,kr=a,Cr=o,Ar=Y("species"),Ee=function(e){var t=Sr(e),n=kr.f;Cr&&t&&!t[Ar]&&n(t,Ar,{configurable:!0,get:function(){return this}})},n=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e},Le=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e},l={exports:{}},Nr=Ze,Rr=Y("iterator"),xr=Array.prototype,X=function(e){return void 0!==e&&(Nr.Array===e||xr[Rr]===e)},Pr=n,Te=function(r,i,e){if(Pr(r),void 0===i)return r;switch(e){case 0:return function(){return r.call(i)};case 1:return function(e){return r.call(i,e)};case 2:return function(e,t){return r.call(i,e,t)};case 3:return function(e,t,n){return r.call(i,e,t,n)}}return function(){return r.apply(i,arguments)}},Dr=je,Or=Ze,Mr=Y("iterator"),p=function(e){if(null!=e)return e[Mr]||e["@@iterator"]||Or[Dr(e)]},Lr=t,Ye=function(t,e,n,r){try{return r?e(Lr(n)[0],n[1]):e(n)}catch(e){var i=t.return;throw void 0!==i&&Lr(i.call(t)),e}},Fr=t,Ur=X,qr=Et,jr=Te,Vr=p,Br=Ye;(l.exports=function(e,t,n,r,i){var s,o,a,c,l,u,h,d=jr(t,n,r?2:1);if(i)s=e;else{if("function"!=typeof(o=Vr(e)))throw TypeError("Target is not iterable");if(Ur(o)){for(a=0,c=qr(e.length);a<c;a++)if((l=r?d(Fr(h=e[a])[0],h[1]):d(e[a]))&&l instanceof Ir)return l;return new Ir(!1)}s=o.call(e)}for(u=s.next;!(h=u.call(s)).done;)if("object"==typeof(l=Br(s,d,h.value,r))&&l&&l instanceof Ir)return l;return new Ir(!1)}).stop=function(e){return new Ir(!0,e)};var Kr=Y("iterator"),$r=!1;try{var Wr=0,zr={next:function(){return{done:!!Wr++}},return:function(){$r=!0}};zr[Kr]=function(){return this},Array.from(zr,function(){throw 2})}catch(_b){}function Gr(e){return function(){ai(e)}}var Hr,r=function(e,t){if(!t&&!$r)return!1;var n=!1;try{var r={};r[Kr]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},Qr=t,Yr=n,Jr=Y("species"),R=function(e,t){var n,r=Qr(e).constructor;return void 0===r||null==(n=Qr(r)[Jr])?t:Yr(n)},A=vt("navigator","userAgent")||"",B=/(iphone|ipod|ipad).*applewebkit/i.test(A),Xr=i,or=e,ar=Me,he=Te,Zr=Be,ei=d,x=B,ti=Xr.location,de=Xr.setImmediate,Ze=Xr.clearImmediate,ni=Xr.process,zr=Xr.MessageChannel,ri=Xr.Dispatch,ii=0,si={},oi="onreadystatechange",ai=function(e){var t;si.hasOwnProperty(e)&&(t=si[e],delete si[e],t())},Be=function(e){ai(e.data)},d=function(e){Xr.postMessage(e+"",ti.protocol+"//"+ti.host)};de&&Ze||(de=function(e){for(var t=[],n=1;n<arguments.length;)t.push(arguments[n++]);return si[++ii]=function(){("function"==typeof e?e:Function(e)).apply(void 0,t)},Hr(ii),ii},Ze=function(e){delete si[e]},"process"==ar(ni)?Hr=function(e){ni.nextTick(Gr(e))}:ri&&ri.now?Hr=function(e){ri.now(Gr(e))}:zr&&!x?(wi=(yi=new zr).port2,yi.port1.onmessage=Be,Hr=he(wi.postMessage,wi,1)):!Xr.addEventListener||"function"!=typeof postMessage||Xr.importScripts||or(d)||"file:"===ti.protocol?Hr=oi in ei("script")?function(e){Zr.appendChild(ei("script"))[oi]=function(){Zr.removeChild(this),ai(e)}}:function(e){setTimeout(Gr(e),0)}:(Hr=d,Xr.addEventListener("message",Be,!1)));var ci,li,ui,hi,di,fi,pi,gi,ar={set:de,clear:Ze},mi=i,x=Je.f,zr=Me,vi=ar.set,yi=B,he=mi.MutationObserver||mi.WebKitMutationObserver,_i=mi.process,wi=mi.Promise,bi="process"==zr(_i),or=x(mi,"queueMicrotask"),d=or&&or.value;d||(ci=function(){var e,t;for(bi&&(e=_i.domain)&&e.exit();li;){t=li.fn,li=li.next;try{t()}catch(e){throw li?hi():ui=void 0,e}}ui=void 0,e&&e.enter()},hi=bi?function(){_i.nextTick(ci)}:he&&!yi?(di=!0,fi=document.createTextNode(""),new he(ci).observe(fi,{characterData:!0}),function(){fi.data=di=!di}):wi&&wi.resolve?(pi=wi.resolve(void 0),gi=pi.then,function(){gi.call(pi,ci)}):function(){vi.call(mi,ci)});function Ii(e){var n,r;this.promise=new e(function(e,t){if(void 0!==n||void 0!==r)throw TypeError("Bad Promise constructor");n=e,r=t}),this.resolve=Ti(n),this.reject=Ti(r)}var Be=d||function(e){var t={fn:e,next:void 0};ui&&(ui.next=t),li||(li=t,hi()),ui=t},de={},Ti=n;de.f=function(e){return new Ii(e)};var Ei=t,Si=c,ki=de,Ze=function(e,t){if(Ei(e),Si(t)&&t.constructor===e)return t;var n=ki.f(e);return(0,n.resolve)(t),n.promise},Ci=i,B=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},zr=A,x=i.process,or=x&&x.versions,yi=or&&or.v8;yi?qi=(Li=yi.split("."))[0]+Li[1]:zr&&(!(Li=zr.match(/Edge\/(\d+)/))||74<=Li[1])&&(Li=zr.match(/Chrome\/(\d+)/))&&(qi=Li[1]);var Ai,Ni,Ri,xi,he=qi&&+qi,wi=z,Pi=i,d=vt,A=fe,x=Z.exports,or=Er,yi=tt,zr=Ee,Di=c,Oi=n,Mi=Le,Li=Me,Fi=ue,Ui=l.exports,qi=r,ji=R,Vi=ar.set,Bi=Be,Ki=Ze,$i=function(e,t){var n=Ci.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))},ue=de,Wi=B,ar=Se,Be=V,zi=he,Gi=Y("species"),Hi="Promise",Qi=ar.get,Yi=ar.set,Ji=ar.getterFor(Hi),Xi=A,Zi=Pi.TypeError,es=Pi.document,ts=Pi.process,ns=d("fetch"),rs=ue.f,is=rs,ss="process"==Li(ts),os=!!(es&&es.createEvent&&Pi.dispatchEvent),as="unhandledrejection",cs="rejectionhandled",ls=1,us=2,hs=1,ds=2,Be=Be(Hi,function(){if(!(Fi(Xi)!==String(Xi))){if(66===zi)return!0;if(!ss&&"function"!=typeof PromiseRejectionEvent)return!0}if(51<=zi&&/native code/.test(Xi))return!1;function e(e){e(function(){},function(){})}var t=Xi.resolve(1);return(t.constructor={})[Gi]=e,!(t.then(function(){})instanceof e)}),qi=Be||!qi(function(e){Xi.all(e).catch(function(){})}),fs=function(e){var t;return!(!Di(e)||"function"!=typeof(t=e.then))&&t},ps=function(f,p,g){var m;p.notified||(p.notified=!0,m=p.reactions,Bi(function(){for(var r,i,e=p.value,t=p.state==ls,n=0;m.length>n;){var s,o,a,c=m[n++],l=t?c.ok:c.fail,u=c.resolve,h=c.reject,d=c.domain;try{l?(t||(p.rejection===ds&&function(e,t){Vi.call(Pi,function(){if(ss)ts.emit("rejectionHandled",e);else gs(cs,e,t.value)})}(f,p),p.rejection=hs),!0===l?s=e:(d&&d.enter(),s=l(e),d&&(d.exit(),a=!0)),s===c.promise?h(Zi("Promise-chain cycle")):(o=fs(s))?o.call(s,u,h):u(s)):h(e)}catch(e){d&&!a&&d.exit(),h(e)}}p.reactions=[],p.notified=!1,g&&!p.rejection&&(r=f,i=p,Vi.call(Pi,function(){var e,t=i.value,n=ms(i);if(n&&(e=Wi(function(){ss?ts.emit("unhandledRejection",t,r):gs(as,r,t)}),i.rejection=ss||ms(i)?ds:hs,e.error))throw e.value}))}))},gs=function(e,t,n){var r,i;os?((r=es.createEvent("Event")).promise=t,r.reason=n,r.initEvent(e,!1,!0),Pi.dispatchEvent(r)):r={promise:t,reason:n},(i=Pi["on"+e])?i(r):e===as&&$i("Unhandled promise rejection",n)},ms=function(e){return e.rejection!==hs&&!e.parent},vs=function(t,n,r,i){return function(e){t(n,r,e,i)}},ys=function(e,t,n,r){t.done||(t.done=!0,(t=r?r:t).value=n,t.state=us,ps(e,t,!0))},_s=function(n,r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(n===e)throw Zi("Promise can't be resolved itself");var i=fs(e);i?Bi(function(){var t={done:!1};try{i.call(e,vs(_s,n,t,r),vs(ys,n,t,r))}catch(e){ys(n,t,e,r)}}):(r.value=e,r.state=ls,ps(n,r,!1))}catch(e){ys(n,{done:!1},e,r)}}};Be&&(Xi=function(e){Mi(this,Xi,Hi),Oi(e),Ai.call(this);var t=Qi(this);try{e(vs(_s,this,t),vs(ys,this,t))}catch(e){ys(this,t,e)}},(Ai=function(e){Yi(this,{type:Hi,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=or(Xi.prototype,{then:function(e,t){var n=Ji(this),r=rs(ji(this,Xi));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=ss?ts.domain:void 0,n.parent=!0,n.reactions.push(r),0!=n.state&&ps(this,n,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Ni=function(){var e=new Ai,t=Qi(e);this.promise=e,this.resolve=vs(_s,e,t),this.reject=vs(ys,e,t)},ue.f=rs=function(e){return e===Xi||e===Ri?new Ni:is(e)},"function"==typeof A&&(xi=A.prototype.then,x(A.prototype,"then",function(e,t){var n=this;return new Xi(function(e,t){xi.call(n,e,t)}).then(e,t)},{unsafe:!0}),"function"==typeof ns&&wi({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return Ki(Xi,ns.apply(Pi,arguments))}}))),wi({global:!0,wrap:!0,forced:Be},{Promise:Xi}),yi(Xi,Hi,!1),zr(Hi),Ri=d(Hi),wi({target:Hi,stat:!0,forced:Be},{reject:function(e){var t=rs(this);return t.reject.call(void 0,e),t.promise}}),wi({target:Hi,stat:!0,forced:Be},{resolve:function(e){return Ki(this,e)}}),wi({target:Hi,stat:!0,forced:qi},{all:function(e){var a=this,t=rs(a),c=t.resolve,l=t.reject,n=Wi(function(){var r=Oi(a.resolve),i=[],s=0,o=1;Ui(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(a,e).then(function(e){n||(n=!0,i[t]=e,--o||c(i))},l)}),--o||c(i)});return n.error&&l(n.value),t.promise},race:function(e){var n=this,r=rs(n),i=r.reject,t=Wi(function(){var t=Oi(n.resolve);Ui(e,function(e){t.call(n,e).then(r.resolve,i)})});return t.error&&i(t.value),r.promise}});var d=z,ws=n,bs=de,Is=B,Ts=l.exports;d({target:"Promise",stat:!0},{allSettled:function(e){var a=this,t=bs.f(a),c=t.resolve,n=t.reject,r=Is(function(){var r=ws(a.resolve),i=[],s=0,o=1;Ts(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(a,e).then(function(e){n||(n=!0,i[t]={status:"fulfilled",value:e},--o||c(i))},function(e){n||(n=!0,i[t]={status:"rejected",reason:e},--o||c(i))})}),--o||c(i)});return r.error&&n(r.value),t.promise}});var Be=z,Es=fe,wi=e,Ss=vt,ks=R,Cs=Ze,qi=Z.exports;Be({target:"Promise",proto:!0,real:!0,forced:!!Es&&wi(function(){Es.prototype.finally.call({then:function(){}},function(){})})},{finally:function(t){var n=ks(this,Ss("Promise")),e="function"==typeof t;return this.then(e?function(e){return Cs(n,t()).then(function(){return e})}:t,e?function(e){return Cs(n,t()).then(function(){throw e})}:t)}}),"function"!=typeof Es||Es.prototype.finally||qi(Es.prototype,"finally",Ss("Promise").prototype.finally),yt.Promise;function As(e,t){var n=this;if(!(n instanceof As))return new As(e,t);xs&&(n=xs(new Error(t),Rs(n)));var r=[];return Ps(e,r.push,r),Ns?Os(n,{errors:r,type:"AggregateError"}):n.errors=r,void 0!==t&&Ds(n,"message",String(t)),n}var d=z,Ns=o,Rs=ee,xs=rt,fe=Qe,Ze=a,Be=I,Ps=l.exports,Ds=S,wi=Se,Os=wi.set,Ms=wi.getterFor("AggregateError");As.prototype=fe(Error.prototype,{constructor:Be(5,As),message:Be(5,""),name:Be(5,"AggregateError")}),Ns&&Ze.f(As.prototype,"errors",{get:function(){return Ms(this).errors},configurable:!0}),d({global:!0},{AggregateError:As});var Ls=de,Fs=B;z({target:"Promise",stat:!0},{try:function(e){var t=Ls.f(this),n=Fs(e);return(n.error?t.reject:t.resolve)(n.value),t.promise}});var qi=z,Us=n,qs=vt,js=de,Vs=B,Bs=l.exports,Ks="No one promise resolved";qi({target:"Promise",stat:!0},{any:function(e){var c=this,t=js.f(c),l=t.resolve,u=t.reject,n=Vs(function(){var r=Us(c.resolve),i=[],s=0,o=1,a=!1;Bs(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(c,e).then(function(e){n||a||(a=!0,l(e))},function(e){n||a||(n=!0,i[t]=e,--o||u(new(qs("AggregateError"))(i,Ks)))})}),--o||u(new(qs("AggregateError"))(i,Ks))});return n.error&&u(n.value),t.promise}});function $s(e){throw e}var Ws=Me,wi=Array.isArray||function(e){return"Array"==Ws(e)},zs=c,Gs=wi,Hs=Y("species"),fe=function(e,t){var n;return new(void 0===(n=Gs(e)&&("function"==typeof(n=e.constructor)&&(n===Array||Gs(n.prototype))||zs(n)&&null===(n=n[Hs]))?void 0:n)?Array:n)(0===t?0:t)},Qs=Te,Ys=ot,Js=$,Xs=Et,Zs=fe,eo=[].push,Be=function(f){var p=1==f,g=2==f,m=3==f,v=4==f,y=6==f,_=5==f||y;return function(e,t,n,r){for(var i,s,o=Js(e),a=Ys(o),c=Qs(t,n,3),l=Xs(a.length),u=0,h=r||Zs,d=p?h(e,l):g?h(e,0):void 0;u<l;u++)if((_||u in a)&&(s=c(i=a[u],u,o),f))if(p)d[u]=s;else if(s)switch(f){case 3:return!0;case 5:return i;case 6:return u;case 2:eo.call(d,i)}else if(v)return!1;return y?-1:m||v?v:d}},Ze={forEach:Be(0),map:Be(1),filter:Be(2),some:Be(3),every:Be(4),find:Be(5),findIndex:Be(6)},to=o,no=e,ro=D,io=Object.defineProperty,so={},d=function(e,t){if(ro(so,e))return so[e];var n=[][e],r=!!ro(t=t||{},"ACCESSORS")&&t.ACCESSORS,i=ro(t,0)?t[0]:$s,s=ro(t,1)?t[1]:void 0;return so[e]=!!n&&!no(function(){if(r&&!to)return!0;var e={length:-1};r?io(e,1,{enumerable:!0,get:$s}):e[1]=1,n.call(e,i,s)})},de=z,oo=Ze.find,B=J,qi="find",ao=!0,Be=d(qi);qi in[]&&Array(1)[qi](function(){ao=!1}),de({target:"Array",proto:!0,forced:ao||!Be},{find:function(e){return oo(this,e,1<arguments.length?arguments[1]:void 0)}}),B(qi);var co=i,lo=Te,uo=Function.call,de=function(e,t,n){return lo(uo,co[e].prototype[t],n)};de("Array","find");var Be=z,ho=Ze.findIndex,B=J,qi="findIndex",fo=!0,J=d(qi);qi in[]&&Array(1)[qi](function(){fo=!1}),Be({target:"Array",proto:!0,forced:fo||!J},{findIndex:function(e){return ho(this,e,1<arguments.length?arguments[1]:void 0)}}),B(qi),de("Array","findIndex");var po=v,go=a,mo=I,J=function(e,t,n){var r=po(t);r in e?go.f(e,r,mo(0,n)):e[r]=n},vo=Te,yo=$,_o=Ye,wo=X,bo=Et,Io=J,To=p,B=function(e){var t,n,r,i,s,o,a=yo(e),c="function"==typeof this?this:Array,l=arguments.length,u=1<l?arguments[1]:void 0,h=void 0!==u,d=To(a),f=0;if(h&&(u=vo(u,2<l?arguments[2]:void 0,2)),null==d||c==Array&&wo(d))for(n=new c(t=bo(a.length));f<t;f++)o=h?u(a[f],f):a[f],Io(n,f,o);else for(s=(i=d.call(a)).next,n=new c;!(r=s.call(i)).done;f++)o=h?_o(i,u,[r.value,f],!0):r.value,Io(n,f,o);return n.length=f,n};z({target:"Array",stat:!0,forced:!r(function(e){Array.from(e)})},{from:B}),yt.Array.from;var Eo=e,qi=z,So=Ze.some,Ye=d,X=function(e,t){var n=[][e];return!!n&&Eo(function(){n.call(null,t||function(){throw 1},1)})}("some"),B=Ye("some");qi({target:"Array",proto:!0,forced:!X||!B},{some:function(e){return So(this,e,1<arguments.length?arguments[1]:void 0)}}),de("Array","some");function ko(e){return Ro(e)&&xo(Ko,Po(e))}var Co,d="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ao=o,No=i,Ro=c,xo=D,Po=je,Do=S,Oo=Z.exports,Ye=a.f,qi=ee,Mo=rt,X=Y,B=O,Lo=No.Int8Array,Fo=Lo&&Lo.prototype,je=No.Uint8ClampedArray,ee=je&&je.prototype,Uo=Lo&&qi(Lo),qo=Fo&&qi(Fo),je=Object.prototype,jo=je.isPrototypeOf,X=X("toStringTag"),Vo=B("TYPED_ARRAY_TAG"),Bo=d&&!!Mo&&"Opera"!==Po(No.opera),d=!1,Ko={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(Co in Ko)No[Co]||(Bo=!1);if((!Bo||"function"!=typeof Uo||Uo===Function.prototype)&&(Uo=function(){throw TypeError("Incorrect invocation")},Bo))for(Co in Ko)No[Co]&&Mo(No[Co],Uo);if((!Bo||!qo||qo===je)&&(qo=Uo.prototype,Bo))for(Co in Ko)No[Co]&&Mo(No[Co].prototype,qo);if(Bo&&qi(ee)!==qo&&Mo(ee,qo),Ao&&!xo(qo,X))for(Co in d=!0,Ye(qo,X,{get:function(){return Ro(this)?this[Vo]:void 0}}),Ko)No[Co]&&Do(No[Co],Vo,Co);var Ye=i,X={NATIVE_ARRAY_BUFFER_VIEWS:Bo,TYPED_ARRAY_TAG:d&&Vo,aTypedArray:function(e){if(ko(e))return e;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Mo){if(jo.call(Uo,e))return e}else for(var t in Ko)if(xo(Ko,Co)){t=No[t];if(t&&(e===t||jo.call(t,e)))return e}throw TypeError("Target is not a typed array constructor")},exportTypedArrayMethod:function(e,t,n){if(Ao){if(n)for(var r in Ko){r=No[r];r&&xo(r.prototype,e)&&delete r.prototype[e]}qo[e]&&!n||Oo(qo,e,!n&&Bo&&Fo[e]||t)}},exportTypedArrayStaticMethod:function(e,t,n){var r,i;if(Ao){if(Mo){if(n)for(r in Ko)(i=No[r])&&xo(i,e)&&delete i[e];if(Uo[e]&&!n)return;try{return Oo(Uo,e,!n&&Bo&&Lo[e]||t)}catch(e){}}for(r in Ko)!(i=No[r])||i[e]&&!n||Oo(i,e,t)}},isView:function(e){var t=Po(e);return"DataView"===t||xo(Ko,t)},isTypedArray:ko,TypedArray:Uo,TypedArrayPrototype:qo},d=pe,pe=Y("iterator"),Ye=Ye.Uint8Array,$o=d.values,Wo=d.keys,zo=d.entries,Go=X.aTypedArray,d=X.exportTypedArrayMethod,X=Ye&&Ye.prototype[pe],Ye=!!X&&("values"==X.name||null==X.name),X=function(){return $o.call(Go(this))};d("entries",function(){return zo.call(Go(this))}),d("keys",function(){return Wo.call(Go(this))}),d("values",X,!Ye),d(pe,X,!Ye);var Ho=o,X=e,Qo=Ie,Yo=N,Jo=Xe,Xo=$,Zo=ot,ea=Object.assign,ta=Object.defineProperty,Ye=!ea||X(function(){if(Ho&&1!==ea({b:1},ea(ta({},"a",{enumerable:!0,get:function(){ta(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=ea({},e)[n]||Qo(ea({},t)).join("")!=r})?function(e,t){for(var n=Xo(e),r=arguments.length,i=1,s=Yo.f,o=Jo.f;i<r;)for(var a,c=Zo(arguments[i++]),l=s?Qo(c).concat(s(c)):Qo(c),u=l.length,h=0;h<u;)a=l[h++],Ho&&!o.call(c,a)||(n[a]=c[a]);return n}:ea;z({target:"Object",stat:!0,forced:Object.assign!==Ye},{assign:Ye}),yt.Object.assign;var na=o,ra=Ie,ia=nt,sa=Xe.f,ot=function(a){return function(e){for(var t,n=ia(e),r=ra(n),i=r.length,s=0,o=[];s<i;)t=r[s++],na&&!sa.call(n,t)||o.push(a?[t,n[t]]:n[t]);return o}},X={entries:ot(!0),values:ot(!1)},Ye=z,oa=X.entries;Ye({target:"Object",stat:!0},{entries:function(e){return oa(e)}}),yt.Object.entries;var ot=z,aa=X.values;ot({target:"Object",stat:!0},{values:function(e){return aa(e)}}),yt.Object.values;var ca=c,la=Me,ua=Y("match"),ha=function(e){var t;return ca(e)&&(void 0!==(t=e[ua])?!!t:"RegExp"==la(e))},Ye=function(e){if(ha(e))throw TypeError("The method doesn't accept regular expressions");return e},da=Y("match"),X=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[da]=!1,"/./"[t](n)}catch(e){}}return!1},fa=Ye,pa=ze;z({target:"String",proto:!0,forced:!X("includes")},{includes:function(e){return!!~String(pa(this)).indexOf(fa(e),1<arguments.length?arguments[1]:void 0)}}),de("String","includes");var ot=z,Me=Je.f,ga=Et,ma=Ye,va=ze,X=X,ya="".startsWith,_a=Math.min,X=X("startsWith");ot({target:"String",proto:!0,forced:!!(X||(!(Me=Me(String.prototype,"startsWith"))||Me.writable))&&!X},{startsWith:function(e){var t=String(va(this));ma(e);var n=ga(_a(1<arguments.length?arguments[1]:void 0,t.length)),r=String(e);return ya?ya.call(t,r,n):t.slice(n,n+r.length)===r}}),de("String","startsWith");var wa=We,ba=ze;z({target:"String",proto:!0},{repeat:"".repeat||function(e){var t=String(ba(this)),n="",r=wa(e);if(r<0||r==1/0)throw RangeError("Wrong number of repetitions");for(;0<r;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n}}),de("String","repeat");var Ia=e,Ta=he,Ea=Y("species"),We=z,ze=e,Sa=wi,ka=c,Ca=$,Aa=Et,Na=J,Ra=fe,de=function(t){return 51<=Ta||!Ia(function(){var e=[];return(e.constructor={})[Ea]=function(){return{foo:1}},1!==e[t](Boolean).foo})},Et=he,xa=Y("isConcatSpreadable"),Pa=9007199254740991,Da="Maximum allowed index exceeded",J=51<=Et||!ze(function(){var e=[];return e[xa]=!1,e.concat()[0]!==e}),fe=de("concat");We({target:"Array",proto:!0,forced:!J||!fe},{concat:function(e){for(var t,n,r,i=Ca(this),s=Ra(i,0),o=0,a=-1,c=arguments.length;a<c;a++)if(function(e){if(!ka(e))return!1;var t=e[xa];return void 0!==t?!!t:Sa(e)}(r=-1===a?i:arguments[a])){if(n=Aa(r.length),Pa<o+n)throw TypeError(Da);for(t=0;t<n;t++,o++)t in r&&Na(s,o,r[t])}else{if(Pa<=o)throw TypeError(Da);Na(s,o++,r)}return s.length=o,s}});var he={},Oa=nt,Ma=bt.f,La={}.toString,Fa="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];he.f=function(e){return Fa&&"[object Window]"==La.call(e)?function(e){try{return Ma(e)}catch(e){return Fa.slice()}}(e):Ma(Oa(e))};Et={};Et.f=Y;function Ua(e,t){var n=_c[e]=Za(fc[lc]);return uc(n,{type:cc,tag:e,description:t}),$a||(n.description=t),n}function qa(t,e){Ha(t);var n=Ya(e),r=ec(n).concat(Ac(n));return oc(r,function(e){$a&&!Cc.call(n,e)||kc(t,e,n[e])}),t}var ja=yt,Va=D,Ba=Et,Ka=a.f,ze=function(e){var t=ja.Symbol||(ja.Symbol={});Va(t,e)||Ka(t,e,{value:Ba.f(e)})},de=z,We=i,J=vt,$a=o,fe=q,q=j,j=e,Wa=D,za=wi,Ga=c,Ha=t,Qa=$,Ya=nt,Ja=v,Xa=I,Za=Qe,ec=Ie,v=bt,I=he,tc=N,Ie=Je,bt=a,he=Xe,N=S,Je=Z.exports,Xe=s.exports,S=ve,nc=ye,rc=O,ic=Y,s=Et,sc=ze,ve=tt,Y=Se,oc=Ze.forEach,ac=S("hidden"),cc="Symbol",lc="prototype",S=ic("toPrimitive"),uc=Y.set,hc=Y.getterFor(cc),dc=Object[lc],fc=We.Symbol,pc=J("JSON","stringify"),gc=Ie.f,mc=bt.f,vc=I.f,yc=he.f,_c=Xe("symbols"),wc=Xe("op-symbols"),bc=Xe("string-to-symbol-registry"),Ic=Xe("symbol-to-string-registry"),Xe=Xe("wks"),We=We.QObject,Tc=!We||!We[lc]||!We[lc].findChild,Ec=$a&&j(function(){return 7!=Za(mc({},"a",{get:function(){return mc(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=gc(dc,t);r&&delete dc[t],mc(e,t,n),r&&e!==dc&&mc(dc,t,r)}:mc,Sc=q?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof fc},kc=function(e,t,n){e===dc&&kc(wc,t,n),Ha(e);var r=Ja(t,!0);return Ha(n),Wa(_c,r)?(n.enumerable?(Wa(e,ac)&&e[ac][r]&&(e[ac][r]=!1),n=Za(n,{enumerable:Xa(0,!1)})):(Wa(e,ac)||mc(e,ac,Xa(1,{})),e[ac][r]=!0),Ec(e,r,n)):mc(e,r,n)},Cc=function(e){var t=Ja(e,!0),n=yc.call(this,t);return!(this===dc&&Wa(_c,t)&&!Wa(wc,t))&&(!(n||!Wa(this,t)||!Wa(_c,t)||Wa(this,ac)&&this[ac][t])||n)},We=function(e,t){var n=Ya(e),r=Ja(t,!0);if(n!==dc||!Wa(_c,r)||Wa(wc,r)){var i=gc(n,r);return!i||!Wa(_c,r)||Wa(n,ac)&&n[ac][r]||(i.enumerable=!0),i}},q=function(e){var t=vc(Ya(e)),n=[];return oc(t,function(e){Wa(_c,e)||Wa(nc,e)||n.push(e)}),n},Ac=function(e){var t=e===dc,n=vc(t?wc:Ya(e)),r=[];return oc(n,function(e){!Wa(_c,e)||t&&!Wa(dc,e)||r.push(_c[e])}),r};fe||(Je((fc=function(){if(this instanceof fc)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,t=rc(e),n=function(e){this===dc&&n.call(wc,e),Wa(this,ac)&&Wa(this[ac],t)&&(this[ac][t]=!1),Ec(this,t,Xa(1,e))};return $a&&Tc&&Ec(dc,t,{configurable:!0,set:n}),Ua(t,e)})[lc],"toString",function(){return hc(this).tag}),Je(fc,"withoutSetter",function(e){return Ua(rc(e),e)}),he.f=Cc,bt.f=kc,Ie.f=We,v.f=I.f=q,tc.f=Ac,s.f=function(e){return Ua(ic(e),e)},$a&&(mc(fc[lc],"description",{configurable:!0,get:function(){return hc(this).description}}),Je(dc,"propertyIsEnumerable",Cc,{unsafe:!0}))),de({global:!0,wrap:!0,forced:!fe,sham:!fe},{Symbol:fc}),oc(ec(Xe),function(e){sc(e)}),de({target:cc,stat:!0,forced:!fe},{for:function(e){var t=String(e);if(Wa(bc,t))return bc[t];var n=fc(t);return bc[t]=n,Ic[n]=t,n},keyFor:function(e){if(!Sc(e))throw TypeError(e+" is not a symbol");if(Wa(Ic,e))return Ic[e]},useSetter:function(){Tc=!0},useSimple:function(){Tc=!1}}),de({target:"Object",stat:!0,forced:!fe,sham:!$a},{create:function(e,t){return void 0===t?Za(e):qa(Za(e),t)},defineProperty:kc,defineProperties:qa,getOwnPropertyDescriptor:We}),de({target:"Object",stat:!0,forced:!fe},{getOwnPropertyNames:q,getOwnPropertySymbols:Ac}),de({target:"Object",stat:!0,forced:j(function(){tc.f(1)})},{getOwnPropertySymbols:function(e){return tc.f(Qa(e))}}),pc&&de({target:"JSON",stat:!0,forced:!fe||j(function(){var e=fc();return"[null]"!=pc([e])||"{}"!=pc({a:e})||"{}"!=pc(Object(e))})},{stringify:function(e,t,n){for(var r,i=[e],s=1;s<arguments.length;)i.push(arguments[s++]);if((Ga(r=t)||void 0!==e)&&!Sc(e))return za(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!Sc(t))return t}),i[1]=t,pc.apply(null,i)}}),fc[lc][S]||N(fc[lc],S,fc[lc].valueOf),ve(fc,cc),nc[ac]=!0,ze("asyncIterator");var Nc,Rc,xc,Pc,Dc,S=z,Oc=D,Mc=c,ve=a.f,U=U,Lc=i.Symbol;!o||"function"!=typeof Lc||"description"in Lc.prototype&&void 0===Lc().description||(Nc={},U(Rc=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),t=this instanceof Rc?new Lc(e):void 0===e?Lc():Lc(e);return""===e&&(Nc[t]=!0),t},Lc),(U=Rc.prototype=Lc.prototype).constructor=Rc,xc=U.toString,Pc="Symbol(test)"==String(Lc("test")),Dc=/^Symbol\((.*)\)[^)]+$/,ve(U,"description",{configurable:!0,get:function(){var e=Mc(this)?this.valueOf():this,t=xc.call(e);if(Oc(Nc,e))return"";t=Pc?t.slice(7,-1):t.replace(Dc,"$1");return""===t?void 0:t}}),S({global:!0,forced:!0},{Symbol:Rc})),ze("hasInstance"),ze("isConcatSpreadable"),ze("iterator"),ze("match"),ze("matchAll"),ze("replace"),ze("search"),ze("species"),ze("split"),ze("toPrimitive"),ze("toStringTag"),ze("unscopables"),tt(Math,"Math",!0),tt(i.JSON,"JSON",!0),yt.Symbol,ze("asyncDispose"),ze("dispose"),ze("observable"),ze("patternMatch"),ze("replaceAll"),Et.f("iterator");function Fc(e){jc(e,Bc,{value:{objectID:"O"+ ++Kc,weakData:{}}})}var ze={exports:{}},Et=!e(function(){return Object.isExtensible(Object.preventExtensions({}))}),ye=ye,Uc=c,qc=D,jc=a.f,Vc=Et,Bc=O("meta"),Kc=0,$c=Object.isExtensible||function(){return!0},Wc=ze.exports={REQUIRED:!1,fastKey:function(e,t){if(!Uc(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!qc(e,Bc)){if(!$c(e))return"F";if(!t)return"E";Fc(e)}return e[Bc].objectID},getWeakData:function(e,t){if(!qc(e,Bc)){if(!$c(e))return!0;if(!t)return!1;Fc(e)}return e[Bc].weakData},onFreeze:function(e){return Vc&&Wc.REQUIRED&&$c(e)&&!qc(e,Bc)&&Fc(e),e}};ye[Bc]=!0;var zc=c,Gc=rt,Hc=z,Qc=i,Yc=V,Jc=Z.exports,Xc=ze.exports,Zc=l.exports,el=Le,tl=c,nl=e,rl=r,il=tt,sl=function(e,t,n){var r,i;return Gc&&"function"==typeof(r=t.constructor)&&r!==n&&zc(i=r.prototype)&&i!==n.prototype&&Gc(e,i),e},tt=function(r,e,t){function n(e){var n=f[e];Jc(f,e,"add"==e?function(e){return n.call(this,0===e?0:e),this}:"delete"==e?function(e){return!(u&&!tl(e))&&n.call(this,0===e?0:e)}:"get"==e?function(e){return u&&!tl(e)?void 0:n.call(this,0===e?0:e)}:"has"==e?function(e){return!(u&&!tl(e))&&n.call(this,0===e?0:e)}:function(e,t){return n.call(this,0===e?0:e,t),this})}var i,s,o,a,c,l=-1!==r.indexOf("Map"),u=-1!==r.indexOf("Weak"),h=l?"set":"add",d=Qc[r],f=d&&d.prototype,p=d,g={};return Yc(r,"function"!=typeof d||!(u||f.forEach&&!nl(function(){(new d).entries().next()})))?(p=t.getConstructor(e,r,l,h),Xc.REQUIRED=!0):Yc(r,!0)&&(s=(i=new p)[h](u?{}:-0,1)!=i,o=nl(function(){i.has(1)}),a=rl(function(e){new d(e)}),c=!u&&nl(function(){for(var e=new d,t=5;t--;)e[h](t,t);return!e.has(-0)}),a||(((p=e(function(e,t){el(e,p,r);var n=sl(new d,e,p);return null!=t&&Zc(t,n[h],n,l),n})).prototype=f).constructor=p),(o||c)&&(n("delete"),n("has"),l&&n("get")),(c||s)&&n(h),u&&f.clear&&delete f.clear),g[r]=p,Hc({global:!0,forced:p!=d},g),il(p,r),u||t.setStrong(p,r,l),p},ol=a.f,al=Qe,cl=Er,ll=Te,ul=Le,hl=l.exports,dl=xt,fl=Ee,pl=o,gl=ze.exports.fastKey,ml=Se.set,vl=Se.getterFor,xt={getConstructor:function(e,n,r,i){function s(e,t,n){var r,i,s=c(e),o=a(e,t);return o?o.value=n:(s.last=o={index:i=gl(t,!0),key:t,value:n,previous:r=s.last,next:void 0,removed:!1},s.first||(s.first=o),r&&(r.next=o),pl?s.size++:e.size++,"F"!==i&&(s.index[i]=o)),e}function a(e,t){var n,r=c(e),i=gl(t);if("F"!==i)return r.index[i];for(n=r.first;n;n=n.next)if(n.key==t)return n}var o=e(function(e,t){ul(e,o,n),ml(e,{type:n,index:al(null),first:void 0,last:void 0,size:0}),pl||(e.size=0),null!=t&&hl(t,e[i],e,r)}),c=vl(n);return cl(o.prototype,{clear:function(){for(var e=c(this),t=e.index,n=e.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete t[n.index],n=n.next;e.first=e.last=void 0,pl?e.size=0:this.size=0},delete:function(e){var t,n,r=c(this),i=a(this,e);return i&&(t=i.next,n=i.previous,delete r.index[i.index],i.removed=!0,n&&(n.next=t),t&&(t.previous=n),r.first==i&&(r.first=t),r.last==i&&(r.last=n),pl?r.size--:this.size--),!!i},forEach:function(e){for(var t,n=c(this),r=ll(e,1<arguments.length?arguments[1]:void 0,3);t=t?t.next:n.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!a(this,e)}}),cl(o.prototype,r?{get:function(e){var t=a(this,e);return t&&t.value},set:function(e,t){return s(this,0===e?0:e,t)}}:{add:function(e){return s(this,e=0===e?0:e,e)}}),pl&&ol(o.prototype,"size",{get:function(){return c(this).size}}),o},setStrong:function(e,t,n){var r=t+" Iterator",i=vl(t),s=vl(r);dl(e,t,function(e,t){ml(this,{type:r,target:e,state:i(e),kind:t,last:void 0})},function(){for(var e=s(this),t=e.kind,n=e.last;n&&n.removed;)n=n.previous;return e.target&&(e.last=n=n?n.next:e.state.first)?"keys"==t?{value:n.key,done:!1}:"values"==t?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:{value:e.target=void 0,done:!0}},n?"entries":"values",!n,!0),fl(t)}};tt("Map",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},xt),yt.Map;var yl=n,_l=Te,wl=l.exports,Ee=function(e){var t,n,r,i,s=arguments.length,o=1<s?arguments[1]:void 0;return yl(this),(t=void 0!==o)&&yl(o),null==e?new this:(n=[],t?(r=0,i=_l(o,2<s?arguments[2]:void 0,2),wl(e,function(e){n.push(i(e,r++))})):wl(e,n.push,n),new this(n))};z({target:"Map",stat:!0},{from:Ee});o=function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];return new this(t)};z({target:"Map",stat:!0},{of:o});var bl=t,Il=n,ze=function(){for(var e,t=bl(this),n=Il(t.delete),r=!0,i=0,s=arguments.length;i<s;i++)e=n.call(t,arguments[i]),r=r&&e;return!!r},Tl=ze;z({target:"Map",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Tl.apply(this,arguments)}});var El=t,Sl=p,Se=function(e){return Map.prototype.entries.call(e)},p=z,kl=t,Cl=Te,Al=Se,Nl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{every:function(e){var n=kl(this),t=Al(n),r=Cl(e,1<arguments.length?arguments[1]:void 0,3);return!Nl(t,function(e,t){if(!r(t,e,n))return Nl.stop()},void 0,!0,!0).stopped}});var p=z,Rl=vt,xl=t,Pl=n,Dl=Te,Ol=R,Ml=Se,Ll=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{filter:function(e){var n=xl(this),t=Ml(n),r=Dl(e,1<arguments.length?arguments[1]:void 0,3),i=new(Ol(n,Rl("Map"))),s=Pl(i.set);return Ll(t,function(e,t){r(t,e,n)&&s.call(i,e,t)},void 0,!0,!0),i}});var p=z,Fl=t,Ul=Te,ql=Se,jl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{find:function(e){var n=Fl(this),t=ql(n),r=Ul(e,1<arguments.length?arguments[1]:void 0,3);return jl(t,function(e,t){if(r(t,e,n))return jl.stop(t)},void 0,!0,!0).result}});var p=z,Vl=t,Bl=Te,Kl=Se,$l=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{findKey:function(e){var n=Vl(this),t=Kl(n),r=Bl(e,1<arguments.length?arguments[1]:void 0,3);return $l(t,function(e,t){if(r(t,e,n))return $l.stop(e)},void 0,!0,!0).result}});var p=z,Wl=l.exports,zl=n;p({target:"Map",stat:!0},{groupBy:function(e,n){var r=new this;zl(n);var i=zl(r.has),s=zl(r.get),o=zl(r.set);return Wl(e,function(e){var t=n(e);i.call(r,t)?s.call(r,t).push(e):o.call(r,t,[e])}),r}});var p=z,Gl=t,Hl=Se,Ql=function(e,t){return e===t||e!=e&&t!=t},Yl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{includes:function(n){return Yl(Hl(Gl(this)),function(e,t){if(Ql(t,n))return Yl.stop()},void 0,!0,!0).stopped}});var p=z,Jl=l.exports,Xl=n;p({target:"Map",stat:!0},{keyBy:function(e,t){var n=new this;Xl(t);var r=Xl(n.set);return Jl(e,function(e){r.call(n,t(e),e)}),n}});var p=z,Zl=t,eu=Se,tu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{keyOf:function(n){return tu(eu(Zl(this)),function(e,t){if(t===n)return tu.stop(e)},void 0,!0,!0).result}});var p=z,nu=vt,ru=t,iu=n,su=Te,ou=R,au=Se,cu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{mapKeys:function(e){var n=ru(this),t=au(n),r=su(e,1<arguments.length?arguments[1]:void 0,3),i=new(ou(n,nu("Map"))),s=iu(i.set);return cu(t,function(e,t){s.call(i,r(t,e,n),t)},void 0,!0,!0),i}});var p=z,lu=vt,uu=t,hu=n,du=Te,fu=R,pu=Se,gu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{mapValues:function(e){var n=uu(this),t=pu(n),r=du(e,1<arguments.length?arguments[1]:void 0,3),i=new(fu(n,lu("Map"))),s=hu(i.set);return gu(t,function(e,t){s.call(i,e,r(t,e,n))},void 0,!0,!0),i}});var p=z,mu=t,vu=n,yu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{merge:function(e){for(var t=mu(this),n=vu(t.set),r=0;r<arguments.length;)yu(arguments[r++],n,t,!0);return t}});var p=z,_u=t,wu=n,bu=Se,Iu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{reduce:function(n){var r=_u(this),e=bu(r),i=arguments.length<2,s=i?void 0:arguments[1];if(wu(n),Iu(e,function(e,t){s=i?(i=!1,t):n(s,t,e,r)},void 0,!0,!0),i)throw TypeError("Reduce of empty map with no initial value");return s}});var p=z,Tu=t,Eu=Te,Su=Se,ku=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{some:function(e){var n=Tu(this),t=Su(n),r=Eu(e,1<arguments.length?arguments[1]:void 0,3);return ku(t,function(e,t){if(r(t,e,n))return ku.stop()},void 0,!0,!0).stopped}});var Cu=t,Au=n;z({target:"Map",proto:!0,real:!0,forced:!1},{update:function(e,t){var n=Cu(this),r=arguments.length;Au(t);var i=n.has(e);if(!i&&r<3)throw TypeError("Updating absent value");r=i?n.get(e):Au(2<r?arguments[2]:void 0)(e,n);return n.set(e,t(r,e,n)),n}});var Nu=t,p=function(e,t){var n,r=Nu(this),i=2<arguments.length?arguments[2]:void 0;if("function"!=typeof t&&"function"!=typeof i)throw TypeError("At least one callback required");return r.has(e)?(n=r.get(e),"function"==typeof t&&(n=t(n),r.set(e,n))):"function"==typeof i&&(n=i(),r.set(e,n)),n};z({target:"Map",proto:!0,real:!0,forced:!1},{upsert:p});z({target:"Map",proto:!0,real:!0,forced:!1},{updateOrInsert:p}),tt("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},xt),yt.Set,z({target:"Set",stat:!0},{from:Ee}),z({target:"Set",stat:!0},{of:o});var Ru=t,xu=n,Pu=function(){for(var e=Ru(this),t=xu(e.add),n=0,r=arguments.length;n<r;n++)t.call(e,arguments[n]);return e};z({target:"Set",proto:!0,real:!0,forced:!1},{addAll:function(){return Pu.apply(this,arguments)}});var Du=ze;z({target:"Set",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Du.apply(this,arguments)}});var o=function(e){return Set.prototype.values.call(e)},ze=z,Ou=t,Mu=Te,Lu=o,Fu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{every:function(e){var t=Ou(this),n=Lu(t),r=Mu(e,1<arguments.length?arguments[1]:void 0,3);return!Fu(n,function(e){if(!r(e,e,t))return Fu.stop()},void 0,!1,!0).stopped}});var ze=z,Uu=vt,qu=t,ju=n,Vu=R,Bu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{difference:function(e){var t=qu(this),n=new(Vu(t,Uu("Set")))(t),r=ju(n.delete);return Bu(e,function(e){r.call(n,e)}),n}});var ze=z,Ku=vt,$u=t,Wu=n,zu=Te,Gu=R,Hu=o,Qu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{filter:function(e){var t=$u(this),n=Hu(t),r=zu(e,1<arguments.length?arguments[1]:void 0,3),i=new(Gu(t,Ku("Set"))),s=Wu(i.add);return Qu(n,function(e){r(e,e,t)&&s.call(i,e)},void 0,!1,!0),i}});var ze=z,Yu=t,Ju=Te,Xu=o,Zu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{find:function(e){var t=Yu(this),n=Xu(t),r=Ju(e,1<arguments.length?arguments[1]:void 0,3);return Zu(n,function(e){if(r(e,e,t))return Zu.stop(e)},void 0,!1,!0).result}});var ze=z,eh=vt,th=t,nh=n,rh=R,ih=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{intersection:function(e){var t=th(this),n=new(rh(t,eh("Set"))),r=nh(t.has),i=nh(n.add);return ih(e,function(e){r.call(t,e)&&i.call(n,e)}),n}});var ze=z,sh=t,oh=n,ah=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{isDisjointFrom:function(e){var t=sh(this),n=oh(t.has);return!ah(e,function(e){if(!0===n.call(t,e))return ah.stop()}).stopped}});var ze=z,ch=vt,lh=t,uh=n,hh=function(e){var t=Sl(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return El(t.call(e))},dh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{isSubsetOf:function(e){var t=hh(this),n=lh(e),r=n.has;return"function"!=typeof r&&(n=new(ch("Set"))(e),r=uh(n.has)),!dh(t,function(e){if(!1===r.call(n,e))return dh.stop()},void 0,!1,!0).stopped}});var ze=z,fh=t,ph=n,gh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{isSupersetOf:function(e){var t=fh(this),n=ph(t.has);return!gh(e,function(e){if(!1===n.call(t,e))return gh.stop()}).stopped}});var ze=z,mh=t,vh=o,yh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{join:function(e){var t=mh(this),n=vh(t),r=void 0===e?",":String(e),t=[];return yh(n,t.push,t,!1,!0),t.join(r)}});var ze=z,_h=vt,wh=t,bh=n,Ih=Te,Th=R,Eh=o,Sh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{map:function(e){var t=wh(this),n=Eh(t),r=Ih(e,1<arguments.length?arguments[1]:void 0,3),i=new(Th(t,_h("Set"))),s=bh(i.add);return Sh(n,function(e){s.call(i,r(e,e,t))},void 0,!1,!0),i}});var ze=z,kh=t,Ch=n,Ah=o,Nh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{reduce:function(t){var n=kh(this),e=Ah(n),r=arguments.length<2,i=r?void 0:arguments[1];if(Ch(t),Nh(e,function(e){i=r?(r=!1,e):t(i,e,e,n)},void 0,!1,!0),r)throw TypeError("Reduce of empty set with no initial value");return i}});var ze=z,Rh=t,xh=Te,Ph=o,Dh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{some:function(e){var t=Rh(this),n=Ph(t),r=xh(e,1<arguments.length?arguments[1]:void 0,3);return Dh(n,function(e){if(r(e,e,t))return Dh.stop()},void 0,!1,!0).stopped}});var ze=z,Oh=vt,Mh=t,Lh=n,Fh=R,Uh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{symmetricDifference:function(e){var t=Mh(this),n=new(Fh(t,Oh("Set")))(t),r=Lh(n.delete),i=Lh(n.add);return Uh(e,function(e){r.call(n,e)||i.call(n,e)}),n}});var ze=z,qh=vt,jh=t,Vh=n,Bh=R,Kh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{union:function(e){var t=jh(this),t=new(Bh(t,qh("Set")))(t);return Kh(e,Vh(t.add),t),t}});var $h,Wh,zh=c,Gh=Math.floor;z({target:"Number",stat:!0},{isInteger:function(e){return!zh(e)&&isFinite(e)&&Gh(e)===e}}),yt.Number.isInteger;function Hh(e){var t=Xh(e);return Zh.encodeByteArray(t,!0)}const Qh={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},Yh=function(e,t){if(!e)throw Jh(t)},Jh=function(e){return new Error("Firebase Database ("+Qh.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},Xh=function(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n},Zh={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(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],o=u+1<n.length,a=o?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&a)<<2|l>>6,t=63&l;c||(t=64,o||(e=64)),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(Xh(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,o=e[n++];o<128?t[r++]=String.fromCharCode(o):191<o&&o<224?(i=e[n++],t[r++]=String.fromCharCode((31&o)<<6|63&i)):239<o&&o<365?(s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var o=c<e.length?n[e.charAt(c)]:64;++c;var a=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==o||null==a)throw Error();r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a&&r.push(o<<6&192|a))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},ed=function(e){return Hh(e).replace(/\./g,"")},td=function(e){try{return Zh.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function nd(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=nd(e[r],t[r]));return e}class rd{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function id(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[ed(JSON.stringify({alg:"none",type:"JWT"})),ed(JSON.stringify(i)),""].join(".")}function sd(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function od(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(sd())}function ad(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function cd(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function ld(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function ud(){const e=sd();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function hd(){return!0===Qh.NODE_ADMIN}function dd(){return"object"==typeof indexedDB}function fd(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function pd(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class gd extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,gd.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,md.prototype.create)}}class md{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(vd,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new gd(i,s,n)}}const vd=/\{\$([^}]+)}/g;function yd(e){return JSON.parse(e)}function _d(e){return JSON.stringify(e)}function wd(e){let t={},n={},r={},i="";try{var s=e.split(".");t=yd(td(s[0])||""),n=yd(td(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function bd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Id(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Td(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Ed(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function Sd(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const o of n){if(!r.includes(o))return;var i=e[o],s=t[o];if(kd(i)&&kd(s)){if(!Sd(i,s))return}else if(i!==s)return}for(const a of r)if(!n.includes(a))return;return 1}function kd(e){return null!==e&&"object"==typeof e}function Cd(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function Ad(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function Nd(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class Rd{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,u;for(let f=0;f<80;f++){u=f<40?f<20?(l=a^s&(o^a),1518500249):(l=s^o^a,1859775393):f<60?(l=s&o|a&(s|o),2400959708):(l=s^o^a,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[f]&4294967295;c=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=h}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function xd(e,t){const n=new Pd(e,t);return n.subscribe.bind(n)}class Pd{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=Dd),void 0===r.error&&(r.error=Dd),void 0===r.complete&&(r.complete=Dd);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Dd(){}function Od(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function Md(e,t){return`${e} failed: ${t} argument `}function Ld(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(Md(e,t)+"must be a valid function.")}function Fd(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(Md(e,t)+"must be a valid context object.")}const Ud=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},qd=1e3,jd=2,Vd=144e5,Bd=.5;function Kd(e,t=qd,n=jd){var r=t*Math.pow(n,e),i=Math.round(Bd*r*(Math.random()-.5)*2);return Math.min(Vd,r+i)}function $d(e){return e&&e._delegate?e._delegate:e}function Wd(e,r){return new Promise((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(`${r}: ${null===(t=e.target.error)||void 0===t?void 0:t.message}`)}})}class zd{constructor(e){this._db=e,this.objectStoreNames=this._db.objectStoreNames}transaction(e,t="readonly"){return new Gd(this._db.transaction.call(this._db,e,t))}createObjectStore(e,t){return new Hd(this._db.createObjectStore(e,t))}close(){this._db.close()}}class Gd{constructor(e){this._transaction=e,this.complete=new Promise((e,t)=>{this._transaction.oncomplete=function(){e()},this._transaction.onerror=()=>{t(this._transaction.error)},this._transaction.onabort=()=>{t(this._transaction.error)}})}objectStore(e){return new Hd(this._transaction.objectStore(e))}}class Hd{constructor(e){this._store=e}index(e){return new Qd(this._store.index(e))}createIndex(e,t,n){return new Qd(this._store.createIndex(e,t,n))}get(e){return Wd(this._store.get(e),"Error reading from IndexedDB")}put(e,t){return Wd(this._store.put(e,t),"Error writing to IndexedDB")}delete(e){return Wd(this._store.delete(e),"Error deleting from IndexedDB")}clear(){return Wd(this._store.clear(),"Error clearing IndexedDB object store")}}class Qd{constructor(e){this._index=e}get(e){return Wd(this._index.get(e),"Error reading from IndexedDB")}}function Yd(e,i,s){return new Promise((t,n)=>{try{const r=indexedDB.open(e,i);r.onsuccess=e=>{t(new zd(e.target.result))},r.onerror=e=>{var t;n(`Error opening indexedDB: ${null===(t=e.target.error)||void 0===t?void 0:t.message}`)},r.onupgradeneeded=e=>{s(new zd(r.result),e.oldVersion,e.newVersion,new Gd(r.transaction))}}catch(e){n(`Error opening indexedDB: ${e.message}`)}})}async function Jd(r){return new Promise((e,n)=>{try{const t=indexedDB.deleteDatabase(r);t.onsuccess=()=>{e()},t.onerror=e=>{var t;n(`Error deleting indexedDB database "${r}": ${null===(t=e.target.error)||void 0===t?void 0:t.message}`)}}catch(e){n(`Error deleting indexedDB database "${r}": ${e.message}`)}})}class Xd{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const Zd="[DEFAULT]";class ef{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new rd;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:Zd})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=Zd){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=Zd){return this.instances.has(e)}getOptions(e=Zd){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===Zd?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=Zd){return!this.component||this.component.multipleInstances?e:Zd}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class tf{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new ef(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const nf=[];(Wh=$h=$h||{})[Wh.DEBUG=0]="DEBUG",Wh[Wh.VERBOSE=1]="VERBOSE",Wh[Wh.INFO=2]="INFO",Wh[Wh.WARN=3]="WARN",Wh[Wh.ERROR=4]="ERROR",Wh[Wh.SILENT=5]="SILENT";const rf={debug:$h.DEBUG,verbose:$h.VERBOSE,info:$h.INFO,warn:$h.WARN,error:$h.ERROR,silent:$h.SILENT},sf=$h.INFO,of={[$h.DEBUG]:"log",[$h.VERBOSE]:"log",[$h.INFO]:"info",[$h.WARN]:"warn",[$h.ERROR]:"error"},af=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=of[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class cf{constructor(e){this.name=e,this._logLevel=sf,this._logHandler=af,this._userLogHandler=null,nf.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in $h))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?rf[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,$h.DEBUG,...e),this._logHandler(this,$h.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,$h.VERBOSE,...e),this._logHandler(this,$h.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,$h.INFO,...e),this._logHandler(this,$h.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,$h.WARN,...e),this._logHandler(this,$h.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,$h.ERROR,...e),this._logHandler(this,$h.ERROR,...e)}}class lf{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const uf="@firebase/app",hf=new cf("@firebase/app");var df;const ff="[DEFAULT]",pf={"@firebase/app":"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},gf=new Map,mf=new Map;function vf(t,n){try{t.container.addComponent(n)}catch(e){hf.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function yf(e,t){e.container.addOrOverwriteComponent(t)}function _f(e){var t=e.name;if(mf.has(t))return hf.debug(`There were multiple attempts to register component ${t}.`),!1;mf.set(t,e);for(const n of gf.values())vf(n,e);return!0}function wf(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const bf=new md("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}."});class If{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new Xd("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw bf.create("app-deleted",{appName:this._name})}}const Tf="9.6.11";function Ef(e,t={}){if("object"!=typeof t){const r=t;t={name:r}}var n=Object.assign({name:ff,automaticDataCollectionEnabled:!1},t);const r=n.name;if("string"!=typeof r||!r)throw bf.create("bad-app-name",{appName:String(r)});var i=gf.get(r);if(i){if(Sd(e,i.options)&&Sd(n,i.config))return i;throw bf.create("duplicate-app",{appName:r})}const s=new tf(r);for(const o of mf.values())s.addComponent(o);n=new If(e,n,s);return gf.set(r,n),n}function Sf(e=ff){var t=gf.get(e);if(!t)throw bf.create("no-app",{appName:e});return t}async function kf(e){var t=e.name;gf.has(t)&&(gf.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function Cf(e,t,n){let r=null!==(s=pf[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const o=[`Unable to register library "${r}" with version "${t}":`];return i&&o.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&o.push("and"),s&&o.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void hf.warn(o.join(" "))}_f(new Xd(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function Af(e,t){if(null!==e&&"function"!=typeof e)throw bf.create("invalid-log-argument");!function(s,e){for(const t of nf){let i=null;e&&e.level&&(i=rf[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&s({level:$h[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function Nf(e){var t;t=e,nf.forEach(e=>{e.setLogLevel(t)})}const Rf="firebase-heartbeat-database",xf=1,Pf="firebase-heartbeat-store";let Df=null;function Of(){return Df=Df||Yd(Rf,xf,(e,t)=>{0===t&&e.createObjectStore(Pf)}).catch(e=>{throw bf.create("storage-open",{originalErrorMessage:e.message})}),Df}async function Mf(e,t){try{const n=await Of(),r=n.transaction(Pf,"readwrite"),i=r.objectStore(Pf);return await i.put(t,Lf(e)),r.complete}catch(e){throw bf.create("storage-set",{originalErrorMessage:e.message})}}function Lf(e){return`${e.name}!${e.options.appId}`}class Ff{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new qf(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate();var t=e.getPlatformInfoString();const n=Uf();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";var e=Uf(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const s=n.find(e=>e.agent===i.agent);if(s){if(s.dates.push(i.date),jf(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),jf(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),t=ed(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function Uf(){const e=new Date;return e.toISOString().substring(0,10)}class qf{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!dd()&&fd().then(()=>!0).catch(()=>!1)}async read(){return await this._canUseIndexedDBPromise&&await async function(e){try{const t=await Of();return t.transaction(Pf).objectStore(Pf).get(Lf(e))}catch(e){throw bf.create("storage-get",{originalErrorMessage:e.message})}}(this.app)||{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return Mf(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return Mf(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function jf(e){return ed(JSON.stringify({version:2,heartbeats:e})).length}df="",_f(new Xd("platform-logger",e=>new lf(e),"PRIVATE")),_f(new Xd("heartbeat",e=>new Ff(e),"PRIVATE")),Cf(uf,"0.7.21",df),Cf(uf,"0.7.21","esm2017"),Cf("fire-js","");var Vf=Object.freeze({__proto__:null,SDK_VERSION:Tf,_DEFAULT_ENTRY_NAME:ff,_addComponent:vf,_addOrOverwriteComponent:yf,_apps:gf,_clearComponents:function(){mf.clear()},_components:mf,_getProvider:wf,_registerComponent:_f,_removeServiceInstance:function(e,t,n=ff){wf(e,t).clearInstance(n)},deleteApp:kf,getApp:Sf,getApps:function(){return Array.from(gf.values())},initializeApp:Ef,onLog:Af,registerVersion:Cf,setLogLevel:Nf,FirebaseError:gd});class Bf{constructor(e,t){this._delegate=e,this.firebase=t,vf(e,new Xd("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),kf(this._delegate)))}_getService(e,t=ff){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=ff){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){vf(this._delegate,e)}_addOrOverwriteComponent(e){yf(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Kf=new md("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function $f(i){const s={},o={__esModule:!0,initializeApp:function(e,t={}){var n=Ef(e,t);if(bd(s,n.name))return s[n.name];var r=new i(n,o);return s[n.name]=r},app:a,registerVersion:Cf,setLogLevel:Nf,onLog:Af,apps:null,SDK_VERSION:Tf,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;_f(n)&&"PUBLIC"===n.type&&(e=(e=a())=>{if("function"!=typeof e[t])throw Kf.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&nd(e,n.serviceProps),o[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?o[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:Vf}};function a(e){if(e=e||ff,!bd(s,e))throw Kf.create("no-app",{appName:e});return s[e]}return o.default=o,Object.defineProperty(o,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),a.App=i,o}l=function e(){const t=$f(Bf);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){nd(t,e)},createSubscribe:xd,ErrorFactory:md,deepExtend:nd}),t}();const Wf=new cf("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){Wf.warn(`
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";!function(e){var t,n,o,r,i,s,a,c,l,u;function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function d(e){return e="string"!=typeof e?String(e):e}function f(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function p(t){this.map={},t instanceof p?t.forEach(function(e,t){this.append(t,e)},this):Array.isArray(t)?t.forEach(function(e){this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function g(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function m(n){return new Promise(function(e,t){n.onload=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function v(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function _(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e)if("string"==typeof e)this._bodyText=e;else if(o&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(r&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(i&&o&&a(e))this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!i||!ArrayBuffer.prototype.isPrototypeOf(e)&&!c(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=y(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=g(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(v)}),this.text=function(){var e,t,n=g(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}function w(e,t){var n,r=(t=t||{}).body;if(e instanceof w){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,r||null==e._bodyInit||(r=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"omit",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(e=t.method||this.method||"GET",n=e.toUpperCase(),-1<l.indexOf(n)?n:e),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function b(e){var r=new FormData;return e.trim().split("&").forEach(function(e){var t,n;e&&(t=(n=e.split("=")).shift().replace(/\+/g," "),n=n.join("=").replace(/\+/g," "),r.append(decodeURIComponent(t),decodeURIComponent(n)))}),r}function I(e,t){t=t||{},this.type="default",this.status=void 0===t.status?200:t.status,this.ok=200<=this.status&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}e.fetch||(t="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,o="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),r="FormData"in e,(i="ArrayBuffer"in e)&&(s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=function(e){return e&&DataView.prototype.isPrototypeOf(e)},c=ArrayBuffer.isView||function(e){return e&&-1<s.indexOf(Object.prototype.toString.call(e))}),p.prototype.append=function(e,t){e=h(e),t=d(t);var n=this.map[e];this.map[e]=n?n+","+t:t},p.prototype.delete=function(e){delete this.map[h(e)]},p.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},p.prototype.set=function(e,t){this.map[h(e)]=d(t)},p.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},p.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),f(n)},p.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),f(t)},p.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),f(n)},n&&(p.prototype[Symbol.iterator]=p.prototype.entries),l=["DELETE","GET","HEAD","OPTIONS","POST","PUT"],w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},_.call(w.prototype),_.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},I.error=function(){var e=new I(null,{status:0,statusText:""});return e.type="error",e},u=[301,302,303,307,308],I.redirect=function(e,t){if(-1===u.indexOf(t))throw new RangeError("Invalid status code");return new I(null,{status:t,headers:{location:e}})},e.Headers=p,e.Request=w,e.Response=I,e.fetch=function(n,r){return new Promise(function(i,e){var t=new w(n,r),s=new XMLHttpRequest;s.onload=function(){var e,r,t={status:s.status,statusText:s.statusText,headers:(e=s.getAllResponseHeaders()||"",r=new p,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var t=e.split(":"),n=t.shift().trim();n&&(t=t.join(":").trim(),r.append(n,t))}),r)};t.url="responseURL"in s?s.responseURL:t.headers.get("X-Request-URL");var n="response"in s?s.response:s.responseText;i(new I(n,t))},s.onerror=function(){e(new TypeError("Network request failed"))},s.ontimeout=function(){e(new TypeError("Network request failed"))},s.open(t.method,t.url,!0),"include"===t.credentials?s.withCredentials=!0:"omit"===t.credentials&&(s.withCredentials=!1),"responseType"in s&&o&&(s.responseType="blob"),t.headers.forEach(function(e,t){s.setRequestHeader(t,e)}),s.send(void 0===t._bodyInit?null:t._bodyInit)})},e.fetch.polyfill=!0)}("undefined"!=typeof self?self:void 0);function e(e){try{return!!e()}catch(e){return!0}}function t(e){if(!g(e))throw TypeError(String(e)+" is not an object");return e}var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r=function(e){return e&&e.Math==Math&&e},i=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n&&n)||Function("return this")(),s={exports:{}},o=!e(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}),a={},c=function(e){return"object"==typeof e?null!==e:"function"==typeof e},l=c,u=i.document,h=l(u)&&l(u.createElement),d=function(e){return h?u.createElement(e):{}},f=d,p=!o&&!e(function(){return 7!=Object.defineProperty(f("div"),"a",{get:function(){return 7}}).a}),g=c,m=c,v=function(e,t){if(!m(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!m(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!m(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!m(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")},y=p,_=t,w=v,b=Object.defineProperty;a.f=o?b:function(e,t,n){if(_(e),t=w(t,!0),_(n),y)try{return b(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var I=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},T=a,E=I,S=o?function(e,t,n){return T.f(e,t,E(1,n))}:function(e,t,n){return e[t]=n,e},k=i,C=S,A=function(t,n){try{C(k,t,n)}catch(e){k[t]=n}return n},N=A,R="__core-js_shared__",x=i[R]||N(R,{}),P=x;(s.exports=function(e,t){return P[e]||(P[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"});function D(e,t){return M.call(e,t)}function O(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++L+F).toString(36)}var M={}.hasOwnProperty,L=0,F=Math.random(),U=e,q=!!Object.getOwnPropertySymbols&&!U(function(){return!String(Symbol())}),j=q&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,V=i,B=s.exports,K=D,$=O,W=q,z=j,G=B("wks"),H=V.Symbol,Q=z?H:H&&H.withoutSetter||$,Y=function(e){return K(G,e)||(W&&K(H,e)?G[e]=H[e]:G[e]=Q("Symbol."+e)),G[e]},J={};J[Y("toStringTag")]="z";var X="[object z]"===String(J),Z={exports:{}},ee=x,te=Function.toString;"function"!=typeof ee.inspectSource&&(ee.inspectSource=function(e){return te.call(e)});var ne,re,ie,se,oe,ae,ce,le,ue=ee.inspectSource,he=ue,de=i.WeakMap,fe="function"==typeof de&&/native code/.test(he(de)),pe=s.exports,ge=O,me=pe("keys"),ve=function(e){return me[e]||(me[e]=ge(e))},ye={},_e=c,we=S,be=D,Ie=ve,Te=ye,Ee=i.WeakMap;ce=fe?(ne=new Ee,re=ne.get,ie=ne.has,se=ne.set,oe=function(e,t){return se.call(ne,e,t),t},ae=function(e){return re.call(ne,e)||{}},function(e){return ie.call(ne,e)}):(Te[le=Ie("state")]=!0,oe=function(e,t){return we(e,le,t),t},ae=function(e){return be(e,le)?e[le]:{}},function(e){return be(e,le)});var Se={set:oe,get:ae,has:ce,enforce:function(e){return ce(e)?ae(e):oe(e,{})},getterFor:function(n){return function(e){var t;if(!_e(e)||(t=ae(e)).type!==n)throw TypeError("Incompatible receiver, "+n+" required");return t}}},ke=i,Ce=S,Ae=D,Ne=A,Re=ue,xe=Se.get,Pe=Se.enforce,De=String(String).split("String");(Z.exports=function(e,t,n,r){var i=!!r&&!!r.unsafe,s=!!r&&!!r.enumerable,o=!!r&&!!r.noTargetGet;"function"==typeof n&&("string"!=typeof t||Ae(n,"name")||Ce(n,"name",t),Pe(n).source=De.join("string"==typeof t?t:"")),e!==ke?(i?!o&&e[t]&&(s=!0):delete e[t],s?e[t]=n:Ce(e,t,n)):s?e[t]=n:Ne(t,n)})(Function.prototype,"toString",function(){return"function"==typeof this&&xe(this).source||Re(this)});var Oe={}.toString,Me=function(e){return Oe.call(e).slice(8,-1)},Le=X,Fe=Me,Ue=Y("toStringTag"),qe="Arguments"==Fe(function(){return arguments}()),je=Le?Fe:function(e){var t,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),Ue))?n:qe?Fe(t):"Object"==(n=Fe(t))&&"function"==typeof t.callee?"Arguments":n},Ve=je,Be=Z.exports;X||Be(Object.prototype,"toString",X?{}.toString:function(){return"[object "+Ve(this)+"]"},{unsafe:!0});var Ke=Math.ceil,$e=Math.floor,We=function(e){return isNaN(e=+e)?0:(0<e?$e:Ke)(e)},ze=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e},Ge=We,He=ze,Qe=function(a){return function(e,t){var n,r,i=String(He(e)),s=Ge(t),o=i.length;return s<0||o<=s?a?"":void 0:(n=i.charCodeAt(s))<55296||56319<n||s+1===o||(r=i.charCodeAt(s+1))<56320||57343<r?a?i.charAt(s):n:a?i.slice(s,s+2):r-56320+(n-55296<<10)+65536}},Ye={codeAt:Qe(!1),charAt:Qe(!0)},Je={},Xe={},Ze={}.propertyIsEnumerable,et=Object.getOwnPropertyDescriptor,tt=et&&!Ze.call({1:2},1);Xe.f=tt?function(e){var t=et(this,e);return!!t&&t.enumerable}:Ze;function nt(e){return at(ct(e))}var rt=e,it=Me,st="".split,ot=rt(function(){return!Object("z").propertyIsEnumerable(0)})?function(e){return"String"==it(e)?st.call(e,""):Object(e)}:Object,at=ot,ct=ze,lt=Xe,ut=I,ht=nt,dt=v,ft=D,pt=p,gt=Object.getOwnPropertyDescriptor;Je.f=o?gt:function(e,t){if(e=ht(e),t=dt(t,!0),pt)try{return gt(e,t)}catch(e){}if(ft(e,t))return ut(!lt.f.call(e,t),e[t])};function mt(e){return"function"==typeof e?e:void 0}function vt(e,t){return arguments.length<2?mt(_t[e])||mt(wt[e]):_t[e]&&_t[e][t]||wt[e]&&wt[e][t]}var yt=i,_t=yt,wt=i,bt={},It=We,Tt=Math.min,Et=function(e){return 0<e?Tt(It(e),9007199254740991):0},St=We,kt=Math.max,Ct=Math.min,At=nt,Nt=Et,Rt=function(e,t){var n=St(e);return n<0?kt(n+t,0):Ct(n,t)},xt=function(a){return function(e,t,n){var r,i=At(e),s=Nt(i.length),o=Rt(n,s);if(a&&t!=t){for(;o<s;)if((r=i[o++])!=r)return!0}else for(;o<s;o++)if((a||o in i)&&i[o]===t)return a||o||0;return!a&&-1}},r={includes:xt(!0),indexOf:xt(!1)},Pt=D,Dt=nt,Ot=r.indexOf,Mt=ye,n=function(e,t){var n,r=Dt(e),i=0,s=[];for(n in r)!Pt(Mt,n)&&Pt(r,n)&&s.push(n);for(;t.length>i;)Pt(r,n=t[i++])&&(~Ot(s,n)||s.push(n));return s},l=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Lt=n,Ft=l.concat("length","prototype");bt.f=Object.getOwnPropertyNames||function(e){return Lt(e,Ft)};N={};N.f=Object.getOwnPropertySymbols;var Ut=bt,qt=N,jt=t,R=vt("Reflect","ownKeys")||function(e){var t=Ut.f(jt(e)),n=qt.f;return n?t.concat(n(e)):t},Vt=D,Bt=R,Kt=Je,$t=a,U=function(e,t){for(var n=Bt(t),r=$t.f,i=Kt.f,s=0;s<n.length;s++){var o=n[s];Vt(e,o)||r(e,o,i(t,o))}},Wt=e,zt=/#|\.prototype\./,B=function(e,t){var n=Ht[Gt(e)];return n==Yt||n!=Qt&&("function"==typeof t?Wt(t):!!t)},Gt=B.normalize=function(e){return String(e).replace(zt,".").toLowerCase()},Ht=B.data={},Qt=B.NATIVE="N",Yt=B.POLYFILL="P",V=B,Jt=i,Xt=Je.f,Zt=S,en=Z.exports,tn=A,nn=U,rn=V,z=function(e,t){var n,r,i,s=e.target,o=e.global,a=e.stat,c=o?Jt:a?Jt[s]||tn(s,{}):(Jt[s]||{}).prototype;if(c)for(n in t){if(r=t[n],i=e.noTargetGet?(i=Xt(c,n))&&i.value:c[n],!rn(o?n:s+(a?".":"#")+n,e.forced)&&void 0!==i){if(typeof r==typeof i)continue;nn(r,i)}(e.sham||i&&i.sham)&&Zt(r,"sham",!0),en(c,n,r,e)}},sn=ze,$=function(e){return Object(sn(e))},J=!e(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),on=D,an=$,x=J,cn=ve("IE_PROTO"),ln=Object.prototype,ee=x?Object.getPrototypeOf:function(e){return e=an(e),on(e,cn)?e[cn]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ln:null},he=ee,de=S,pe=D,fe=Y("iterator"),Ee=!1;[].keys&&("next"in(or=[].keys())?(ar=he(he(or)))!==Object.prototype&&(Er=ar):Ee=!0),pe(Er=null==Er?{}:Er,fe)||de(Er,fe,function(){return this});function un(){}var hn,Te={IteratorPrototype:Er,BUGGY_SAFARI_ITERATORS:Ee},dn=n,fn=l,Ie=Object.keys||function(e){return dn(e,fn)},pn=a,gn=t,mn=Ie,Le=o?Object.defineProperties:function(e,t){gn(e);for(var n,r=mn(t),i=r.length,s=0;s<i;)pn.f(e,n=r[s++],t[n]);return e},Be=vt("document","documentElement"),vn=t,yn=Le,_n=l,X=ye,wn=Be,bn=d,In="prototype",Tn="script",En=ve("IE_PROTO"),Sn=function(e){return"<"+Tn+">"+e+"</"+Tn+">"},kn=function(){try{hn=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;kn=hn?function(e){e.write(Sn("")),e.close();var t=e.parentWindow.Object;return e=null,t}(hn):(e=bn("iframe"),t="java"+Tn+":",e.style.display="none",wn.appendChild(e),e.src=String(t),(e=e.contentWindow.document).open(),e.write(Sn("document.F=Object")),e.close(),e.F);for(var n=_n.length;n--;)delete kn[In][_n[n]];return kn()};X[En]=!0;function Cn(){return this}function An(){return this}var Qe=Object.create||function(e,t){var n;return null!==e?(un[In]=vn(e),n=new un,un[In]=null,n[En]=e):n=kn(),void 0===t?n:yn(n,t)},Nn=a.f,Rn=D,xn=Y("toStringTag"),tt=function(e,t,n){e&&!Rn(e=n?e:e.prototype,xn)&&Nn(e,xn,{configurable:!0,value:t})},Ze={},Pn=Te.IteratorPrototype,Dn=Qe,On=I,Mn=tt,Ln=Ze,Fn=c,Un=t,qn=function(e){if(!Fn(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e},rt=Object.setPrototypeOf||("__proto__"in{}?function(){var n,r=!1,e={};try{(n=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),r=e instanceof Array}catch(e){}return function(e,t){return Un(e),qn(t),r?n.call(e,t):e.__proto__=t,e}}():void 0),jn=z,Vn=function(e,t,n){var r=t+" Iterator";return e.prototype=Dn(Pn,{next:On(1,n)}),Mn(e,r,!1),Ln[r]=Cn,e},Bn=ee,Kn=rt,$n=tt,Wn=S,zn=Z.exports,p=Y,Gn=Ze,Hn=Te.IteratorPrototype,Qn=Te.BUGGY_SAFARI_ITERATORS,Yn=p("iterator"),Jn="values",Xn="entries",xt=function(e,t,n,r,i,s,o){Vn(n,t,r);function a(e){if(e===i&&p)return p;if(!Qn&&e in d)return d[e];switch(e){case"keys":case Jn:case Xn:return function(){return new n(this,e)}}return function(){return new n(this)}}var c,l,u=t+" Iterator",h=!1,d=e.prototype,f=d[Yn]||d["@@iterator"]||i&&d[i],p=!Qn&&f||a(i),g="Array"==t&&d.entries||f;if(g&&(g=Bn(g.call(new e)),Hn!==Object.prototype&&g.next&&(Bn(g)!==Hn&&(Kn?Kn(g,Hn):"function"!=typeof g[Yn]&&Wn(g,Yn,An)),$n(g,u,!0))),i==Jn&&f&&f.name!==Jn&&(h=!0,p=function(){return f.call(this)}),d[Yn]!==p&&Wn(d,Yn,p),Gn[t]=p,i)if(c={values:a(Jn),keys:s?p:a("keys"),entries:a(Xn)},o)for(l in c)!Qn&&!h&&l in d||zn(d,l,c[l]);else jn({target:t,proto:!0,forced:Qn||h},c);return c},Zn=Ye.charAt,r=Se,R=xt,er="String Iterator",tr=r.set,nr=r.getterFor(er);R(String,"String",function(e){tr(this,{type:er,string:String(e),index:0})},function(){var e=nr(this),t=e.string,n=e.index;return n>=t.length?{value:void 0,done:!0}:(n=Zn(t,n),e.index+=n.length,{value:n,done:!1})});var B=Qe,A=a,rr=Y("unscopables"),ir=Array.prototype;null==ir[rr]&&A.f(ir,rr,{configurable:!0,value:B(null)});var J=function(e){ir[rr][e]=!0},sr=nt,x=J,he=Ze,or=Se,ar=xt,cr="Array Iterator",lr=or.set,ur=or.getterFor(cr),pe=ar(Array,"Array",function(e,t){lr(this,{type:cr,target:sr(e),index:0,kind:t})},function(){var e=ur(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?{value:e.target=void 0,done:!0}:"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}},"values");he.Arguments=he.Array,x("keys"),x("values"),x("entries");var hr,dr=i,fr={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},pr=pe,gr=S,de=Y,mr=de("iterator"),vr=de("toStringTag"),yr=pr.values;for(hr in fr){var _r=dr[hr],wr=_r&&_r.prototype;if(wr){if(wr[mr]!==yr)try{gr(wr,mr,yr)}catch(_b){wr[mr]=yr}if(wr[vr]||gr(wr,vr,hr),fr[hr])for(var br in pr)if(wr[br]!==pr[br])try{gr(wr,br,pr[br])}catch(_b){wr[br]=pr[br]}}}function Ir(e,t){this.stopped=e,this.result=t}var fe=i.Promise,Tr=Z.exports,Er=function(e,t,n){for(var r in t)Tr(e,r,t[r],n);return e},Sr=vt,kr=a,Cr=o,Ar=Y("species"),Ee=function(e){var t=Sr(e),n=kr.f;Cr&&t&&!t[Ar]&&n(t,Ar,{configurable:!0,get:function(){return this}})},n=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e},Le=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e},l={exports:{}},Nr=Ze,Rr=Y("iterator"),xr=Array.prototype,X=function(e){return void 0!==e&&(Nr.Array===e||xr[Rr]===e)},Pr=n,Te=function(r,i,e){if(Pr(r),void 0===i)return r;switch(e){case 0:return function(){return r.call(i)};case 1:return function(e){return r.call(i,e)};case 2:return function(e,t){return r.call(i,e,t)};case 3:return function(e,t,n){return r.call(i,e,t,n)}}return function(){return r.apply(i,arguments)}},Dr=je,Or=Ze,Mr=Y("iterator"),p=function(e){if(null!=e)return e[Mr]||e["@@iterator"]||Or[Dr(e)]},Lr=t,Ye=function(t,e,n,r){try{return r?e(Lr(n)[0],n[1]):e(n)}catch(e){var i=t.return;throw void 0!==i&&Lr(i.call(t)),e}},Fr=t,Ur=X,qr=Et,jr=Te,Vr=p,Br=Ye;(l.exports=function(e,t,n,r,i){var s,o,a,c,l,u,h,d=jr(t,n,r?2:1);if(i)s=e;else{if("function"!=typeof(o=Vr(e)))throw TypeError("Target is not iterable");if(Ur(o)){for(a=0,c=qr(e.length);a<c;a++)if((l=r?d(Fr(h=e[a])[0],h[1]):d(e[a]))&&l instanceof Ir)return l;return new Ir(!1)}s=o.call(e)}for(u=s.next;!(h=u.call(s)).done;)if("object"==typeof(l=Br(s,d,h.value,r))&&l&&l instanceof Ir)return l;return new Ir(!1)}).stop=function(e){return new Ir(!0,e)};var Kr=Y("iterator"),$r=!1;try{var Wr=0,zr={next:function(){return{done:!!Wr++}},return:function(){$r=!0}};zr[Kr]=function(){return this},Array.from(zr,function(){throw 2})}catch(_b){}function Gr(e){return function(){ai(e)}}var Hr,r=function(e,t){if(!t&&!$r)return!1;var n=!1;try{var r={};r[Kr]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},Qr=t,Yr=n,Jr=Y("species"),R=function(e,t){var n,r=Qr(e).constructor;return void 0===r||null==(n=Qr(r)[Jr])?t:Yr(n)},A=vt("navigator","userAgent")||"",B=/(iphone|ipod|ipad).*applewebkit/i.test(A),Xr=i,or=e,ar=Me,he=Te,Zr=Be,ei=d,x=B,ti=Xr.location,de=Xr.setImmediate,Ze=Xr.clearImmediate,ni=Xr.process,zr=Xr.MessageChannel,ri=Xr.Dispatch,ii=0,si={},oi="onreadystatechange",ai=function(e){var t;si.hasOwnProperty(e)&&(t=si[e],delete si[e],t())},Be=function(e){ai(e.data)},d=function(e){Xr.postMessage(e+"",ti.protocol+"//"+ti.host)};de&&Ze||(de=function(e){for(var t=[],n=1;n<arguments.length;)t.push(arguments[n++]);return si[++ii]=function(){("function"==typeof e?e:Function(e)).apply(void 0,t)},Hr(ii),ii},Ze=function(e){delete si[e]},"process"==ar(ni)?Hr=function(e){ni.nextTick(Gr(e))}:ri&&ri.now?Hr=function(e){ri.now(Gr(e))}:zr&&!x?(wi=(yi=new zr).port2,yi.port1.onmessage=Be,Hr=he(wi.postMessage,wi,1)):!Xr.addEventListener||"function"!=typeof postMessage||Xr.importScripts||or(d)||"file:"===ti.protocol?Hr=oi in ei("script")?function(e){Zr.appendChild(ei("script"))[oi]=function(){Zr.removeChild(this),ai(e)}}:function(e){setTimeout(Gr(e),0)}:(Hr=d,Xr.addEventListener("message",Be,!1)));var ci,li,ui,hi,di,fi,pi,gi,ar={set:de,clear:Ze},mi=i,x=Je.f,zr=Me,vi=ar.set,yi=B,he=mi.MutationObserver||mi.WebKitMutationObserver,_i=mi.process,wi=mi.Promise,bi="process"==zr(_i),or=x(mi,"queueMicrotask"),d=or&&or.value;d||(ci=function(){var e,t;for(bi&&(e=_i.domain)&&e.exit();li;){t=li.fn,li=li.next;try{t()}catch(e){throw li?hi():ui=void 0,e}}ui=void 0,e&&e.enter()},hi=bi?function(){_i.nextTick(ci)}:he&&!yi?(di=!0,fi=document.createTextNode(""),new he(ci).observe(fi,{characterData:!0}),function(){fi.data=di=!di}):wi&&wi.resolve?(pi=wi.resolve(void 0),gi=pi.then,function(){gi.call(pi,ci)}):function(){vi.call(mi,ci)});function Ii(e){var n,r;this.promise=new e(function(e,t){if(void 0!==n||void 0!==r)throw TypeError("Bad Promise constructor");n=e,r=t}),this.resolve=Ti(n),this.reject=Ti(r)}var Be=d||function(e){var t={fn:e,next:void 0};ui&&(ui.next=t),li||(li=t,hi()),ui=t},de={},Ti=n;de.f=function(e){return new Ii(e)};var Ei=t,Si=c,ki=de,Ze=function(e,t){if(Ei(e),Si(t)&&t.constructor===e)return t;var n=ki.f(e);return(0,n.resolve)(t),n.promise},Ci=i,B=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},zr=A,x=i.process,or=x&&x.versions,yi=or&&or.v8;yi?qi=(Li=yi.split("."))[0]+Li[1]:zr&&(!(Li=zr.match(/Edge\/(\d+)/))||74<=Li[1])&&(Li=zr.match(/Chrome\/(\d+)/))&&(qi=Li[1]);var Ai,Ni,Ri,xi,he=qi&&+qi,wi=z,Pi=i,d=vt,A=fe,x=Z.exports,or=Er,yi=tt,zr=Ee,Di=c,Oi=n,Mi=Le,Li=Me,Fi=ue,Ui=l.exports,qi=r,ji=R,Vi=ar.set,Bi=Be,Ki=Ze,$i=function(e,t){var n=Ci.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))},ue=de,Wi=B,ar=Se,Be=V,zi=he,Gi=Y("species"),Hi="Promise",Qi=ar.get,Yi=ar.set,Ji=ar.getterFor(Hi),Xi=A,Zi=Pi.TypeError,es=Pi.document,ts=Pi.process,ns=d("fetch"),rs=ue.f,is=rs,ss="process"==Li(ts),os=!!(es&&es.createEvent&&Pi.dispatchEvent),as="unhandledrejection",cs="rejectionhandled",ls=1,us=2,hs=1,ds=2,Be=Be(Hi,function(){if(!(Fi(Xi)!==String(Xi))){if(66===zi)return!0;if(!ss&&"function"!=typeof PromiseRejectionEvent)return!0}if(51<=zi&&/native code/.test(Xi))return!1;function e(e){e(function(){},function(){})}var t=Xi.resolve(1);return(t.constructor={})[Gi]=e,!(t.then(function(){})instanceof e)}),qi=Be||!qi(function(e){Xi.all(e).catch(function(){})}),fs=function(e){var t;return!(!Di(e)||"function"!=typeof(t=e.then))&&t},ps=function(f,p,g){var m;p.notified||(p.notified=!0,m=p.reactions,Bi(function(){for(var r,i,e=p.value,t=p.state==ls,n=0;m.length>n;){var s,o,a,c=m[n++],l=t?c.ok:c.fail,u=c.resolve,h=c.reject,d=c.domain;try{l?(t||(p.rejection===ds&&function(e,t){Vi.call(Pi,function(){if(ss)ts.emit("rejectionHandled",e);else gs(cs,e,t.value)})}(f,p),p.rejection=hs),!0===l?s=e:(d&&d.enter(),s=l(e),d&&(d.exit(),a=!0)),s===c.promise?h(Zi("Promise-chain cycle")):(o=fs(s))?o.call(s,u,h):u(s)):h(e)}catch(e){d&&!a&&d.exit(),h(e)}}p.reactions=[],p.notified=!1,g&&!p.rejection&&(r=f,i=p,Vi.call(Pi,function(){var e,t=i.value,n=ms(i);if(n&&(e=Wi(function(){ss?ts.emit("unhandledRejection",t,r):gs(as,r,t)}),i.rejection=ss||ms(i)?ds:hs,e.error))throw e.value}))}))},gs=function(e,t,n){var r,i;os?((r=es.createEvent("Event")).promise=t,r.reason=n,r.initEvent(e,!1,!0),Pi.dispatchEvent(r)):r={promise:t,reason:n},(i=Pi["on"+e])?i(r):e===as&&$i("Unhandled promise rejection",n)},ms=function(e){return e.rejection!==hs&&!e.parent},vs=function(t,n,r,i){return function(e){t(n,r,e,i)}},ys=function(e,t,n,r){t.done||(t.done=!0,(t=r?r:t).value=n,t.state=us,ps(e,t,!0))},_s=function(n,r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(n===e)throw Zi("Promise can't be resolved itself");var i=fs(e);i?Bi(function(){var t={done:!1};try{i.call(e,vs(_s,n,t,r),vs(ys,n,t,r))}catch(e){ys(n,t,e,r)}}):(r.value=e,r.state=ls,ps(n,r,!1))}catch(e){ys(n,{done:!1},e,r)}}};Be&&(Xi=function(e){Mi(this,Xi,Hi),Oi(e),Ai.call(this);var t=Qi(this);try{e(vs(_s,this,t),vs(ys,this,t))}catch(e){ys(this,t,e)}},(Ai=function(e){Yi(this,{type:Hi,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=or(Xi.prototype,{then:function(e,t){var n=Ji(this),r=rs(ji(this,Xi));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=ss?ts.domain:void 0,n.parent=!0,n.reactions.push(r),0!=n.state&&ps(this,n,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Ni=function(){var e=new Ai,t=Qi(e);this.promise=e,this.resolve=vs(_s,e,t),this.reject=vs(ys,e,t)},ue.f=rs=function(e){return e===Xi||e===Ri?new Ni:is(e)},"function"==typeof A&&(xi=A.prototype.then,x(A.prototype,"then",function(e,t){var n=this;return new Xi(function(e,t){xi.call(n,e,t)}).then(e,t)},{unsafe:!0}),"function"==typeof ns&&wi({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return Ki(Xi,ns.apply(Pi,arguments))}}))),wi({global:!0,wrap:!0,forced:Be},{Promise:Xi}),yi(Xi,Hi,!1),zr(Hi),Ri=d(Hi),wi({target:Hi,stat:!0,forced:Be},{reject:function(e){var t=rs(this);return t.reject.call(void 0,e),t.promise}}),wi({target:Hi,stat:!0,forced:Be},{resolve:function(e){return Ki(this,e)}}),wi({target:Hi,stat:!0,forced:qi},{all:function(e){var a=this,t=rs(a),c=t.resolve,l=t.reject,n=Wi(function(){var r=Oi(a.resolve),i=[],s=0,o=1;Ui(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(a,e).then(function(e){n||(n=!0,i[t]=e,--o||c(i))},l)}),--o||c(i)});return n.error&&l(n.value),t.promise},race:function(e){var n=this,r=rs(n),i=r.reject,t=Wi(function(){var t=Oi(n.resolve);Ui(e,function(e){t.call(n,e).then(r.resolve,i)})});return t.error&&i(t.value),r.promise}});var d=z,ws=n,bs=de,Is=B,Ts=l.exports;d({target:"Promise",stat:!0},{allSettled:function(e){var a=this,t=bs.f(a),c=t.resolve,n=t.reject,r=Is(function(){var r=ws(a.resolve),i=[],s=0,o=1;Ts(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(a,e).then(function(e){n||(n=!0,i[t]={status:"fulfilled",value:e},--o||c(i))},function(e){n||(n=!0,i[t]={status:"rejected",reason:e},--o||c(i))})}),--o||c(i)});return r.error&&n(r.value),t.promise}});var Be=z,Es=fe,wi=e,Ss=vt,ks=R,Cs=Ze,qi=Z.exports;Be({target:"Promise",proto:!0,real:!0,forced:!!Es&&wi(function(){Es.prototype.finally.call({then:function(){}},function(){})})},{finally:function(t){var n=ks(this,Ss("Promise")),e="function"==typeof t;return this.then(e?function(e){return Cs(n,t()).then(function(){return e})}:t,e?function(e){return Cs(n,t()).then(function(){throw e})}:t)}}),"function"!=typeof Es||Es.prototype.finally||qi(Es.prototype,"finally",Ss("Promise").prototype.finally),yt.Promise;function As(e,t){var n=this;if(!(n instanceof As))return new As(e,t);xs&&(n=xs(new Error(t),Rs(n)));var r=[];return Ps(e,r.push,r),Ns?Os(n,{errors:r,type:"AggregateError"}):n.errors=r,void 0!==t&&Ds(n,"message",String(t)),n}var d=z,Ns=o,Rs=ee,xs=rt,fe=Qe,Ze=a,Be=I,Ps=l.exports,Ds=S,wi=Se,Os=wi.set,Ms=wi.getterFor("AggregateError");As.prototype=fe(Error.prototype,{constructor:Be(5,As),message:Be(5,""),name:Be(5,"AggregateError")}),Ns&&Ze.f(As.prototype,"errors",{get:function(){return Ms(this).errors},configurable:!0}),d({global:!0},{AggregateError:As});var Ls=de,Fs=B;z({target:"Promise",stat:!0},{try:function(e){var t=Ls.f(this),n=Fs(e);return(n.error?t.reject:t.resolve)(n.value),t.promise}});var qi=z,Us=n,qs=vt,js=de,Vs=B,Bs=l.exports,Ks="No one promise resolved";qi({target:"Promise",stat:!0},{any:function(e){var c=this,t=js.f(c),l=t.resolve,u=t.reject,n=Vs(function(){var r=Us(c.resolve),i=[],s=0,o=1,a=!1;Bs(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(c,e).then(function(e){n||a||(a=!0,l(e))},function(e){n||a||(n=!0,i[t]=e,--o||u(new(qs("AggregateError"))(i,Ks)))})}),--o||u(new(qs("AggregateError"))(i,Ks))});return n.error&&u(n.value),t.promise}});function $s(e){throw e}var Ws=Me,wi=Array.isArray||function(e){return"Array"==Ws(e)},zs=c,Gs=wi,Hs=Y("species"),fe=function(e,t){var n;return new(void 0===(n=Gs(e)&&("function"==typeof(n=e.constructor)&&(n===Array||Gs(n.prototype))||zs(n)&&null===(n=n[Hs]))?void 0:n)?Array:n)(0===t?0:t)},Qs=Te,Ys=ot,Js=$,Xs=Et,Zs=fe,eo=[].push,Be=function(f){var p=1==f,g=2==f,m=3==f,v=4==f,y=6==f,_=5==f||y;return function(e,t,n,r){for(var i,s,o=Js(e),a=Ys(o),c=Qs(t,n,3),l=Xs(a.length),u=0,h=r||Zs,d=p?h(e,l):g?h(e,0):void 0;u<l;u++)if((_||u in a)&&(s=c(i=a[u],u,o),f))if(p)d[u]=s;else if(s)switch(f){case 3:return!0;case 5:return i;case 6:return u;case 2:eo.call(d,i)}else if(v)return!1;return y?-1:m||v?v:d}},Ze={forEach:Be(0),map:Be(1),filter:Be(2),some:Be(3),every:Be(4),find:Be(5),findIndex:Be(6)},to=o,no=e,ro=D,io=Object.defineProperty,so={},d=function(e,t){if(ro(so,e))return so[e];var n=[][e],r=!!ro(t=t||{},"ACCESSORS")&&t.ACCESSORS,i=ro(t,0)?t[0]:$s,s=ro(t,1)?t[1]:void 0;return so[e]=!!n&&!no(function(){if(r&&!to)return!0;var e={length:-1};r?io(e,1,{enumerable:!0,get:$s}):e[1]=1,n.call(e,i,s)})},de=z,oo=Ze.find,B=J,qi="find",ao=!0,Be=d(qi);qi in[]&&Array(1)[qi](function(){ao=!1}),de({target:"Array",proto:!0,forced:ao||!Be},{find:function(e){return oo(this,e,1<arguments.length?arguments[1]:void 0)}}),B(qi);var co=i,lo=Te,uo=Function.call,de=function(e,t,n){return lo(uo,co[e].prototype[t],n)};de("Array","find");var Be=z,ho=Ze.findIndex,B=J,qi="findIndex",fo=!0,J=d(qi);qi in[]&&Array(1)[qi](function(){fo=!1}),Be({target:"Array",proto:!0,forced:fo||!J},{findIndex:function(e){return ho(this,e,1<arguments.length?arguments[1]:void 0)}}),B(qi),de("Array","findIndex");var po=v,go=a,mo=I,J=function(e,t,n){var r=po(t);r in e?go.f(e,r,mo(0,n)):e[r]=n},vo=Te,yo=$,_o=Ye,wo=X,bo=Et,Io=J,To=p,B=function(e){var t,n,r,i,s,o,a=yo(e),c="function"==typeof this?this:Array,l=arguments.length,u=1<l?arguments[1]:void 0,h=void 0!==u,d=To(a),f=0;if(h&&(u=vo(u,2<l?arguments[2]:void 0,2)),null==d||c==Array&&wo(d))for(n=new c(t=bo(a.length));f<t;f++)o=h?u(a[f],f):a[f],Io(n,f,o);else for(s=(i=d.call(a)).next,n=new c;!(r=s.call(i)).done;f++)o=h?_o(i,u,[r.value,f],!0):r.value,Io(n,f,o);return n.length=f,n};z({target:"Array",stat:!0,forced:!r(function(e){Array.from(e)})},{from:B}),yt.Array.from;var Eo=e,qi=z,So=Ze.some,Ye=d,X=function(e,t){var n=[][e];return!!n&&Eo(function(){n.call(null,t||function(){throw 1},1)})}("some"),B=Ye("some");qi({target:"Array",proto:!0,forced:!X||!B},{some:function(e){return So(this,e,1<arguments.length?arguments[1]:void 0)}}),de("Array","some");function ko(e){return Ro(e)&&xo(Ko,Po(e))}var Co,d="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ao=o,No=i,Ro=c,xo=D,Po=je,Do=S,Oo=Z.exports,Ye=a.f,qi=ee,Mo=rt,X=Y,B=O,Lo=No.Int8Array,Fo=Lo&&Lo.prototype,je=No.Uint8ClampedArray,ee=je&&je.prototype,Uo=Lo&&qi(Lo),qo=Fo&&qi(Fo),je=Object.prototype,jo=je.isPrototypeOf,X=X("toStringTag"),Vo=B("TYPED_ARRAY_TAG"),Bo=d&&!!Mo&&"Opera"!==Po(No.opera),d=!1,Ko={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(Co in Ko)No[Co]||(Bo=!1);if((!Bo||"function"!=typeof Uo||Uo===Function.prototype)&&(Uo=function(){throw TypeError("Incorrect invocation")},Bo))for(Co in Ko)No[Co]&&Mo(No[Co],Uo);if((!Bo||!qo||qo===je)&&(qo=Uo.prototype,Bo))for(Co in Ko)No[Co]&&Mo(No[Co].prototype,qo);if(Bo&&qi(ee)!==qo&&Mo(ee,qo),Ao&&!xo(qo,X))for(Co in d=!0,Ye(qo,X,{get:function(){return Ro(this)?this[Vo]:void 0}}),Ko)No[Co]&&Do(No[Co],Vo,Co);var Ye=i,X={NATIVE_ARRAY_BUFFER_VIEWS:Bo,TYPED_ARRAY_TAG:d&&Vo,aTypedArray:function(e){if(ko(e))return e;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Mo){if(jo.call(Uo,e))return e}else for(var t in Ko)if(xo(Ko,Co)){t=No[t];if(t&&(e===t||jo.call(t,e)))return e}throw TypeError("Target is not a typed array constructor")},exportTypedArrayMethod:function(e,t,n){if(Ao){if(n)for(var r in Ko){r=No[r];r&&xo(r.prototype,e)&&delete r.prototype[e]}qo[e]&&!n||Oo(qo,e,!n&&Bo&&Fo[e]||t)}},exportTypedArrayStaticMethod:function(e,t,n){var r,i;if(Ao){if(Mo){if(n)for(r in Ko)(i=No[r])&&xo(i,e)&&delete i[e];if(Uo[e]&&!n)return;try{return Oo(Uo,e,!n&&Bo&&Lo[e]||t)}catch(e){}}for(r in Ko)!(i=No[r])||i[e]&&!n||Oo(i,e,t)}},isView:function(e){var t=Po(e);return"DataView"===t||xo(Ko,t)},isTypedArray:ko,TypedArray:Uo,TypedArrayPrototype:qo},d=pe,pe=Y("iterator"),Ye=Ye.Uint8Array,$o=d.values,Wo=d.keys,zo=d.entries,Go=X.aTypedArray,d=X.exportTypedArrayMethod,X=Ye&&Ye.prototype[pe],Ye=!!X&&("values"==X.name||null==X.name),X=function(){return $o.call(Go(this))};d("entries",function(){return zo.call(Go(this))}),d("keys",function(){return Wo.call(Go(this))}),d("values",X,!Ye),d(pe,X,!Ye);var Ho=o,X=e,Qo=Ie,Yo=N,Jo=Xe,Xo=$,Zo=ot,ea=Object.assign,ta=Object.defineProperty,Ye=!ea||X(function(){if(Ho&&1!==ea({b:1},ea(ta({},"a",{enumerable:!0,get:function(){ta(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=ea({},e)[n]||Qo(ea({},t)).join("")!=r})?function(e,t){for(var n=Xo(e),r=arguments.length,i=1,s=Yo.f,o=Jo.f;i<r;)for(var a,c=Zo(arguments[i++]),l=s?Qo(c).concat(s(c)):Qo(c),u=l.length,h=0;h<u;)a=l[h++],Ho&&!o.call(c,a)||(n[a]=c[a]);return n}:ea;z({target:"Object",stat:!0,forced:Object.assign!==Ye},{assign:Ye}),yt.Object.assign;var na=o,ra=Ie,ia=nt,sa=Xe.f,ot=function(a){return function(e){for(var t,n=ia(e),r=ra(n),i=r.length,s=0,o=[];s<i;)t=r[s++],na&&!sa.call(n,t)||o.push(a?[t,n[t]]:n[t]);return o}},X={entries:ot(!0),values:ot(!1)},Ye=z,oa=X.entries;Ye({target:"Object",stat:!0},{entries:function(e){return oa(e)}}),yt.Object.entries;var ot=z,aa=X.values;ot({target:"Object",stat:!0},{values:function(e){return aa(e)}}),yt.Object.values;var ca=c,la=Me,ua=Y("match"),ha=function(e){var t;return ca(e)&&(void 0!==(t=e[ua])?!!t:"RegExp"==la(e))},Ye=function(e){if(ha(e))throw TypeError("The method doesn't accept regular expressions");return e},da=Y("match"),X=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[da]=!1,"/./"[t](n)}catch(e){}}return!1},fa=Ye,pa=ze;z({target:"String",proto:!0,forced:!X("includes")},{includes:function(e){return!!~String(pa(this)).indexOf(fa(e),1<arguments.length?arguments[1]:void 0)}}),de("String","includes");var ot=z,Me=Je.f,ga=Et,ma=Ye,va=ze,X=X,ya="".startsWith,_a=Math.min,X=X("startsWith");ot({target:"String",proto:!0,forced:!!(X||(!(Me=Me(String.prototype,"startsWith"))||Me.writable))&&!X},{startsWith:function(e){var t=String(va(this));ma(e);var n=ga(_a(1<arguments.length?arguments[1]:void 0,t.length)),r=String(e);return ya?ya.call(t,r,n):t.slice(n,n+r.length)===r}}),de("String","startsWith");var wa=We,ba=ze;z({target:"String",proto:!0},{repeat:"".repeat||function(e){var t=String(ba(this)),n="",r=wa(e);if(r<0||r==1/0)throw RangeError("Wrong number of repetitions");for(;0<r;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n}}),de("String","repeat");var Ia=e,Ta=he,Ea=Y("species"),We=z,ze=e,Sa=wi,ka=c,Ca=$,Aa=Et,Na=J,Ra=fe,de=function(t){return 51<=Ta||!Ia(function(){var e=[];return(e.constructor={})[Ea]=function(){return{foo:1}},1!==e[t](Boolean).foo})},Et=he,xa=Y("isConcatSpreadable"),Pa=9007199254740991,Da="Maximum allowed index exceeded",J=51<=Et||!ze(function(){var e=[];return e[xa]=!1,e.concat()[0]!==e}),fe=de("concat");We({target:"Array",proto:!0,forced:!J||!fe},{concat:function(e){for(var t,n,r,i=Ca(this),s=Ra(i,0),o=0,a=-1,c=arguments.length;a<c;a++)if(function(e){if(!ka(e))return!1;var t=e[xa];return void 0!==t?!!t:Sa(e)}(r=-1===a?i:arguments[a])){if(n=Aa(r.length),Pa<o+n)throw TypeError(Da);for(t=0;t<n;t++,o++)t in r&&Na(s,o,r[t])}else{if(Pa<=o)throw TypeError(Da);Na(s,o++,r)}return s.length=o,s}});var he={},Oa=nt,Ma=bt.f,La={}.toString,Fa="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];he.f=function(e){return Fa&&"[object Window]"==La.call(e)?function(e){try{return Ma(e)}catch(e){return Fa.slice()}}(e):Ma(Oa(e))};Et={};Et.f=Y;function Ua(e,t){var n=_c[e]=Za(fc[lc]);return uc(n,{type:cc,tag:e,description:t}),$a||(n.description=t),n}function qa(t,e){Ha(t);var n=Ya(e),r=ec(n).concat(Ac(n));return oc(r,function(e){$a&&!Cc.call(n,e)||kc(t,e,n[e])}),t}var ja=yt,Va=D,Ba=Et,Ka=a.f,ze=function(e){var t=ja.Symbol||(ja.Symbol={});Va(t,e)||Ka(t,e,{value:Ba.f(e)})},de=z,We=i,J=vt,$a=o,fe=q,q=j,j=e,Wa=D,za=wi,Ga=c,Ha=t,Qa=$,Ya=nt,Ja=v,Xa=I,Za=Qe,ec=Ie,v=bt,I=he,tc=N,Ie=Je,bt=a,he=Xe,N=S,Je=Z.exports,Xe=s.exports,S=ve,nc=ye,rc=O,ic=Y,s=Et,sc=ze,ve=tt,Y=Se,oc=Ze.forEach,ac=S("hidden"),cc="Symbol",lc="prototype",S=ic("toPrimitive"),uc=Y.set,hc=Y.getterFor(cc),dc=Object[lc],fc=We.Symbol,pc=J("JSON","stringify"),gc=Ie.f,mc=bt.f,vc=I.f,yc=he.f,_c=Xe("symbols"),wc=Xe("op-symbols"),bc=Xe("string-to-symbol-registry"),Ic=Xe("symbol-to-string-registry"),Xe=Xe("wks"),We=We.QObject,Tc=!We||!We[lc]||!We[lc].findChild,Ec=$a&&j(function(){return 7!=Za(mc({},"a",{get:function(){return mc(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=gc(dc,t);r&&delete dc[t],mc(e,t,n),r&&e!==dc&&mc(dc,t,r)}:mc,Sc=q?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof fc},kc=function(e,t,n){e===dc&&kc(wc,t,n),Ha(e);var r=Ja(t,!0);return Ha(n),Wa(_c,r)?(n.enumerable?(Wa(e,ac)&&e[ac][r]&&(e[ac][r]=!1),n=Za(n,{enumerable:Xa(0,!1)})):(Wa(e,ac)||mc(e,ac,Xa(1,{})),e[ac][r]=!0),Ec(e,r,n)):mc(e,r,n)},Cc=function(e){var t=Ja(e,!0),n=yc.call(this,t);return!(this===dc&&Wa(_c,t)&&!Wa(wc,t))&&(!(n||!Wa(this,t)||!Wa(_c,t)||Wa(this,ac)&&this[ac][t])||n)},We=function(e,t){var n=Ya(e),r=Ja(t,!0);if(n!==dc||!Wa(_c,r)||Wa(wc,r)){var i=gc(n,r);return!i||!Wa(_c,r)||Wa(n,ac)&&n[ac][r]||(i.enumerable=!0),i}},q=function(e){var t=vc(Ya(e)),n=[];return oc(t,function(e){Wa(_c,e)||Wa(nc,e)||n.push(e)}),n},Ac=function(e){var t=e===dc,n=vc(t?wc:Ya(e)),r=[];return oc(n,function(e){!Wa(_c,e)||t&&!Wa(dc,e)||r.push(_c[e])}),r};fe||(Je((fc=function(){if(this instanceof fc)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,t=rc(e),n=function(e){this===dc&&n.call(wc,e),Wa(this,ac)&&Wa(this[ac],t)&&(this[ac][t]=!1),Ec(this,t,Xa(1,e))};return $a&&Tc&&Ec(dc,t,{configurable:!0,set:n}),Ua(t,e)})[lc],"toString",function(){return hc(this).tag}),Je(fc,"withoutSetter",function(e){return Ua(rc(e),e)}),he.f=Cc,bt.f=kc,Ie.f=We,v.f=I.f=q,tc.f=Ac,s.f=function(e){return Ua(ic(e),e)},$a&&(mc(fc[lc],"description",{configurable:!0,get:function(){return hc(this).description}}),Je(dc,"propertyIsEnumerable",Cc,{unsafe:!0}))),de({global:!0,wrap:!0,forced:!fe,sham:!fe},{Symbol:fc}),oc(ec(Xe),function(e){sc(e)}),de({target:cc,stat:!0,forced:!fe},{for:function(e){var t=String(e);if(Wa(bc,t))return bc[t];var n=fc(t);return bc[t]=n,Ic[n]=t,n},keyFor:function(e){if(!Sc(e))throw TypeError(e+" is not a symbol");if(Wa(Ic,e))return Ic[e]},useSetter:function(){Tc=!0},useSimple:function(){Tc=!1}}),de({target:"Object",stat:!0,forced:!fe,sham:!$a},{create:function(e,t){return void 0===t?Za(e):qa(Za(e),t)},defineProperty:kc,defineProperties:qa,getOwnPropertyDescriptor:We}),de({target:"Object",stat:!0,forced:!fe},{getOwnPropertyNames:q,getOwnPropertySymbols:Ac}),de({target:"Object",stat:!0,forced:j(function(){tc.f(1)})},{getOwnPropertySymbols:function(e){return tc.f(Qa(e))}}),pc&&de({target:"JSON",stat:!0,forced:!fe||j(function(){var e=fc();return"[null]"!=pc([e])||"{}"!=pc({a:e})||"{}"!=pc(Object(e))})},{stringify:function(e,t,n){for(var r,i=[e],s=1;s<arguments.length;)i.push(arguments[s++]);if((Ga(r=t)||void 0!==e)&&!Sc(e))return za(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!Sc(t))return t}),i[1]=t,pc.apply(null,i)}}),fc[lc][S]||N(fc[lc],S,fc[lc].valueOf),ve(fc,cc),nc[ac]=!0,ze("asyncIterator");var Nc,Rc,xc,Pc,Dc,S=z,Oc=D,Mc=c,ve=a.f,U=U,Lc=i.Symbol;!o||"function"!=typeof Lc||"description"in Lc.prototype&&void 0===Lc().description||(Nc={},U(Rc=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),t=this instanceof Rc?new Lc(e):void 0===e?Lc():Lc(e);return""===e&&(Nc[t]=!0),t},Lc),(U=Rc.prototype=Lc.prototype).constructor=Rc,xc=U.toString,Pc="Symbol(test)"==String(Lc("test")),Dc=/^Symbol\((.*)\)[^)]+$/,ve(U,"description",{configurable:!0,get:function(){var e=Mc(this)?this.valueOf():this,t=xc.call(e);if(Oc(Nc,e))return"";t=Pc?t.slice(7,-1):t.replace(Dc,"$1");return""===t?void 0:t}}),S({global:!0,forced:!0},{Symbol:Rc})),ze("hasInstance"),ze("isConcatSpreadable"),ze("iterator"),ze("match"),ze("matchAll"),ze("replace"),ze("search"),ze("species"),ze("split"),ze("toPrimitive"),ze("toStringTag"),ze("unscopables"),tt(Math,"Math",!0),tt(i.JSON,"JSON",!0),yt.Symbol,ze("asyncDispose"),ze("dispose"),ze("observable"),ze("patternMatch"),ze("replaceAll"),Et.f("iterator");function Fc(e){jc(e,Bc,{value:{objectID:"O"+ ++Kc,weakData:{}}})}var ze={exports:{}},Et=!e(function(){return Object.isExtensible(Object.preventExtensions({}))}),ye=ye,Uc=c,qc=D,jc=a.f,Vc=Et,Bc=O("meta"),Kc=0,$c=Object.isExtensible||function(){return!0},Wc=ze.exports={REQUIRED:!1,fastKey:function(e,t){if(!Uc(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!qc(e,Bc)){if(!$c(e))return"F";if(!t)return"E";Fc(e)}return e[Bc].objectID},getWeakData:function(e,t){if(!qc(e,Bc)){if(!$c(e))return!0;if(!t)return!1;Fc(e)}return e[Bc].weakData},onFreeze:function(e){return Vc&&Wc.REQUIRED&&$c(e)&&!qc(e,Bc)&&Fc(e),e}};ye[Bc]=!0;var zc=c,Gc=rt,Hc=z,Qc=i,Yc=V,Jc=Z.exports,Xc=ze.exports,Zc=l.exports,el=Le,tl=c,nl=e,rl=r,il=tt,sl=function(e,t,n){var r,i;return Gc&&"function"==typeof(r=t.constructor)&&r!==n&&zc(i=r.prototype)&&i!==n.prototype&&Gc(e,i),e},tt=function(r,e,t){function n(e){var n=f[e];Jc(f,e,"add"==e?function(e){return n.call(this,0===e?0:e),this}:"delete"==e?function(e){return!(u&&!tl(e))&&n.call(this,0===e?0:e)}:"get"==e?function(e){return u&&!tl(e)?void 0:n.call(this,0===e?0:e)}:"has"==e?function(e){return!(u&&!tl(e))&&n.call(this,0===e?0:e)}:function(e,t){return n.call(this,0===e?0:e,t),this})}var i,s,o,a,c,l=-1!==r.indexOf("Map"),u=-1!==r.indexOf("Weak"),h=l?"set":"add",d=Qc[r],f=d&&d.prototype,p=d,g={};return Yc(r,"function"!=typeof d||!(u||f.forEach&&!nl(function(){(new d).entries().next()})))?(p=t.getConstructor(e,r,l,h),Xc.REQUIRED=!0):Yc(r,!0)&&(s=(i=new p)[h](u?{}:-0,1)!=i,o=nl(function(){i.has(1)}),a=rl(function(e){new d(e)}),c=!u&&nl(function(){for(var e=new d,t=5;t--;)e[h](t,t);return!e.has(-0)}),a||(((p=e(function(e,t){el(e,p,r);var n=sl(new d,e,p);return null!=t&&Zc(t,n[h],n,l),n})).prototype=f).constructor=p),(o||c)&&(n("delete"),n("has"),l&&n("get")),(c||s)&&n(h),u&&f.clear&&delete f.clear),g[r]=p,Hc({global:!0,forced:p!=d},g),il(p,r),u||t.setStrong(p,r,l),p},ol=a.f,al=Qe,cl=Er,ll=Te,ul=Le,hl=l.exports,dl=xt,fl=Ee,pl=o,gl=ze.exports.fastKey,ml=Se.set,vl=Se.getterFor,xt={getConstructor:function(e,n,r,i){function s(e,t,n){var r,i,s=c(e),o=a(e,t);return o?o.value=n:(s.last=o={index:i=gl(t,!0),key:t,value:n,previous:r=s.last,next:void 0,removed:!1},s.first||(s.first=o),r&&(r.next=o),pl?s.size++:e.size++,"F"!==i&&(s.index[i]=o)),e}function a(e,t){var n,r=c(e),i=gl(t);if("F"!==i)return r.index[i];for(n=r.first;n;n=n.next)if(n.key==t)return n}var o=e(function(e,t){ul(e,o,n),ml(e,{type:n,index:al(null),first:void 0,last:void 0,size:0}),pl||(e.size=0),null!=t&&hl(t,e[i],e,r)}),c=vl(n);return cl(o.prototype,{clear:function(){for(var e=c(this),t=e.index,n=e.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete t[n.index],n=n.next;e.first=e.last=void 0,pl?e.size=0:this.size=0},delete:function(e){var t,n,r=c(this),i=a(this,e);return i&&(t=i.next,n=i.previous,delete r.index[i.index],i.removed=!0,n&&(n.next=t),t&&(t.previous=n),r.first==i&&(r.first=t),r.last==i&&(r.last=n),pl?r.size--:this.size--),!!i},forEach:function(e){for(var t,n=c(this),r=ll(e,1<arguments.length?arguments[1]:void 0,3);t=t?t.next:n.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!a(this,e)}}),cl(o.prototype,r?{get:function(e){var t=a(this,e);return t&&t.value},set:function(e,t){return s(this,0===e?0:e,t)}}:{add:function(e){return s(this,e=0===e?0:e,e)}}),pl&&ol(o.prototype,"size",{get:function(){return c(this).size}}),o},setStrong:function(e,t,n){var r=t+" Iterator",i=vl(t),s=vl(r);dl(e,t,function(e,t){ml(this,{type:r,target:e,state:i(e),kind:t,last:void 0})},function(){for(var e=s(this),t=e.kind,n=e.last;n&&n.removed;)n=n.previous;return e.target&&(e.last=n=n?n.next:e.state.first)?"keys"==t?{value:n.key,done:!1}:"values"==t?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:{value:e.target=void 0,done:!0}},n?"entries":"values",!n,!0),fl(t)}};tt("Map",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},xt),yt.Map;var yl=n,_l=Te,wl=l.exports,Ee=function(e){var t,n,r,i,s=arguments.length,o=1<s?arguments[1]:void 0;return yl(this),(t=void 0!==o)&&yl(o),null==e?new this:(n=[],t?(r=0,i=_l(o,2<s?arguments[2]:void 0,2),wl(e,function(e){n.push(i(e,r++))})):wl(e,n.push,n),new this(n))};z({target:"Map",stat:!0},{from:Ee});o=function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];return new this(t)};z({target:"Map",stat:!0},{of:o});var bl=t,Il=n,ze=function(){for(var e,t=bl(this),n=Il(t.delete),r=!0,i=0,s=arguments.length;i<s;i++)e=n.call(t,arguments[i]),r=r&&e;return!!r},Tl=ze;z({target:"Map",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Tl.apply(this,arguments)}});var El=t,Sl=p,Se=function(e){return Map.prototype.entries.call(e)},p=z,kl=t,Cl=Te,Al=Se,Nl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{every:function(e){var n=kl(this),t=Al(n),r=Cl(e,1<arguments.length?arguments[1]:void 0,3);return!Nl(t,function(e,t){if(!r(t,e,n))return Nl.stop()},void 0,!0,!0).stopped}});var p=z,Rl=vt,xl=t,Pl=n,Dl=Te,Ol=R,Ml=Se,Ll=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{filter:function(e){var n=xl(this),t=Ml(n),r=Dl(e,1<arguments.length?arguments[1]:void 0,3),i=new(Ol(n,Rl("Map"))),s=Pl(i.set);return Ll(t,function(e,t){r(t,e,n)&&s.call(i,e,t)},void 0,!0,!0),i}});var p=z,Fl=t,Ul=Te,ql=Se,jl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{find:function(e){var n=Fl(this),t=ql(n),r=Ul(e,1<arguments.length?arguments[1]:void 0,3);return jl(t,function(e,t){if(r(t,e,n))return jl.stop(t)},void 0,!0,!0).result}});var p=z,Vl=t,Bl=Te,Kl=Se,$l=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{findKey:function(e){var n=Vl(this),t=Kl(n),r=Bl(e,1<arguments.length?arguments[1]:void 0,3);return $l(t,function(e,t){if(r(t,e,n))return $l.stop(e)},void 0,!0,!0).result}});var p=z,Wl=l.exports,zl=n;p({target:"Map",stat:!0},{groupBy:function(e,n){var r=new this;zl(n);var i=zl(r.has),s=zl(r.get),o=zl(r.set);return Wl(e,function(e){var t=n(e);i.call(r,t)?s.call(r,t).push(e):o.call(r,t,[e])}),r}});var p=z,Gl=t,Hl=Se,Ql=function(e,t){return e===t||e!=e&&t!=t},Yl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{includes:function(n){return Yl(Hl(Gl(this)),function(e,t){if(Ql(t,n))return Yl.stop()},void 0,!0,!0).stopped}});var p=z,Jl=l.exports,Xl=n;p({target:"Map",stat:!0},{keyBy:function(e,t){var n=new this;Xl(t);var r=Xl(n.set);return Jl(e,function(e){r.call(n,t(e),e)}),n}});var p=z,Zl=t,eu=Se,tu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{keyOf:function(n){return tu(eu(Zl(this)),function(e,t){if(t===n)return tu.stop(e)},void 0,!0,!0).result}});var p=z,nu=vt,ru=t,iu=n,su=Te,ou=R,au=Se,cu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{mapKeys:function(e){var n=ru(this),t=au(n),r=su(e,1<arguments.length?arguments[1]:void 0,3),i=new(ou(n,nu("Map"))),s=iu(i.set);return cu(t,function(e,t){s.call(i,r(t,e,n),t)},void 0,!0,!0),i}});var p=z,lu=vt,uu=t,hu=n,du=Te,fu=R,pu=Se,gu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{mapValues:function(e){var n=uu(this),t=pu(n),r=du(e,1<arguments.length?arguments[1]:void 0,3),i=new(fu(n,lu("Map"))),s=hu(i.set);return gu(t,function(e,t){s.call(i,e,r(t,e,n))},void 0,!0,!0),i}});var p=z,mu=t,vu=n,yu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{merge:function(e){for(var t=mu(this),n=vu(t.set),r=0;r<arguments.length;)yu(arguments[r++],n,t,!0);return t}});var p=z,_u=t,wu=n,bu=Se,Iu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{reduce:function(n){var r=_u(this),e=bu(r),i=arguments.length<2,s=i?void 0:arguments[1];if(wu(n),Iu(e,function(e,t){s=i?(i=!1,t):n(s,t,e,r)},void 0,!0,!0),i)throw TypeError("Reduce of empty map with no initial value");return s}});var p=z,Tu=t,Eu=Te,Su=Se,ku=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{some:function(e){var n=Tu(this),t=Su(n),r=Eu(e,1<arguments.length?arguments[1]:void 0,3);return ku(t,function(e,t){if(r(t,e,n))return ku.stop()},void 0,!0,!0).stopped}});var Cu=t,Au=n;z({target:"Map",proto:!0,real:!0,forced:!1},{update:function(e,t){var n=Cu(this),r=arguments.length;Au(t);var i=n.has(e);if(!i&&r<3)throw TypeError("Updating absent value");r=i?n.get(e):Au(2<r?arguments[2]:void 0)(e,n);return n.set(e,t(r,e,n)),n}});var Nu=t,p=function(e,t){var n,r=Nu(this),i=2<arguments.length?arguments[2]:void 0;if("function"!=typeof t&&"function"!=typeof i)throw TypeError("At least one callback required");return r.has(e)?(n=r.get(e),"function"==typeof t&&(n=t(n),r.set(e,n))):"function"==typeof i&&(n=i(),r.set(e,n)),n};z({target:"Map",proto:!0,real:!0,forced:!1},{upsert:p});z({target:"Map",proto:!0,real:!0,forced:!1},{updateOrInsert:p}),tt("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},xt),yt.Set,z({target:"Set",stat:!0},{from:Ee}),z({target:"Set",stat:!0},{of:o});var Ru=t,xu=n,Pu=function(){for(var e=Ru(this),t=xu(e.add),n=0,r=arguments.length;n<r;n++)t.call(e,arguments[n]);return e};z({target:"Set",proto:!0,real:!0,forced:!1},{addAll:function(){return Pu.apply(this,arguments)}});var Du=ze;z({target:"Set",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Du.apply(this,arguments)}});var o=function(e){return Set.prototype.values.call(e)},ze=z,Ou=t,Mu=Te,Lu=o,Fu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{every:function(e){var t=Ou(this),n=Lu(t),r=Mu(e,1<arguments.length?arguments[1]:void 0,3);return!Fu(n,function(e){if(!r(e,e,t))return Fu.stop()},void 0,!1,!0).stopped}});var ze=z,Uu=vt,qu=t,ju=n,Vu=R,Bu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{difference:function(e){var t=qu(this),n=new(Vu(t,Uu("Set")))(t),r=ju(n.delete);return Bu(e,function(e){r.call(n,e)}),n}});var ze=z,Ku=vt,$u=t,Wu=n,zu=Te,Gu=R,Hu=o,Qu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{filter:function(e){var t=$u(this),n=Hu(t),r=zu(e,1<arguments.length?arguments[1]:void 0,3),i=new(Gu(t,Ku("Set"))),s=Wu(i.add);return Qu(n,function(e){r(e,e,t)&&s.call(i,e)},void 0,!1,!0),i}});var ze=z,Yu=t,Ju=Te,Xu=o,Zu=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{find:function(e){var t=Yu(this),n=Xu(t),r=Ju(e,1<arguments.length?arguments[1]:void 0,3);return Zu(n,function(e){if(r(e,e,t))return Zu.stop(e)},void 0,!1,!0).result}});var ze=z,eh=vt,th=t,nh=n,rh=R,ih=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{intersection:function(e){var t=th(this),n=new(rh(t,eh("Set"))),r=nh(t.has),i=nh(n.add);return ih(e,function(e){r.call(t,e)&&i.call(n,e)}),n}});var ze=z,sh=t,oh=n,ah=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{isDisjointFrom:function(e){var t=sh(this),n=oh(t.has);return!ah(e,function(e){if(!0===n.call(t,e))return ah.stop()}).stopped}});var ze=z,ch=vt,lh=t,uh=n,hh=function(e){var t=Sl(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return El(t.call(e))},dh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{isSubsetOf:function(e){var t=hh(this),n=lh(e),r=n.has;return"function"!=typeof r&&(n=new(ch("Set"))(e),r=uh(n.has)),!dh(t,function(e){if(!1===r.call(n,e))return dh.stop()},void 0,!1,!0).stopped}});var ze=z,fh=t,ph=n,gh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{isSupersetOf:function(e){var t=fh(this),n=ph(t.has);return!gh(e,function(e){if(!1===n.call(t,e))return gh.stop()}).stopped}});var ze=z,mh=t,vh=o,yh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{join:function(e){var t=mh(this),n=vh(t),r=void 0===e?",":String(e),t=[];return yh(n,t.push,t,!1,!0),t.join(r)}});var ze=z,_h=vt,wh=t,bh=n,Ih=Te,Th=R,Eh=o,Sh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{map:function(e){var t=wh(this),n=Eh(t),r=Ih(e,1<arguments.length?arguments[1]:void 0,3),i=new(Th(t,_h("Set"))),s=bh(i.add);return Sh(n,function(e){s.call(i,r(e,e,t))},void 0,!1,!0),i}});var ze=z,kh=t,Ch=n,Ah=o,Nh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{reduce:function(t){var n=kh(this),e=Ah(n),r=arguments.length<2,i=r?void 0:arguments[1];if(Ch(t),Nh(e,function(e){i=r?(r=!1,e):t(i,e,e,n)},void 0,!1,!0),r)throw TypeError("Reduce of empty set with no initial value");return i}});var ze=z,Rh=t,xh=Te,Ph=o,Dh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{some:function(e){var t=Rh(this),n=Ph(t),r=xh(e,1<arguments.length?arguments[1]:void 0,3);return Dh(n,function(e){if(r(e,e,t))return Dh.stop()},void 0,!1,!0).stopped}});var ze=z,Oh=vt,Mh=t,Lh=n,Fh=R,Uh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{symmetricDifference:function(e){var t=Mh(this),n=new(Fh(t,Oh("Set")))(t),r=Lh(n.delete),i=Lh(n.add);return Uh(e,function(e){r.call(n,e)||i.call(n,e)}),n}});var ze=z,qh=vt,jh=t,Vh=n,Bh=R,Kh=l.exports;ze({target:"Set",proto:!0,real:!0,forced:!1},{union:function(e){var t=jh(this),t=new(Bh(t,qh("Set")))(t);return Kh(e,Vh(t.add),t),t}});var $h,Wh,zh=c,Gh=Math.floor;z({target:"Number",stat:!0},{isInteger:function(e){return!zh(e)&&isFinite(e)&&Gh(e)===e}}),yt.Number.isInteger;function Hh(e){var t=Xh(e);return Zh.encodeByteArray(t,!0)}const Qh={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},Yh=function(e,t){if(!e)throw Jh(t)},Jh=function(e){return new Error("Firebase Database ("+Qh.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},Xh=function(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n},Zh={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(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],o=u+1<n.length,a=o?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&a)<<2|l>>6,t=63&l;c||(t=64,o||(e=64)),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(Xh(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,o=e[n++];o<128?t[r++]=String.fromCharCode(o):191<o&&o<224?(i=e[n++],t[r++]=String.fromCharCode((31&o)<<6|63&i)):239<o&&o<365?(s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var o=c<e.length?n[e.charAt(c)]:64;++c;var a=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==o||null==a)throw Error();r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a&&r.push(o<<6&192|a))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},ed=function(e){return Hh(e).replace(/\./g,"")},td=function(e){try{return Zh.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function nd(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=nd(e[r],t[r]));return e}class rd{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function id(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[ed(JSON.stringify({alg:"none",type:"JWT"})),ed(JSON.stringify(i)),""].join(".")}function sd(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function od(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(sd())}function ad(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function cd(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function ld(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function ud(){const e=sd();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function hd(){return!0===Qh.NODE_ADMIN}function dd(){return"object"==typeof indexedDB}function fd(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function pd(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class gd extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,gd.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,md.prototype.create)}}class md{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(vd,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new gd(i,s,n)}}const vd=/\{\$([^}]+)}/g;function yd(e){return JSON.parse(e)}function _d(e){return JSON.stringify(e)}function wd(e){let t={},n={},r={},i="";try{var s=e.split(".");t=yd(td(s[0])||""),n=yd(td(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function bd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Id(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Td(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Ed(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function Sd(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const o of n){if(!r.includes(o))return;var i=e[o],s=t[o];if(kd(i)&&kd(s)){if(!Sd(i,s))return}else if(i!==s)return}for(const a of r)if(!n.includes(a))return;return 1}function kd(e){return null!==e&&"object"==typeof e}function Cd(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function Ad(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function Nd(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class Rd{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,u;for(let f=0;f<80;f++){u=f<40?f<20?(l=a^s&(o^a),1518500249):(l=s^o^a,1859775393):f<60?(l=s&o|a&(s|o),2400959708):(l=s^o^a,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[f]&4294967295;c=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=h}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function xd(e,t){const n=new Pd(e,t);return n.subscribe.bind(n)}class Pd{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=Dd),void 0===r.error&&(r.error=Dd),void 0===r.complete&&(r.complete=Dd);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Dd(){}function Od(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function Md(e,t){return`${e} failed: ${t} argument `}function Ld(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(Md(e,t)+"must be a valid function.")}function Fd(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(Md(e,t)+"must be a valid context object.")}const Ud=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},qd=1e3,jd=2,Vd=144e5,Bd=.5;function Kd(e,t=qd,n=jd){var r=t*Math.pow(n,e),i=Math.round(Bd*r*(Math.random()-.5)*2);return Math.min(Vd,r+i)}function $d(e){return e&&e._delegate?e._delegate:e}function Wd(e,r){return new Promise((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(`${r}: ${null===(t=e.target.error)||void 0===t?void 0:t.message}`)}})}class zd{constructor(e){this._db=e,this.objectStoreNames=this._db.objectStoreNames}transaction(e,t="readonly"){return new Gd(this._db.transaction.call(this._db,e,t))}createObjectStore(e,t){return new Hd(this._db.createObjectStore(e,t))}close(){this._db.close()}}class Gd{constructor(e){this._transaction=e,this.complete=new Promise((e,t)=>{this._transaction.oncomplete=function(){e()},this._transaction.onerror=()=>{t(this._transaction.error)},this._transaction.onabort=()=>{t(this._transaction.error)}})}objectStore(e){return new Hd(this._transaction.objectStore(e))}}class Hd{constructor(e){this._store=e}index(e){return new Qd(this._store.index(e))}createIndex(e,t,n){return new Qd(this._store.createIndex(e,t,n))}get(e){return Wd(this._store.get(e),"Error reading from IndexedDB")}put(e,t){return Wd(this._store.put(e,t),"Error writing to IndexedDB")}delete(e){return Wd(this._store.delete(e),"Error deleting from IndexedDB")}clear(){return Wd(this._store.clear(),"Error clearing IndexedDB object store")}}class Qd{constructor(e){this._index=e}get(e){return Wd(this._index.get(e),"Error reading from IndexedDB")}}function Yd(e,i,s){return new Promise((t,n)=>{try{const r=indexedDB.open(e,i);r.onsuccess=e=>{t(new zd(e.target.result))},r.onerror=e=>{var t;n(`Error opening indexedDB: ${null===(t=e.target.error)||void 0===t?void 0:t.message}`)},r.onupgradeneeded=e=>{s(new zd(r.result),e.oldVersion,e.newVersion,new Gd(r.transaction))}}catch(e){n(`Error opening indexedDB: ${e.message}`)}})}async function Jd(r){return new Promise((e,n)=>{try{const t=indexedDB.deleteDatabase(r);t.onsuccess=()=>{e()},t.onerror=e=>{var t;n(`Error deleting indexedDB database "${r}": ${null===(t=e.target.error)||void 0===t?void 0:t.message}`)}}catch(e){n(`Error deleting indexedDB database "${r}": ${e.message}`)}})}class Xd{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const Zd="[DEFAULT]";class ef{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new rd;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:Zd})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=Zd){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=Zd){return this.instances.has(e)}getOptions(e=Zd){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===Zd?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=Zd){return!this.component||this.component.multipleInstances?e:Zd}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class tf{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new ef(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const nf=[];(Wh=$h=$h||{})[Wh.DEBUG=0]="DEBUG",Wh[Wh.VERBOSE=1]="VERBOSE",Wh[Wh.INFO=2]="INFO",Wh[Wh.WARN=3]="WARN",Wh[Wh.ERROR=4]="ERROR",Wh[Wh.SILENT=5]="SILENT";const rf={debug:$h.DEBUG,verbose:$h.VERBOSE,info:$h.INFO,warn:$h.WARN,error:$h.ERROR,silent:$h.SILENT},sf=$h.INFO,of={[$h.DEBUG]:"log",[$h.VERBOSE]:"log",[$h.INFO]:"info",[$h.WARN]:"warn",[$h.ERROR]:"error"},af=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=of[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class cf{constructor(e){this.name=e,this._logLevel=sf,this._logHandler=af,this._userLogHandler=null,nf.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in $h))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?rf[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,$h.DEBUG,...e),this._logHandler(this,$h.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,$h.VERBOSE,...e),this._logHandler(this,$h.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,$h.INFO,...e),this._logHandler(this,$h.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,$h.WARN,...e),this._logHandler(this,$h.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,$h.ERROR,...e),this._logHandler(this,$h.ERROR,...e)}}class lf{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const uf="@firebase/app",hf=new cf("@firebase/app");var df;const ff="[DEFAULT]",pf={"@firebase/app":"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},gf=new Map,mf=new Map;function vf(t,n){try{t.container.addComponent(n)}catch(e){hf.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function yf(e,t){e.container.addOrOverwriteComponent(t)}function _f(e){var t=e.name;if(mf.has(t))return hf.debug(`There were multiple attempts to register component ${t}.`),!1;mf.set(t,e);for(const n of gf.values())vf(n,e);return!0}function wf(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const bf=new md("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}."});class If{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new Xd("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw bf.create("app-deleted",{appName:this._name})}}const Tf="9.7.0";function Ef(e,t={}){if("object"!=typeof t){const r=t;t={name:r}}var n=Object.assign({name:ff,automaticDataCollectionEnabled:!1},t);const r=n.name;if("string"!=typeof r||!r)throw bf.create("bad-app-name",{appName:String(r)});var i=gf.get(r);if(i){if(Sd(e,i.options)&&Sd(n,i.config))return i;throw bf.create("duplicate-app",{appName:r})}const s=new tf(r);for(const o of mf.values())s.addComponent(o);n=new If(e,n,s);return gf.set(r,n),n}function Sf(e=ff){var t=gf.get(e);if(!t)throw bf.create("no-app",{appName:e});return t}async function kf(e){var t=e.name;gf.has(t)&&(gf.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function Cf(e,t,n){let r=null!==(s=pf[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const o=[`Unable to register library "${r}" with version "${t}":`];return i&&o.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&o.push("and"),s&&o.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void hf.warn(o.join(" "))}_f(new Xd(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function Af(e,t){if(null!==e&&"function"!=typeof e)throw bf.create("invalid-log-argument");!function(s,e){for(const t of nf){let i=null;e&&e.level&&(i=rf[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&s({level:$h[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function Nf(e){var t;t=e,nf.forEach(e=>{e.setLogLevel(t)})}const Rf="firebase-heartbeat-database",xf=1,Pf="firebase-heartbeat-store";let Df=null;function Of(){return Df=Df||Yd(Rf,xf,(e,t)=>{0===t&&e.createObjectStore(Pf)}).catch(e=>{throw bf.create("storage-open",{originalErrorMessage:e.message})}),Df}async function Mf(e,t){try{const n=await Of(),r=n.transaction(Pf,"readwrite"),i=r.objectStore(Pf);return await i.put(t,Lf(e)),r.complete}catch(e){throw bf.create("storage-set",{originalErrorMessage:e.message})}}function Lf(e){return`${e.name}!${e.options.appId}`}class Ff{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new qf(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate();var t=e.getPlatformInfoString();const n=Uf();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";var e=Uf(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const s=n.find(e=>e.agent===i.agent);if(s){if(s.dates.push(i.date),jf(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),jf(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),t=ed(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function Uf(){const e=new Date;return e.toISOString().substring(0,10)}class qf{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!dd()&&fd().then(()=>!0).catch(()=>!1)}async read(){return await this._canUseIndexedDBPromise&&await async function(e){try{const t=await Of();return t.transaction(Pf).objectStore(Pf).get(Lf(e))}catch(e){throw bf.create("storage-get",{originalErrorMessage:e.message})}}(this.app)||{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return Mf(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return Mf(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function jf(e){return ed(JSON.stringify({version:2,heartbeats:e})).length}df="",_f(new Xd("platform-logger",e=>new lf(e),"PRIVATE")),_f(new Xd("heartbeat",e=>new Ff(e),"PRIVATE")),Cf(uf,"0.7.22",df),Cf(uf,"0.7.22","esm2017"),Cf("fire-js","");var Vf=Object.freeze({__proto__:null,SDK_VERSION:Tf,_DEFAULT_ENTRY_NAME:ff,_addComponent:vf,_addOrOverwriteComponent:yf,_apps:gf,_clearComponents:function(){mf.clear()},_components:mf,_getProvider:wf,_registerComponent:_f,_removeServiceInstance:function(e,t,n=ff){wf(e,t).clearInstance(n)},deleteApp:kf,getApp:Sf,getApps:function(){return Array.from(gf.values())},initializeApp:Ef,onLog:Af,registerVersion:Cf,setLogLevel:Nf,FirebaseError:gd});class Bf{constructor(e,t){this._delegate=e,this.firebase=t,vf(e,new Xd("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),kf(this._delegate)))}_getService(e,t=ff){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=ff){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){vf(this._delegate,e)}_addOrOverwriteComponent(e){yf(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Kf=new md("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function $f(i){const s={},o={__esModule:!0,initializeApp:function(e,t={}){var n=Ef(e,t);if(bd(s,n.name))return s[n.name];var r=new i(n,o);return s[n.name]=r},app:a,registerVersion:Cf,setLogLevel:Nf,onLog:Af,apps:null,SDK_VERSION:Tf,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;_f(n)&&"PUBLIC"===n.type&&(e=(e=a())=>{if("function"!=typeof e[t])throw Kf.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&nd(e,n.serviceProps),o[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?o[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:Vf}};function a(e){if(e=e||ff,!bd(s,e))throw Kf.create("no-app",{appName:e});return s[e]}return o.default=o,Object.defineProperty(o,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),a.App=i,o}l=function e(){const t=$f(Bf);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){nd(t,e)},createSubscribe:xd,ErrorFactory:md,deepExtend:nd}),t}();const Wf=new cf("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){Wf.warn(`
2
2
  Warning: Firebase is already defined in the global scope. Please make sure
3
3
  Firebase library is only loaded once.
4
- `);const BK=self.firebase.SDK_VERSION;BK&&0<=BK.indexOf("LITE")&&Wf.warn(`
4
+ `);const zK=self.firebase.SDK_VERSION;zK&&0<=zK.indexOf("LITE")&&Wf.warn(`
5
5
  Warning: You are trying to load Firebase while using Firebase Performance standalone script.
6
6
  You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
7
- `)}const zf=l;Cf("@firebase/app-compat","0.1.22",void 0);zf.registerVersion("firebase","9.6.11","app-compat");ze="@firebase/installations",c="0.5.8";const Gf=1e4,Hf="w:0.5.8",Qf="FIS_v2",Yf="https://firebaseinstallations.googleapis.com/v1",Jf=36e5;const Xf=new md("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Zf(e){return e instanceof gd&&e.code.includes("request-failed")}function ep({projectId:e}){return`${Yf}/projects/${e}/installations`}function tp(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function np(e,t){var n=(await t.json()).error;return Xf.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function rp({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function ip(e,{refreshToken:t}){const n=rp(e);return n.append("Authorization",(t=t,`${Qf} ${t}`)),n}async function sp(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function op(t){return new Promise(e=>{setTimeout(e,t)})}const ap=/^[cdef][\w-]{21}$/,cp="";function lp(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return ap.test(e)?e:cp}catch(e){return cp}}function up(e){return`${e.appName}!${e.appId}`}const hp=new Map;function dp(e,t){var n=up(e);fp(n,t),function(e,t){const n=function(){!pp&&"BroadcastChannel"in self&&(pp=new BroadcastChannel("[Firebase] FID Change"),pp.onmessage=e=>{fp(e.data.key,e.data.fid)});return pp}();n&&n.postMessage({key:e,fid:t});0===hp.size&&pp&&(pp.close(),pp=null)}(n,t)}function fp(e,t){var n=hp.get(e);if(n)for(const r of n)r(t)}let pp=null;const gp="firebase-installations-store";let mp=null;function vp(){return mp=mp||Yd("firebase-installations-database",1,(e,t)=>{0===t&&e.createObjectStore(gp)}),mp}async function yp(e,t){var n=up(e);const r=await vp(),i=r.transaction(gp,"readwrite"),s=i.objectStore(gp);var o=await s.get(n);return await s.put(t,n),await i.complete,o&&o.fid===t.fid||dp(e,t.fid),t}async function _p(e){var t=up(e);const n=await vp(),r=n.transaction(gp,"readwrite");await r.objectStore(gp).delete(t),await r.complete}async function wp(e,t){var n=up(e);const r=await vp(),i=r.transaction(gp,"readwrite"),s=i.objectStore(gp);var o=await s.get(n),a=t(o);return void 0===a?await s.delete(n):await s.put(a,n),await i.complete,!a||o&&o.fid===a.fid||dp(e,a.fid),a}async function bp(n){let r;var e=await wp(n.appConfig,e=>{var t=Tp(e||{fid:lp(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Ip(e.appConfig);for(;1===t.registrationStatus;)await op(100),t=await Ip(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await bp(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Xf.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=ep(e),i=rp(e),s=t.getImmediate({optional:!0});!s||(o=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",o);var o={fid:n,authVersion:Qf,appId:e.appId,sdkVersion:Hf};const a={method:"POST",headers:i,body:JSON.stringify(o)},c=await sp(()=>fetch(r,a));if(c.ok){o=await c.json();return{fid:o.fid||n,registrationStatus:2,refreshToken:o.refreshToken,authToken:tp(o.authToken)}}throw await np("Create Installation",c)}(t,n);return yp(t.appConfig,e)}catch(e){throw Zf(e)&&409===e.customData.serverCode?await _p(t.appConfig):await yp(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===cp?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Ip(e){return wp(e,e=>{if(!e)throw Xf.create("installation-not-found");return Tp(e)})}function Tp(e){return 1===(t=e).registrationStatus&&t.registrationTime+Gf<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function Ep({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${ep(i)}/${s}/authTokens:generate`);var i,s;const o=ip(e,n),a=t.getImmediate({optional:!0});!a||(c=await a.getHeartbeatsHeader())&&o.append("x-firebase-client",c);var c={installation:{sdkVersion:Hf,appId:e.appId}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await sp(()=>fetch(r,l));if(u.ok)return tp(await u.json());throw await np("Generate Auth Token",u)}async function Sp(r,i=!1){let s;var e=await wp(r.appConfig,e=>{if(!Cp(e))throw Xf.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+Jf}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await kp(e.appConfig);for(;1===n.authToken.requestStatus;)await op(100),n=await kp(e.appConfig);var r=n.authToken;return 0===r.requestStatus?Sp(e,t):r}(r,i),e;if(!navigator.onLine)throw Xf.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await Ep(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await yp(t.appConfig,e),r}catch(e){throw!Zf(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await yp(t.appConfig,r)):await _p(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function kp(e){return wp(e,e=>{if(!Cp(e))throw Xf.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Gf<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function Cp(e){return void 0!==e&&2===e.registrationStatus}async function Ap(e,t=!1){var n,r=e;return await((n=(await bp(r)).registrationPromise)&&await n),(await Sp(r,t)).token}function Np(e){return Xf.create("missing-app-config-values",{valueName:e})}const Rp="installations",xp=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw Np("App Configuration");if(!e.name)throw Np("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw Np(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:wf(t,"heartbeat"),_delete:()=>Promise.resolve()}},Pp=e=>{const t=wf(e.getProvider("app").getImmediate(),Rp).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await bp(t);return(r||Sp(t)).catch(console.error),n.fid}(t),getToken:e=>Ap(t,e)}};_f(new Xd(Rp,xp,"PUBLIC")),_f(new Xd("installations-internal",Pp,"PRIVATE")),Cf(ze,c),Cf(ze,c,"esm2017");const Dp="analytics",Op="firebase_id",Mp="origin",Lp="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Fp="https://www.googletagmanager.com/gtag/js",Up=new cf("@firebase/analytics");function qp(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function jp(r,i,s,o){return async function(e,t,n){try{"event"===e?await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await qp(r);for(const l of e){var o=c.find(e=>e.measurementId===l),a=o&&n[o.appId];if(!a){t=[];break}t.push(a)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){Up.error(e)}}(r,i,s,t,n):"config"===e?await async function(e,t,n,r,i,s){var o=r[i];try{if(o)await t[o];else{const c=await qp(n);var a=c.find(e=>e.measurementId===i);a&&await t[a.appId]}}catch(e){Up.error(e)}e("config",i,s)}(r,i,s,o,t,n):r("set",t)}catch(e){Up.error(e)}}}const Vp=new md("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Bp=30;const Kp=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function $p(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=Lp.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw Vp.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Wp(e,t=Kp,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Vp.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Vp.create("no-api-key")}var o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const a=new Hp;return setTimeout(async()=>{a.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=Kp){const{appId:o,measurementId:a}=n;try{await zp(i,e)}catch(e){if(a)return Up.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${a}`+` provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:o,measurementId:a};throw e}try{const c=await $p(n);return s.deleteThrottleMetadata(o),c}catch(e){if(!Gp(e)){if(s.deleteThrottleMetadata(o),a)return Up.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${a}`+` provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:o,measurementId:a};throw e}const l=503===Number(e.customData.httpStatus)?Kd(r,s.intervalMillis,Bp):Kd(r,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:r+1};return s.setThrottleMetadata(o,u),Up.debug(`Calling attemptFetch again in ${l} millis`),t(n,u,i,s)}}({appId:r,apiKey:i,measurementId:s},o,a,t)}function zp(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(Vp.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function Gp(e){if(!(e instanceof gd&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class Hp{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Qp(t,e,n,r,i,s,o){const a=Wp(t);a.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Up.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>Up.error(e)),e.push(a);var c=async function(){if(!dd())return Up.warn(Vp.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await fd()}catch(e){return Up.warn(Vp.create("indexeddb-unavailable",{errorInfo:e}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([a,c]);!function(){var e=window.document.getElementsByTagName("script");for(const t of Object.values(e))if(t.src&&t.src.includes(Fp))return t}()&&function(e,t){const n=document.createElement("script");n.src=`${Fp}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const h=null!==(c=null==o?void 0:o.config)&&void 0!==c?c:{};return h[Mp]="firebase",h.update=!0,null!=u&&(h[Op]=u),i("config",l.measurementId,h),l.measurementId}class Yp{constructor(e){this.app=e}_delete(){return delete Jp[this.app.options.appId],Promise.resolve()}}let Jp={},Xp=[];const Zp={};let eg="dataLayer",tg="gtag",ng,rg,ig=!1;function sg(e){if(ig)throw Vp.create("already-initialized");e.dataLayerName&&(eg=e.dataLayerName),e.gtagName&&(tg=e.gtagName)}function og(e,t,n){!function(){const e=[];var t;cd()&&e.push("This is a browser extension environment."),pd()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Vp.create("invalid-analytics-context",{errorInfo:t}),Up.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw Vp.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Vp.create("no-api-key");Up.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=Jp[s])throw Vp.create("already-exists",{id:s});return ig||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(eg),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=jp(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Jp,Xp,Zp,eg,tg),rg=r,ng=i,ig=!0),Jp[s]=Qp(e,Xp,Zp,t,ng,eg,n),new Yp(e)}async function ag(){if(cd())return!1;if(!pd())return!1;if(!dd())return!1;try{return await fd()}catch(e){return!1}}function cg(e,t,n){e=$d(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(rg,Jp[e.app.options.appId],t,n).catch(e=>Up.error(e))}function lg(e,t,n){e=$d(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(rg,Jp[e.app.options.appId],t,n).catch(e=>Up.error(e))}function ug(e,t,n){e=$d(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(rg,Jp[e.app.options.appId],t,n).catch(e=>Up.error(e))}function hg(e,t){e=$d(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Jp[e.app.options.appId],t).catch(e=>Up.error(e))}function dg(e,t,n,r){e=$d(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(rg,Jp[e.app.options.appId],t,n,r).catch(e=>Up.error(e))}const fg="@firebase/analytics";_f(new Xd(Dp,(e,{options:t})=>{return og(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),_f(new Xd("analytics-internal",function(e){try{const r=e.getProvider(Dp).getImmediate();return{logEvent:(e,t,n)=>dg(r,e,t,n)}}catch(e){throw Vp.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),Cf(fg,"0.7.8"),Cf(fg,"0.7.8","esm2017");var pg,gg;class mg{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){dg(this._delegate,e,t,n)}setCurrentScreen(e,t){cg(this._delegate,e,t)}setUserId(e,t){lg(this._delegate,e,t)}setUserProperties(e,t){ug(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){hg(this._delegate,e)}}(z=pg=pg||{}).ADD_SHIPPING_INFO="add_shipping_info",z.ADD_PAYMENT_INFO="add_payment_info",z.ADD_TO_CART="add_to_cart",z.ADD_TO_WISHLIST="add_to_wishlist",z.BEGIN_CHECKOUT="begin_checkout",z.CHECKOUT_PROGRESS="checkout_progress",z.EXCEPTION="exception",z.GENERATE_LEAD="generate_lead",z.LOGIN="login",z.PAGE_VIEW="page_view",z.PURCHASE="purchase",z.REFUND="refund",z.REMOVE_FROM_CART="remove_from_cart",z.SCREEN_VIEW="screen_view",z.SEARCH="search",z.SELECT_CONTENT="select_content",z.SELECT_ITEM="select_item",z.SELECT_PROMOTION="select_promotion",z.SET_CHECKOUT_OPTION="set_checkout_option",z.SHARE="share",z.SIGN_UP="sign_up",z.TIMING_COMPLETE="timing_complete",z.VIEW_CART="view_cart",z.VIEW_ITEM="view_item",z.VIEW_ITEM_LIST="view_item_list",z.VIEW_PROMOTION="view_promotion",z.VIEW_SEARCH_RESULTS="view_search_results";const vg=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new mg(t,n)};gg={Analytics:mg,settings:sg,isSupported:ag,EventName:pg},zf.INTERNAL.registerComponent(new Xd("analytics-compat",vg,"PUBLIC").setServiceProps(gg).setMultipleInstances(!0)),zf.registerVersion("@firebase/analytics-compat","0.1.9");const yg=new Map,_g={activated:!1,tokenObservers:[]},wg={initialized:!1,enabled:!1};function bg(e){return yg.get(e)||_g}function Ig(e,t){yg.set(e,t)}const Tg="https://content-firebaseappcheck.googleapis.com/v1beta",Eg="exchangeDebugToken",Sg={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class kg{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new rd,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new rd,await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const Cg=new md("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function Ag(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function Ng(e){if(!bg(e).activated)throw Cg.create("use-before-activation",{appName:e.name})}function Rg(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=xg(n)+"d:"),r&&(s+=xg(r)+"h:"),s+=xg(i)+"m:"+xg(t)+"s",s}function xg(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Pg({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});!i||(c=await i.getHeartbeatsHeader())&&(r["X-Firebase-Client"]=c);var s={method:"POST",body:JSON.stringify(t),headers:r};let o;try{o=await fetch(e,s)}catch(e){throw Cg.create("fetch-network-error",{originalErrorMessage:e.message})}if(200!==o.status)throw Cg.create("fetch-status-error",{httpStatus:o.status});let a;try{a=await o.json()}catch(e){throw Cg.create("fetch-parse-error",{originalErrorMessage:e.message})}var c=a.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw Cg.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${a.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:a.attestationToken,expireTimeMillis:c+s,issuedAtTimeMillis:c}}const Dg="firebase-app-check-database",Og=1,Mg="firebase-app-check-store",Lg="debug-token";let Fg=null;function Ug(){return Fg||(Fg=new Promise((t,n)=>{try{const e=indexedDB.open(Dg,Og);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(Cg.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(Mg,{keyPath:"compositeKey"})}}catch(e){n(Cg.create("storage-open",{originalErrorMessage:e.message}))}}),Fg)}async function qg(e,t){const n=await Ug(),r=n.transaction(Mg,"readwrite"),i=r.objectStore(Mg),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(Cg.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function jg(e){const t=await Ug(),i=t.transaction(Mg,"readonly"),n=i.objectStore(Mg),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(Cg.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function Vg(e){return`${e.options.appId}-${e.name}`}const Bg=new cf("@firebase/app-check");async function Kg(t){if(dd()){let e=void 0;try{e=await jg(Vg(t))}catch(e){Bg.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function $g(e,t){return dd()?qg(Vg(e),t).catch(e=>{Bg.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Wg(){let e=void 0;try{e=await jg(Lg)}catch(e){}if(e)return e;var t,n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)});return t=n,qg(Lg,t).catch(e=>Bg.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function zg(){return wg.enabled}async function Gg(){var e=wg;if(e.enabled&&e.token)return e.token.promise;throw Error(`
7
+ `)}const zf=l;Cf("@firebase/app-compat","0.1.23",void 0);zf.registerVersion("firebase","9.7.0","app-compat");ze="@firebase/installations",c="0.5.8";const Gf=1e4,Hf="w:0.5.8",Qf="FIS_v2",Yf="https://firebaseinstallations.googleapis.com/v1",Jf=36e5;const Xf=new md("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Zf(e){return e instanceof gd&&e.code.includes("request-failed")}function ep({projectId:e}){return`${Yf}/projects/${e}/installations`}function tp(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function np(e,t){var n=(await t.json()).error;return Xf.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function rp({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function ip(e,{refreshToken:t}){const n=rp(e);return n.append("Authorization",(t=t,`${Qf} ${t}`)),n}async function sp(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function op(t){return new Promise(e=>{setTimeout(e,t)})}const ap=/^[cdef][\w-]{21}$/,cp="";function lp(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return ap.test(e)?e:cp}catch(e){return cp}}function up(e){return`${e.appName}!${e.appId}`}const hp=new Map;function dp(e,t){var n=up(e);fp(n,t),function(e,t){const n=function(){!pp&&"BroadcastChannel"in self&&(pp=new BroadcastChannel("[Firebase] FID Change"),pp.onmessage=e=>{fp(e.data.key,e.data.fid)});return pp}();n&&n.postMessage({key:e,fid:t});0===hp.size&&pp&&(pp.close(),pp=null)}(n,t)}function fp(e,t){var n=hp.get(e);if(n)for(const r of n)r(t)}let pp=null;const gp="firebase-installations-store";let mp=null;function vp(){return mp=mp||Yd("firebase-installations-database",1,(e,t)=>{0===t&&e.createObjectStore(gp)}),mp}async function yp(e,t){var n=up(e);const r=await vp(),i=r.transaction(gp,"readwrite"),s=i.objectStore(gp);var o=await s.get(n);return await s.put(t,n),await i.complete,o&&o.fid===t.fid||dp(e,t.fid),t}async function _p(e){var t=up(e);const n=await vp(),r=n.transaction(gp,"readwrite");await r.objectStore(gp).delete(t),await r.complete}async function wp(e,t){var n=up(e);const r=await vp(),i=r.transaction(gp,"readwrite"),s=i.objectStore(gp);var o=await s.get(n),a=t(o);return void 0===a?await s.delete(n):await s.put(a,n),await i.complete,!a||o&&o.fid===a.fid||dp(e,a.fid),a}async function bp(n){let r;var e=await wp(n.appConfig,e=>{var t=Tp(e||{fid:lp(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Ip(e.appConfig);for(;1===t.registrationStatus;)await op(100),t=await Ip(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await bp(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Xf.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=ep(e),i=rp(e),s=t.getImmediate({optional:!0});!s||(o=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",o);var o={fid:n,authVersion:Qf,appId:e.appId,sdkVersion:Hf};const a={method:"POST",headers:i,body:JSON.stringify(o)},c=await sp(()=>fetch(r,a));if(c.ok){o=await c.json();return{fid:o.fid||n,registrationStatus:2,refreshToken:o.refreshToken,authToken:tp(o.authToken)}}throw await np("Create Installation",c)}(t,n);return yp(t.appConfig,e)}catch(e){throw Zf(e)&&409===e.customData.serverCode?await _p(t.appConfig):await yp(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===cp?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Ip(e){return wp(e,e=>{if(!e)throw Xf.create("installation-not-found");return Tp(e)})}function Tp(e){return 1===(t=e).registrationStatus&&t.registrationTime+Gf<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function Ep({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${ep(i)}/${s}/authTokens:generate`);var i,s;const o=ip(e,n),a=t.getImmediate({optional:!0});!a||(c=await a.getHeartbeatsHeader())&&o.append("x-firebase-client",c);var c={installation:{sdkVersion:Hf,appId:e.appId}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await sp(()=>fetch(r,l));if(u.ok)return tp(await u.json());throw await np("Generate Auth Token",u)}async function Sp(r,i=!1){let s;var e=await wp(r.appConfig,e=>{if(!Cp(e))throw Xf.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+Jf}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await kp(e.appConfig);for(;1===n.authToken.requestStatus;)await op(100),n=await kp(e.appConfig);var r=n.authToken;return 0===r.requestStatus?Sp(e,t):r}(r,i),e;if(!navigator.onLine)throw Xf.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await Ep(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await yp(t.appConfig,e),r}catch(e){throw!Zf(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await yp(t.appConfig,r)):await _p(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function kp(e){return wp(e,e=>{if(!Cp(e))throw Xf.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Gf<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function Cp(e){return void 0!==e&&2===e.registrationStatus}async function Ap(e,t=!1){var n,r=e;return await((n=(await bp(r)).registrationPromise)&&await n),(await Sp(r,t)).token}function Np(e){return Xf.create("missing-app-config-values",{valueName:e})}const Rp="installations",xp=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw Np("App Configuration");if(!e.name)throw Np("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw Np(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:wf(t,"heartbeat"),_delete:()=>Promise.resolve()}},Pp=e=>{const t=wf(e.getProvider("app").getImmediate(),Rp).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await bp(t);return(r||Sp(t)).catch(console.error),n.fid}(t),getToken:e=>Ap(t,e)}};_f(new Xd(Rp,xp,"PUBLIC")),_f(new Xd("installations-internal",Pp,"PRIVATE")),Cf(ze,c),Cf(ze,c,"esm2017");const Dp="analytics",Op="firebase_id",Mp="origin",Lp="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Fp="https://www.googletagmanager.com/gtag/js",Up=new cf("@firebase/analytics");function qp(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function jp(r,i,s,o){return async function(e,t,n){try{"event"===e?await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await qp(r);for(const l of e){var o=c.find(e=>e.measurementId===l),a=o&&n[o.appId];if(!a){t=[];break}t.push(a)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){Up.error(e)}}(r,i,s,t,n):"config"===e?await async function(e,t,n,r,i,s){var o=r[i];try{if(o)await t[o];else{const c=await qp(n);var a=c.find(e=>e.measurementId===i);a&&await t[a.appId]}}catch(e){Up.error(e)}e("config",i,s)}(r,i,s,o,t,n):r("set",t)}catch(e){Up.error(e)}}}const Vp=new md("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Bp=30;const Kp=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function $p(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=Lp.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw Vp.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Wp(e,t=Kp,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Vp.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Vp.create("no-api-key")}var o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const a=new Hp;return setTimeout(async()=>{a.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=Kp){const{appId:o,measurementId:a}=n;try{await zp(i,e)}catch(e){if(a)return Up.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${a}`+` provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:o,measurementId:a};throw e}try{const c=await $p(n);return s.deleteThrottleMetadata(o),c}catch(e){if(!Gp(e)){if(s.deleteThrottleMetadata(o),a)return Up.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${a}`+` provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:o,measurementId:a};throw e}const l=503===Number(e.customData.httpStatus)?Kd(r,s.intervalMillis,Bp):Kd(r,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:r+1};return s.setThrottleMetadata(o,u),Up.debug(`Calling attemptFetch again in ${l} millis`),t(n,u,i,s)}}({appId:r,apiKey:i,measurementId:s},o,a,t)}function zp(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(Vp.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function Gp(e){if(!(e instanceof gd&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class Hp{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Qp(t,e,n,r,i,s,o){const a=Wp(t);a.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Up.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>Up.error(e)),e.push(a);var c=async function(){if(!dd())return Up.warn(Vp.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await fd()}catch(e){return Up.warn(Vp.create("indexeddb-unavailable",{errorInfo:e}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([a,c]);!function(){var e=window.document.getElementsByTagName("script");for(const t of Object.values(e))if(t.src&&t.src.includes(Fp))return t}()&&function(e,t){const n=document.createElement("script");n.src=`${Fp}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const h=null!==(c=null==o?void 0:o.config)&&void 0!==c?c:{};return h[Mp]="firebase",h.update=!0,null!=u&&(h[Op]=u),i("config",l.measurementId,h),l.measurementId}class Yp{constructor(e){this.app=e}_delete(){return delete Jp[this.app.options.appId],Promise.resolve()}}let Jp={},Xp=[];const Zp={};let eg="dataLayer",tg="gtag",ng,rg,ig=!1;function sg(e){if(ig)throw Vp.create("already-initialized");e.dataLayerName&&(eg=e.dataLayerName),e.gtagName&&(tg=e.gtagName)}function og(e,t,n){!function(){const e=[];var t;cd()&&e.push("This is a browser extension environment."),pd()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Vp.create("invalid-analytics-context",{errorInfo:t}),Up.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw Vp.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Vp.create("no-api-key");Up.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=Jp[s])throw Vp.create("already-exists",{id:s});return ig||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(eg),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=jp(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Jp,Xp,Zp,eg,tg),rg=r,ng=i,ig=!0),Jp[s]=Qp(e,Xp,Zp,t,ng,eg,n),new Yp(e)}async function ag(){if(cd())return!1;if(!pd())return!1;if(!dd())return!1;try{return await fd()}catch(e){return!1}}function cg(e,t,n){e=$d(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(rg,Jp[e.app.options.appId],t,n).catch(e=>Up.error(e))}function lg(e,t,n){e=$d(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(rg,Jp[e.app.options.appId],t,n).catch(e=>Up.error(e))}function ug(e,t,n){e=$d(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(rg,Jp[e.app.options.appId],t,n).catch(e=>Up.error(e))}function hg(e,t){e=$d(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Jp[e.app.options.appId],t).catch(e=>Up.error(e))}function dg(e,t,n,r){e=$d(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(rg,Jp[e.app.options.appId],t,n,r).catch(e=>Up.error(e))}const fg="@firebase/analytics";_f(new Xd(Dp,(e,{options:t})=>{return og(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),_f(new Xd("analytics-internal",function(e){try{const r=e.getProvider(Dp).getImmediate();return{logEvent:(e,t,n)=>dg(r,e,t,n)}}catch(e){throw Vp.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),Cf(fg,"0.7.8"),Cf(fg,"0.7.8","esm2017");var pg,gg;class mg{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){dg(this._delegate,e,t,n)}setCurrentScreen(e,t){cg(this._delegate,e,t)}setUserId(e,t){lg(this._delegate,e,t)}setUserProperties(e,t){ug(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){hg(this._delegate,e)}}(z=pg=pg||{}).ADD_SHIPPING_INFO="add_shipping_info",z.ADD_PAYMENT_INFO="add_payment_info",z.ADD_TO_CART="add_to_cart",z.ADD_TO_WISHLIST="add_to_wishlist",z.BEGIN_CHECKOUT="begin_checkout",z.CHECKOUT_PROGRESS="checkout_progress",z.EXCEPTION="exception",z.GENERATE_LEAD="generate_lead",z.LOGIN="login",z.PAGE_VIEW="page_view",z.PURCHASE="purchase",z.REFUND="refund",z.REMOVE_FROM_CART="remove_from_cart",z.SCREEN_VIEW="screen_view",z.SEARCH="search",z.SELECT_CONTENT="select_content",z.SELECT_ITEM="select_item",z.SELECT_PROMOTION="select_promotion",z.SET_CHECKOUT_OPTION="set_checkout_option",z.SHARE="share",z.SIGN_UP="sign_up",z.TIMING_COMPLETE="timing_complete",z.VIEW_CART="view_cart",z.VIEW_ITEM="view_item",z.VIEW_ITEM_LIST="view_item_list",z.VIEW_PROMOTION="view_promotion",z.VIEW_SEARCH_RESULTS="view_search_results";const vg=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new mg(t,n)};gg={Analytics:mg,settings:sg,isSupported:ag,EventName:pg},zf.INTERNAL.registerComponent(new Xd("analytics-compat",vg,"PUBLIC").setServiceProps(gg).setMultipleInstances(!0)),zf.registerVersion("@firebase/analytics-compat","0.1.9");const yg=new Map,_g={activated:!1,tokenObservers:[]},wg={initialized:!1,enabled:!1};function bg(e){return yg.get(e)||_g}function Ig(e,t){yg.set(e,t)}const Tg="https://content-firebaseappcheck.googleapis.com/v1",Eg="exchangeDebugToken",Sg={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class kg{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new rd,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new rd,await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const Cg=new md("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function Ag(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function Ng(e){if(!bg(e).activated)throw Cg.create("use-before-activation",{appName:e.name})}function Rg(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=xg(n)+"d:"),r&&(s+=xg(r)+"h:"),s+=xg(i)+"m:"+xg(t)+"s",s}function xg(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Pg({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});!i||(c=await i.getHeartbeatsHeader())&&(r["X-Firebase-Client"]=c);var s={method:"POST",body:JSON.stringify(t),headers:r};let o;try{o=await fetch(e,s)}catch(e){throw Cg.create("fetch-network-error",{originalErrorMessage:e.message})}if(200!==o.status)throw Cg.create("fetch-status-error",{httpStatus:o.status});let a;try{a=await o.json()}catch(e){throw Cg.create("fetch-parse-error",{originalErrorMessage:e.message})}var c=a.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw Cg.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${a.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:a.token,expireTimeMillis:c+s,issuedAtTimeMillis:c}}const Dg="firebase-app-check-database",Og=1,Mg="firebase-app-check-store",Lg="debug-token";let Fg=null;function Ug(){return Fg||(Fg=new Promise((t,n)=>{try{const e=indexedDB.open(Dg,Og);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(Cg.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(Mg,{keyPath:"compositeKey"})}}catch(e){n(Cg.create("storage-open",{originalErrorMessage:e.message}))}}),Fg)}async function qg(e,t){const n=await Ug(),r=n.transaction(Mg,"readwrite"),i=r.objectStore(Mg),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(Cg.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function jg(e){const t=await Ug(),i=t.transaction(Mg,"readonly"),n=i.objectStore(Mg),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(Cg.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function Vg(e){return`${e.options.appId}-${e.name}`}const Bg=new cf("@firebase/app-check");async function Kg(t){if(dd()){let e=void 0;try{e=await jg(Vg(t))}catch(e){Bg.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function $g(e,t){return dd()?qg(Vg(e),t).catch(e=>{Bg.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Wg(){let e=void 0;try{e=await jg(Lg)}catch(e){}if(e)return e;var t,n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)});return t=n,qg(Lg,t).catch(e=>Bg.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function zg(){return wg.enabled}async function Gg(){var e=wg;if(e.enabled&&e.token)return e.token.promise;throw Error(`
8
8
  Can't get debug token in production mode.
9
- `)}function Hg(){var e=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}();const t=wg;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new rd;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Wg())}}const Qg={error:"UNKNOWN_ERROR"};async function Yg(e,t=!1){var n=e.app;Ng(n);const r=bg(n);let i=r.token,s=void 0;if(i||(a=await r.cachedTokenPromise)&&tm(a)&&(i=a),!t&&i&&tm(i))return{token:i.token};let o=!1;if(zg()){r.exchangeTokenPromise||(r.exchangeTokenPromise=Pg(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${Tg}/projects/${n}/apps/${r}:${Eg}?key=${i}`,body:{debug_token:t}}}(n,await Gg()),e.heartbeatServiceProvider).then(e=>(r.exchangeTokenPromise=void 0,e)),o=!0);var a=await r.exchangeTokenPromise;return await $g(n,a),Ig(n,Object.assign(Object.assign({},r),{token:a})),{token:a.token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().then(e=>(r.exchangeTokenPromise=void 0,e)),o=!0),i=await r.exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?Bg.warn(e.message):Bg.error(e),s=e}let c;return i?(c={token:i.token},Ig(n,Object.assign(Object.assign({},r),{token:i})),await $g(n,i)):c=(e=s,{token:function(e){return Zh.encodeString(JSON.stringify(e),!1)}(Qg),error:e}),o&&em(n,c),c}function Jg(e,t,n,r){var i=e["app"];const s=bg(i);var o={next:n,error:r,type:t};if(Ig(i,Object.assign(Object.assign({},s),{tokenObservers:[...s.tokenObservers,o]})),s.token&&tm(s.token)){const a=s.token;Promise.resolve().then(()=>{n({token:a.token}),Zg(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Zg(e))}function Xg(e,t){const n=bg(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),Ig(e,Object.assign(Object.assign({},n),{tokenObservers:r}))}function Zg(e){var t=e["app"],n=bg(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new kg(async()=>{var e=bg(r);let t;if(t=e.token?await Yg(n,!0):await Yg(n),t.error)throw t.error},()=>!0,()=>{var e=bg(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},Sg.RETRIAL_MIN_WAIT,Sg.RETRIAL_MAX_WAIT)}(e),Ig(t,Object.assign(Object.assign({},n),{tokenRefresher:r}))),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function em(e,t){for(const n of bg(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function tm(e){return 0<e.expireTimeMillis-Date.now()}class nm{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=bg(this.app)["tokenObservers"];for(const t of e)Xg(this.app,t.next);return Promise.resolve()}}const rm="https://www.google.com/recaptcha/api.js",im="https://www.google.com/recaptcha/enterprise.js";function sm(t,n){var e=bg(t);const r=new rd;Ig(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=cm(t);e=Ag(!1);return e?am(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=rm,t.onload=e,document.head.appendChild(t)}(()=>{var e=Ag(!1);if(!e)throw new Error("no recaptcha");am(t,n,e,i,r)}),r.promise}function om(t,n){var e=bg(t);const r=new rd;Ig(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=cm(t);e=Ag(!0);return e?am(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=im,t.onload=e,document.head.appendChild(t)}(()=>{var e=Ag(!0);if(!e)throw new Error("no recaptcha");am(t,n,e,i,r)}),r.promise}function am(r,i,s,o,a){s.ready(()=>{var e,t,n;e=r,t=s.render(o,{sitekey:i,size:"invisible"}),n=bg(e),Ig(e,Object.assign(Object.assign({},n),{reCAPTCHAState:Object.assign(Object.assign({},n.reCAPTCHAState),{widgetId:t})})),a.resolve(s)})}function cm(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function lm(r){Ng(r);const i=await bg(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=bg(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class um{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){pm(this._throttleData);var t=await lm(this._app).catch(e=>{throw Cg.create("recaptcha-error")});let e;try{e=await Pg(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${Tg}/projects/${n}/apps/${r}:exchangeRecaptchaToken?key=${i}`,body:{recaptcha_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw"fetch-status-error"===e.code?(this._throttleData=fm(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),Cg.create("throttled",{time:Rg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=wf(e,"heartbeat"),sm(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof um&&this._siteKey===e._siteKey}}class hm{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){pm(this._throttleData);var t=await lm(this._app).catch(e=>{throw Cg.create("recaptcha-error")});let e;try{e=await Pg(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${Tg}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw"fetch-status-error"===e.code?(this._throttleData=fm(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),Cg.create("throttled",{time:Rg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=wf(e,"heartbeat"),om(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof hm&&this._siteKey===e._siteKey}}class dm{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=wd(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof dm&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function fm(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=Kd(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function pm(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw Cg.create("throttled",{time:Rg(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function gm(e=Sf(),t){const n=wf(e=$d(e),"app-check");if(wg.initialized||Hg(),zg()&&Gg().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw Cg.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=bg(t),i=Object.assign(Object.assign({},r),{activated:!0});i.provider=e,i.cachedTokenPromise=Kg(t).then(e=>(e&&tm(e)&&(Ig(t,Object.assign(Object.assign({},bg(t)),{token:e})),em(t,{token:e.token})),e)),i.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,Ig(t,i),i.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),bg(e).isTokenAutoRefreshEnabled&&Jg(r,"INTERNAL",()=>{}),r}const mm="app-check-internal";_f(new Xd("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new nm(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(mm).initialize()})),_f(new Xd(mm,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>Yg(t,e),addTokenListener:e=>Jg(t,"INTERNAL",e),removeTokenListener:e=>Xg(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),Cf("@firebase/app-check","0.5.6");const vm=new md("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class ym{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new um(e):e instanceof hm||e instanceof um||e instanceof dm?e:new dm({getToken:e.getToken}),this._delegate=gm(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw vm.create("use-before-activation",{appName:this.app.name});!function(e,t){var n=e.app;const r=bg(n);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),Ig(n,Object.assign(Object.assign({},r),{isTokenAutoRefreshEnabled:t}))}(this._delegate,e)}getToken(e){if(!this._delegate)throw vm.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Yg(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw vm.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Jg(e,"EXTERNAL",r,i),()=>Xg(e.app,r)}(this._delegate,e,t)}}const _m=e=>{var t=e.getProvider("app-compat").getImmediate();return new ym(t)};function wm(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}zf.INTERNAL.registerComponent(new Xd("appCheck-compat",_m,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:hm,ReCaptchaV3Provider:um,CustomProvider:dm})),zf.registerVersion("@firebase/app-check-compat","0.2.6");const bm={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},Im={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function Tm(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}function Em(){return{"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.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"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 AuthError 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 AuthError 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 to 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-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","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-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","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 AuthError 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 request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","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.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","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 AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError 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.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","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-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","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.","unverified-email":"The operation requires a verified email.","user-cancelled":"The 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.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance."}}const Sm=Tm,km=new md("auth","Firebase",Tm()),Cm=new cf("@firebase/auth");function Am(e,...t){Cm.logLevel<=$h.ERROR&&Cm.error(`Auth (${Tf}): ${e}`,...t)}function Nm(e,...t){throw Dm(e,...t)}function Rm(e,...t){return Dm(e,...t)}function xm(e,t,n){var r=Object.assign(Object.assign({},Sm()),{[t]:n});const i=new md("auth","Firebase",r);return i.create(t,{appName:e.name})}function Pm(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&Nm(e,"argument-error"),xm(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Dm(e,...t){if("string"==typeof e)return km.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function Om(e,t,...n){if(!e)throw Dm(t,...n)}function Mm(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Am(t),new Error(t)}function Lm(e,t){e||Mm(t)}const Fm=new Map;function Um(e){Lm(e instanceof Function,"Expected a class definition");let t=Fm.get(e);return t?Lm(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Fm.set(e,t)),t}function qm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function jm(){return"http:"===Vm()||"https:"===Vm()}function Vm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Bm{constructor(e,t){Lm((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=od()||ld()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(jm()||cd()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Km(e,t){Lm(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class $m{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void Mm("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:void Mm("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:void Mm("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Wm={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error"},zm=new Bm(3e4,6e4);function Gm(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Hm(i,s,o,a,e={}){return Qm(i,e,async()=>{let e={},t={};a&&("GET"===s?t=a:e={body:JSON.stringify(a)});var n=Cd(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),$m.fetch()(Jm(i,i.config.apiHost,o,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Qm(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Wm),e);try{const o=new Xm(t),a=await Promise.race([n(),o.promise]);o.clearNetworkTimeout();var i=await a.json();if("needConfirmation"in i)throw Zm(t,"account-exists-with-different-credential",i);if(a.ok&&!("errorMessage"in i))return i;{const c=a.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Zm(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Zm(t,"email-already-in-use",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw xm(t,s,u);Nm(t,s)}}catch(e){if(e instanceof gd)throw e;Nm(t,"network-request-failed")}}async function Ym(e,t,n,r,i={}){var s=await Hm(e,t,n,r,i);return"mfaPendingCredential"in s&&Nm(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Jm(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?Km(e.config,i):`${e.config.apiScheme}://${i}`}class Xm{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Rm(this.auth,"network-request-failed")),zm.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Zm(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Rm(e,t,r);return i.customData._tokenResponse=n,i}function ev(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function tv(e){return 1e3*Number(e)}function nv(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return Am("JWT malformed, contained fewer than 3 sections"),null;try{var i=td(n);return i?JSON.parse(i):(Am("Failed to decode base64 JWT payload"),null)}catch(e){return Am("Caught error parsing JWT payload as JSON",e),null}}async function rv(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof gd&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class iv{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,t)}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e.code&&this.schedule(!0))}this.schedule()}}class sv{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=ev(this.lastLoginAt),this.creationTime=ev(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function ov(e){var t=e.auth,n=await e.getIdToken(),r=await rv(e,async function(e,t){return Hm(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));Om(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,o,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=wm(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,o=t,[...s.filter(t=>!o.some(e=>e.providerId===t.providerId)),...o]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new sv(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class av{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Om(e.idToken,"internal-error"),Om(void 0!==e.idToken,"internal-error"),Om(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,Om(n=nv(t),"internal-error"),Om(void 0!==n.exp,"internal-error"),Om(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return Om(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:o}=(s=t,await{accessToken:(o=await Qm(i=e,{},async()=>{var e=Cd({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=Jm(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",$m.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:o.expires_in,refreshToken:o.refresh_token});this.updateTokensAndExpiration(n,r,Number(o))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new av;return n&&(Om("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(Om("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(Om("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new av,this.toJSON())}_performRefresh(){return Mm("not implemented")}}function cv(e,t){Om("string"==typeof e||void 0===e,"internal-error",{appName:t})}class lv{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=wm(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new iv(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new sv(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await rv(this,this.stsTokenManager.getToken(this.auth,e));return Om(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=$d(e);var r=await n.getIdToken(t),i=nv(r);Om(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:ev(tv(i.auth_time)),issuedAtTime:ev(tv(i.iat)),expirationTime:ev(tv(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=$d(e);await ov(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Om(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){return new lv(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){Om(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await ov(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await rv(this,async function(e,t){return Hm(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n=null!==(o=t.displayName)&&void 0!==o?o:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(a=t.phoneNumber)&&void 0!==a?a:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,o=null!==(c=t.tenantId)&&void 0!==c?c:void 0,a=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:f,stsTokenManager:p}=t;Om(u&&p,e,"internal-error");var g=av.fromJSON(this.name,p);Om("string"==typeof u,e,"internal-error"),cv(n,e.name),cv(r,e.name),Om("boolean"==typeof h,e,"internal-error"),Om("boolean"==typeof d,e,"internal-error"),cv(i,e.name),cv(s,e.name),cv(o,e.name),cv(a,e.name),cv(c,e.name),cv(l,e.name);const m=new lv({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:g,createdAt:c,lastLoginAt:l});return f&&Array.isArray(f)&&(m.providerData=f.map(e=>Object.assign({},e))),a&&(m._redirectEventId=a),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new av;r.updateFromServerResponse(t);var i=new lv({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await ov(i),i}}class uv{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}uv.type="NONE";const hv=uv;function dv(e,t,n){return`firebase:${e}:${t}:${n}`}class fv{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=dv(this.userKey,r.apiKey,i),this.fullPersistenceKey=dv("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){var e=await this.persistence._get(this.fullUserKey);return e?lv._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence!==e){var t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new fv(Um(hv),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||Um(hv);const s=dv(n,e.config.apiKey,e.name);let o=null;for(const u of t)try{var a=await u._get(s);if(a){var c=lv._fromJSON(e,a);u!==i&&(o=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new fv(i,e,n)}}function pv(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(yv(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(gv(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(wv(t))return"Blackberry";if(bv(t))return"Webos";if(mv(t))return"Safari";if((t.includes("chrome/")||vv(t))&&!t.includes("edge/"))return"Chrome";if(_v(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function gv(e=sd()){return/firefox\//i.test(e)}function mv(e=sd()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function vv(e=sd()){return/crios\//i.test(e)}function yv(e=sd()){return/iemobile/i.test(e)}function _v(e=sd()){return/android/i.test(e)}function wv(e=sd()){return/blackberry/i.test(e)}function bv(e=sd()){return/webos/i.test(e)}function Iv(e=sd()){return/iphone|ipad|ipod/i.test(e)}function Tv(e=sd()){return Iv(e)||_v(e)||bv(e)||wv(e)||/windows phone/i.test(e)||yv(e)}function Ev(e,t=[]){let n;switch(e){case"Browser":n=pv(sd());break;case"Worker":n=`${pv(sd())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Tf}/${r}`}class Sv{constructor(e,t,n){this.app=e,this.heartbeatServiceProvider=t,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Cv(this),this.idTokenSubscription=new Cv(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=km,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion}_initializeWithPersistence(t,n){return n&&(this._popupRedirectResolver=Um(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await fv.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e)}}async initializeCurrentUser(e){var t,n,r;let i=await this.assertedPersistence.getCurrentUser();return e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===i||void 0===i?void 0:i._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(i=r.user)),i?i._redirectEventId?(Om(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)):this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await ov(e)}catch(e){if("auth/network-request-failed"!==e.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?$d(e):null;return t&&Om(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){if(!this._deleted)return e&&Om(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(Um(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new md("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(Om(t=e&&Um(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await fv.create(this,[Um(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=null!==(e=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return Om(s,this,"internal-error"),s.then(()=>i(this.currentUser)),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&(this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh()),(this.currentUser=e)?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return Om(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Ev(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);var t=await(null===(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getHeartbeatsHeader());return t&&(e["X-Firebase-Client"]=t),e}}function kv(e){return $d(e)}class Cv{constructor(e){this.auth=e,this.observer=null,this.addObserver=xd(e=>this.observer=e)}get next(){return Om(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function Av(e,t,n){const r=kv(e);Om(r._canInitEmulator,r,"emulator-config-failed"),Om(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=Nv(t);var{host:o,port:a}=function(e){const t=Nv(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:Rv(r.substr(s.length+1))}}var[o,s]=r.split(":");return{host:o,port:Rv(s)}}}(t);r.config.emulator={url:`${s}//${o}${null===a?"":`:${a}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function Nv(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Rv(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class xv{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Mm("not implemented")}_getIdTokenResponse(e){return Mm("not implemented")}_linkToIdToken(e,t){return Mm("not implemented")}_getReauthenticationResolver(e){return Mm("not implemented")}}async function Pv(e,t){return Hm(e,"POST","/v1/accounts:resetPassword",Gm(e,t))}async function Dv(e,t){return Hm(e,"POST","/v1/accounts:update",t)}async function Ov(e,t){return Hm(e,"POST","/v1/accounts:sendOobCode",Gm(e,t))}class Mv extends xv{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new Mv(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Mv(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithPassword",Gm(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithEmailLink",Gm(e,t))}(e,{email:this._email,oobCode:this._password});default:Nm(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Dv(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithEmailLink",Gm(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:Nm(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Lv(e,t){return Ym(e,"POST","/v1/accounts:signInWithIdp",Gm(e,t))}class Fv extends xv{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Fv(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):Nm("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,t=wm(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Fv(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return Lv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Lv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Lv(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=Cd(t)}return e}}const Uv={USER_NOT_FOUND:"user-not-found"};class qv extends xv{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new qv({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new qv({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithPhoneNumber",Gm(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Ym(e,"POST","/v1/accounts:signInWithPhoneNumber",Gm(e,t));if(n.temporaryProof)throw Zm(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithPhoneNumber",Gm(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Uv)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){var{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new qv({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class jv{constructor(e){var t=Ad(Nd(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);Om(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=Ad(Nd(e=e)).link,n=t?Ad(Nd(t)).deep_link_id:null,((r=Ad(Nd(e)).deep_link_id)?Ad(Nd(r)).link:null)||r||n||t||e);try{return new jv(t)}catch(e){return null}}}class Vv{constructor(){this.providerId=Vv.PROVIDER_ID}static credential(e,t){return Mv._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=jv.parseLink(t);return Om(n,"argument-error"),Mv._fromEmailAndCode(e,n.code,n.tenantId)}}Vv.PROVIDER_ID="password",Vv.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Vv.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Bv{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class Kv extends Bv{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class $v extends Kv{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return Om("providerId"in t&&"signInMethod"in t,"argument-error"),Fv._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return Om(e.idToken||e.accessToken,"argument-error"),Fv._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return $v.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return $v.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:o}=e;if(!(n||r||t||i))return null;if(!o)return null;try{return new $v(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Wv extends Kv{constructor(){super("facebook.com")}static credential(e){return Fv._fromParams({providerId:Wv.PROVIDER_ID,signInMethod:Wv.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Wv.credentialFromTaggedObject(e)}static credentialFromError(e){return Wv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Wv.credential(e.oauthAccessToken)}catch(e){return null}}}Wv.FACEBOOK_SIGN_IN_METHOD="facebook.com",Wv.PROVIDER_ID="facebook.com";class zv extends Kv{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Fv._fromParams({providerId:zv.PROVIDER_ID,signInMethod:zv.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return zv.credentialFromTaggedObject(e)}static credentialFromError(e){return zv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return zv.credential(t,n)}catch(e){return null}}}zv.GOOGLE_SIGN_IN_METHOD="google.com",zv.PROVIDER_ID="google.com";class Gv extends Kv{constructor(){super("github.com")}static credential(e){return Fv._fromParams({providerId:Gv.PROVIDER_ID,signInMethod:Gv.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Gv.credentialFromTaggedObject(e)}static credentialFromError(e){return Gv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Gv.credential(e.oauthAccessToken)}catch(e){return null}}}Gv.GITHUB_SIGN_IN_METHOD="github.com",Gv.PROVIDER_ID="github.com";class Hv extends xv{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return Lv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Lv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Lv(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new Hv(t,r):null}static _create(e,t){return new Hv(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Qv extends Bv{constructor(e){Om(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Qv.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Qv.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Hv.fromJSON(e);return Om(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return Hv._create(n,t)}catch(e){return null}}}class Yv extends Kv{constructor(){super("twitter.com")}static credential(e,t){return Fv._fromParams({providerId:Yv.PROVIDER_ID,signInMethod:Yv.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Yv.credentialFromTaggedObject(e)}static credentialFromError(e){return Yv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return Yv.credential(t,n)}catch(e){return null}}}async function Jv(e,t){return Ym(e,"POST","/v1/accounts:signUp",Gm(e,t))}Yv.TWITTER_SIGN_IN_METHOD="twitter.com",Yv.PROVIDER_ID="twitter.com";class Xv{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await lv._fromIdTokenResponse(e,n,r),s=Zv(n);return new Xv({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=Zv(n);return new Xv({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function Zv(e){return e.providerId||("phoneNumber"in e?"phone":null)}class ey extends gd{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,ey.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new ey(e,t,n,r)}}function ty(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw ey._fromErrorAndOperation(t,e,n,r);throw e})}function ny(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function ry(e,t){const n=$d(e);await sy(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await Hm(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=ny(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function iy(e,t,n=!1){var r=await rv(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Xv._forOperation(e,"link",r)}async function sy(e,t,n){await ov(t);const r=ny(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";Om(r.has(n)===e,t.auth,i)}async function oy(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await rv(e,ty(r,i,t,e),n);Om(s.idToken,r,"internal-error");var o=nv(s.idToken);Om(o,r,"internal-error");var a=o["sub"];return Om(e.uid===a,r,"user-mismatch"),Xv._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&Nm(r,"user-mismatch"),e}}async function ay(e,t,n=!1){var r=await ty(e,"signIn",t),r=await Xv._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function cy(e,t){return ay(kv(e),t)}async function ly(e,t){var n=$d(e);return await sy(!1,n,t.providerId),iy(n,t)}async function uy(e,t){return oy($d(e),t)}async function hy(e,t){const n=kv(e);var r=await Ym(n,"POST","/v1/accounts:signInWithCustomToken",Gm(n,{token:t,returnSecureToken:!0})),r=await Xv._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class dy{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?fy._fromServerResponse(e,t):Nm(e,"internal-error")}}class fy extends dy{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new fy(t)}}function py(e,t,n){var r;Om(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),Om(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(Om(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(Om(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function gy(e,t,n){var r=$d(e),i={requestType:"PASSWORD_RESET",email:t};n&&py(r,i,n),await Ov(r,i)}async function my(e,t){await Hm(e=$d(e),"POST","/v1/accounts:update",Gm(e,{oobCode:t}))}async function vy(e,t){var n=$d(e),r=await Pv(n,{oobCode:t}),i=r.requestType;switch(Om(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":Om(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":Om(r.mfaInfo,n,"internal-error");default:Om(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=dy._fromServerResponse(kv(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function yy(e,t,n){var r=$d(e),i={requestType:"EMAIL_SIGNIN",email:t};Om(n.handleCodeInApp,r,"argument-error"),n&&py(r,i,n),await Ov(r,i)}async function _y(e,t){var n=jm()?qm():"http://localhost",n=(await Hm(e=$d(e),"POST","/v1/accounts:createAuthUri",Gm(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function wy(e,t){var n=$d(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&py(n.auth,r,t);var r=(await Ov(n.auth,r))["email"];r!==e.email&&await e.reload()}async function by(e,t,n){var r=$d(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&py(r.auth,i,n);var i=(await Ov(r.auth,i))["email"];i!==e.email&&await e.reload()}async function Iy(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=$d(e);var r=await i.getIdToken(),r=await rv(i,async function(e,t){return Hm(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function Ty(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await rv(e,Dv(r,i));await e._updateTokensIfNecessary(r,!0)}class Ey{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class Sy extends Ey{constructor(e,t,n,r){super(e,t,n),this.username=r}}class ky extends Ey{constructor(e,t){super(e,"facebook.com",t)}}class Cy extends Sy{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class Ay extends Ey{constructor(e,t){super(e,"google.com",t)}}class Ny extends Sy{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Ry(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=nv(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new Ey(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new ky(r,n);case"github.com":return new Cy(r,n);case"google.com":return new Ay(r,n);case"twitter.com":return new Ny(r,n,e.screenName||null);case"custom":case"anonymous":return new Ey(r,null);default:return new Ey(r,t,n)}}(n)}class xy{constructor(e,t){this.type=e,this.credential=t}static _fromIdtoken(e){return new xy("enroll",e)}static _fromMfaPendingCredential(e){return new xy("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.pendingCredential)return xy._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return xy._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Py{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=kv(e),o=i.customData._serverResponse;var t=(o.mfaInfo||[]).map(e=>dy._fromServerResponse(s,e));Om(o.mfaPendingCredential,s,"internal-error");const a=xy._fromMfaPendingCredential(o.mfaPendingCredential);return new Py(a,t,async e=>{var t=await e._process(s,a);delete o.mfaInfo,delete o.mfaPendingCredential;var n=Object.assign(Object.assign({},o),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Xv._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return Om(i.user,s,"internal-error"),Xv._forOperation(i.user,i.operationType,n);default:Nm(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class Dy{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>dy._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new Dy(e)}async getSession(){return xy._fromIdtoken(await this.user.getIdToken())}async enroll(e,t){const n=e;var r=await this.getSession(),r=await rv(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r=await this.user.getIdToken(),r=await rv(this.user,(n=this.user.auth,e={idToken:r,mfaEnrollmentId:t},Hm(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Gm(n,e))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(r);try{await this.user.reload()}catch(e){if("auth/user-token-expired"!==e.code)throw e}}}const Oy=new WeakMap;const My="__sak";class Ly{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(My,"1"),this.storage.removeItem(My),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){var t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class Fy extends Ly{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(mv(e=sd())||Iv(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Tv(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);ud()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Fy.type="LOCAL";const Uy=Fy;class qy extends Ly{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}qy.type="SESSION";const jy=qy;class Vy{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));if(e)return e;e=new Vy(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:s}))}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function By(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}Vy.receivers=[];class Ky{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,o=50){const a="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!a)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=By("",20);a.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},o);l={messageChannel:a,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),a.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[a.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function $y(){return window}function Wy(){return void 0!==$y().WorkerGlobalScope&&"function"==typeof $y().importScripts}const zy="firebaseLocalStorageDb",Gy="firebaseLocalStorage",Hy="fbase_key";class Qy{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function Yy(e,t){return e.transaction([Gy],t?"readwrite":"readonly").objectStore(Gy)}function Jy(){const r=indexedDB.open(zy,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(Gy,{keyPath:Hy})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(Gy)?n(e):(e.close(),t=indexedDB.deleteDatabase(zy),await new Qy(t).toPromise(),n(await Jy()))})})}async function Xy(e,t,n){var r=Yy(e,!0).put({fbase_key:t,value:n});return new Qy(r).toPromise()}function Zy(e,t){var n=Yy(e,!0).delete(t);return new Qy(n).toPromise()}class e_{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db||(this.db=await Jy(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Wy()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Vy._getInstance(Wy()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new Ky(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;var e=await Jy();return await Xy(e,My,"1"),await Zy(e,My),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Xy(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=Yy(e,!1).get(t);return void 0===(n=await new Qy(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Zy(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=Yy(e,!1).getAll();return new Qy(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}e_.type="LOCAL";const t_=e_;function n_(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=Rm("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function r_(e){return`__${e}${Math.floor(1e6*Math.random())}`}class i_{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new s_(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class s_{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;Om(r,"argument-error",{appName:t}),this.container=r,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const o_=r_("rcb"),a_=new Bm(3e4,6e4);class c_{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!$y().grecaptcha}load(s,o=""){var e;return Om((e=o).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(o)?Promise.resolve($y().grecaptcha):new Promise((t,n)=>{const i=$y().setTimeout(()=>{n(Rm(s,"network-request-failed"))},a_.get());$y()[o_]=()=>{$y().clearTimeout(i),delete $y()[o_];const e=$y().grecaptcha;if(e){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=o,t(e)}else n(Rm(s,"internal-error"))},n_(`https://www.google.com/recaptcha/api.js??${Cd({onload:o_,render:"explicit",hl:o})}`).catch(()=>{clearTimeout(i),n(Rm(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!$y().grecaptcha&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class l_{async load(e){return new i_(e)}clearedOneInstance(){}}const u_="recaptcha",h_={theme:"light",type:"image"};class d_{constructor(e,t=Object.assign({},h_),n){this.parameters=t,this.type=u_,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=kv(n),this.isInvisible="invisible"===this.parameters.size,Om("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof e?document.getElementById(e):e;Om(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?l_:c_),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){Om(!this.parameters.sitekey,this.auth,"argument-error"),Om(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),Om("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=$y()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){Om(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){Om(jm()&&!Wy(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).catch(e=>{throw t&&window.removeEventListener("load",t),e})}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await Hm(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");Om(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return Om(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class f_{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=qv._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function p_(t,n,r){var i,s,o,a,c,l,u=await r.verify();try{Om("string"==typeof u,t,"argument-error"),Om(r.type===u_,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return Om("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await Hm(c,"POST","/v2/accounts/mfaEnrollment:start",Gm(c,l))).phoneSessionInfo.sessionInfo;Om("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return Om(d,t,"missing-multi-factor-info"),(a={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await Hm(t,"POST","/v2/accounts/mfaSignIn:start",Gm(t,a))).phoneResponseInfo.sessionInfo}var f=(s=t,o={phoneNumber:e.phoneNumber,recaptchaToken:u},await Hm(s,"POST","/v1/accounts:sendVerificationCode",Gm(s,o)))["sessionInfo"];return f}finally{r._reset()}}class g_{constructor(e){this.providerId=g_.PROVIDER_ID,this.auth=kv(e)}verifyPhoneNumber(e,t){return p_(this.auth,e,$d(t))}static credential(e,t){return qv._fromVerification(e,t)}static credentialFromResult(e){var t=e;return g_.credentialFromTaggedObject(t)}static credentialFromError(e){return g_.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?qv._fromTokenResponse(t,n):null}}function m_(e,t){return t?Um(t):(Om(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}g_.PROVIDER_ID="phone",g_.PHONE_SIGN_IN_METHOD="phone";class v_ extends xv{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Lv(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Lv(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Lv(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function y_(e){return ay(e.auth,new v_(e),e.bypassAuthState)}function __(e){var{auth:t,user:n}=e;return Om(n,t,"internal-error"),oy(n,new v_(e),e.bypassAuthState)}async function w_(e){var{auth:t,user:n}=e;return Om(n,t,"internal-error"),iy(n,new v_(e),e.bypassAuthState)}class b_{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){var{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return y_;case"linkViaPopup":case"linkViaRedirect":return w_;case"reauthViaPopup":case"reauthViaRedirect":return __;default:Nm(this.auth,"internal-error")}}resolve(e){Lm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Lm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const I_=new Bm(2e3,1e4);class T_ extends b_{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,T_.currentPopupAction&&T_.currentPopupAction.cancel(),T_.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return Om(e,this.auth,"internal-error"),e}async onExecution(){Lm(1===this.filter.length,"Popup operations only handle one event");var e=By();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(Rm(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(Rm(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,T_.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Rm(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(t,I_.get())};t()}}T_.currentPopupAction=null;const E_="pendingRedirect",S_=new Map;class k_ extends b_{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=S_.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=N_(t),r=A_(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}S_.set(this.auth._key(),t)}return this.bypassAuthState||S_.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function C_(e,t){return A_(e)._set(N_(t),"true")}function A_(e){return Um(e._redirectPersistence)}function N_(e){return dv(E_,e.config.apiKey,e.name)}function R_(e,t,n){return async function(e,t,n){var r=kv(e);Pm(e,t,Bv);const i=m_(r,n);return await C_(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function x_(e,t,n){return async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);const i=m_(r.auth,n);await C_(i,r.auth);var s=await O_(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function P_(e,t,n){return async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);const i=m_(r.auth,n);await sy(!1,r,t.providerId),await C_(i,r.auth);var s=await O_(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function D_(e,t,n=!1){const r=kv(e);var i=m_(r,t);const s=new k_(r,i,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,t)),o}async function O_(e){var t=By(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class M_{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(t){if(this.hasEventBeenHandled(t))return!1;let n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return F_(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!F_(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(Rm(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(L_(e))}saveEventToCache(e){this.cachedEventUids.add(L_(e)),this.lastProcessedEventTime=Date.now()}}function L_(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function F_({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function U_(e,t={}){return Hm(e,"GET","/v1/projects",t)}const q_=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,j_=/^https?/;async function V_(e){if(!e.config.emulator){var t=(await U_(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=qm(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!j_.test(n))return!1;if(q_.test(e))return r===e;const s=e.replace(/\./g,"\\."),o=new RegExp("^(.+\\."+s+"|"+s+")$","i");return o.test(r)}(n))return}catch(e){}Nm(e,"unauthorized-domain")}}const B_=new Bm(3e4,6e4);function K_(){const t=$y().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let $_=null;function W_(e){var i;return $_=$_||(i=e,new Promise((e,t)=>{function n(){K_(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{K_(),t(Rm(i,"network-request-failed"))},timeout:B_.get()})}if(null!==(r=null===(r=$y().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=$y().gapi)||void 0===r||!r.load){var r=r_("iframefcb");return $y()[r]=()=>{gapi.load?n():t(Rm(i,"network-request-failed"))},n_(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw $_=null,e})),$_}const z_=new Bm(5e3,15e3),G_="__/auth/iframe",H_="emulator/auth/iframe",Q_={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Y_=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function J_(o){const e=await W_(o);var t=$y().gapi;return Om(t,o,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;Om(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?Km(t,H_):`https://${e.config.authDomain}/${G_}`;const r={apiKey:t.apiKey,appName:e.name,v:Tf};(t=Y_.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${Cd(r).slice(1)}`}(o),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Q_,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=Rm(o,"network-request-failed"),r=$y().setTimeout(()=>{t(n)},z_.get());function i(){$y().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const X_={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Z_{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function ew(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-r)/2,0).toString();let a="";const c=Object.assign(Object.assign({},X_),{width:r.toString(),height:i.toString(),top:s,left:o});s=sd().toLowerCase();n&&(a=vv(s)?"_blank":n),gv(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,o=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=sd()]=[s],Iv(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",a),new Z_(null);const u=window.open(t||"",a,o);Om(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Z_(u)}const tw="__/auth/handler",nw="emulator/auth/handler";function rw(e,t,n,r,i,s){Om(e.config.authDomain,e,"auth-domain-config-required"),Om(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Tf,eventId:i};if(t instanceof Bv){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",Td(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(var[a,c]of Object.entries(s||{}))o[a]=c}if(t instanceof Kv){const u=t.getScopes().filter(e=>""!==e);0<u.length&&(o.scopes=u.join(","))}e.tenantId&&(o.tid=e.tenantId);const l=o;for(const h of Object.keys(l))void 0===l[h]&&delete l[h];return`${e=[e["config"]][0],e.emulator?Km(e,nw):`https://${e.authDomain}/${tw}`}?${Cd(l).slice(1)}`}const iw="webStorageSupport";const sw=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=jy,this._completeRedirectFn=D_}async _openPopup(e,t,n,r){var i;return Lm(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),ew(e,rw(e,t,n,qm(),r),By())}async _openRedirect(e,t,n,r){return await this._originValidation(e),r=rw(e,t,n,qm(),r),$y().location.href=r,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(Lm(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await J_(t),n=new M_(t);return e.register("authEvent",e=>{return Om(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(iw,{type:iw},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[iw];void 0!==t&&r(!!t),Nm(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=V_(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Tv()||mv()||Iv()}};class ow extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return Mm("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ow(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},Hm(e,"POST","/v2/accounts/mfaEnrollment:finalize",Gm(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},Hm(e,"POST","/v2/accounts/mfaSignIn:finalize",Gm(e,t))}}class aw{constructor(){}static assertion(e){return ow._fromCredential(e)}}aw.FACTOR_ID="phone";var cw,lw="@firebase/auth",uw="0.19.12";class hw{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null===e||void 0===e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){Om(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function dw(){return window}cw="Browser",_f(new Xd("auth",(e,{options:r})=>{var t=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");const{apiKey:i,authDomain:s}=t.options;return((e,t)=>{Om(i&&!i.includes(":"),"invalid-api-key",{appName:e.name}),Om(!(null!==s&&void 0!==s&&s.includes(":")),"argument-error",{appName:e.name});var n={apiKey:i,authDomain:s,clientPlatform:cw,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Ev(cw)},n=new Sv(e,t,n);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(Um);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(n,r),n})(t,n)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),_f(new Xd("auth-internal",e=>{var t=kv(e.getProvider("auth").getImmediate());return e=t,new hw(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),Cf(lw,uw,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(cw)),Cf(lw,uw,"esm2017");async function fw(e,t,n){var r=dw()["BuildInfo"];Lm(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(Lm(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return Iv()?s.ibi=r.packageName:_v()?s.apn=r.packageName:Nm(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,rw(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function pw(r){const i=dw()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=sd(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const gw=20;class mw extends M_{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function vw(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<gw;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:Rm(e,"no-auth-event")}}async function yw(e){var t=await ww()._get(bw(e));return t&&await ww()._remove(bw(e)),t}function _w(e,t){var n,r,i;const s=(n=Iw(t=t),o=n.link?decodeURIComponent(n.link):void 0,r=Iw(o).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=Iw(i).link)||i||r||o||t);if(s.includes("/__/auth/callback")){var o=Iw(s),o=o.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(o.firebaseError)):null,o=null===(o=null===(o=null==o?void 0:o.code)||void 0===o?void 0:o.split("auth/"))||void 0===o?void 0:o[1],o=o?Rm(o):null;return o?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:o,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function ww(){return Um(Uy)}function bw(e){return dv("authEvent",e.config.apiKey,e.name)}function Iw(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return Ad(t.join("?"))}const Tw=class{constructor(){this._redirectPersistence=jy,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=D_}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new mw(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){Nm(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,a=dw(),Om("function"==typeof(null===(s=null==a?void 0:a.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),Om(void 0!==(null===(s=null==a?void 0:a.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),Om("function"==typeof(null===(s=null===(s=null===(s=null==a?void 0:a.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),Om("function"==typeof(null===(s=null===(s=null===(s=null==a?void 0:a.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),Om("function"==typeof(null===(a=null===(a=null==a?void 0:a.cordova)||void 0===a?void 0:a.InAppBrowser)||void 0===a?void 0:a.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const o=await this._initialize(e);await o.initialized(),o.resetRedirect(),S_.clear(),await this._originValidation(e);var a=vw(e,n,r);n=e,r=a,await ww()._set(bw(n),r);a=await pw(await fw(e,a,t));return async function(o,a,c){const l=dw()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(Rm(o,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}a.addPassiveListener(r),document.addEventListener("resume",i,!1),_v()&&document.addEventListener("visibilitychange",s,!1),u=()=>{a.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,o,a)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=dw()["BuildInfo"];const n={};Iv()?n.iosBundleId=t.packageName:_v()?n.androidPackageName=t.packageName:Nm(e,"operation-not-supported-in-this-environment"),await U_(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=dw(),s=setTimeout(async()=>{await yw(r),i.onEvent(Ew())},500),o=async e=>{clearTimeout(s);var t=await yw(r);let n=null;t&&null!=e&&e.url&&(n=_w(t,e.url)),i.onEvent(n||Ew())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,o);const a=t,c=`${n.packageName.toLowerCase()}://`;dw().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&o({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}}}};function Ew(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Rm("no-auth-event")}}var Sw;function kw(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function Cw(e=sd()){return!("file:"!==kw()&&"ionic:"!==kw()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Aw(e=sd()){return ud()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=sd()]=[e],/Edge\/\d+/.test(e))}function Nw(){try{const t=self.localStorage;var e=By();if(t)return t.setItem(e,"1"),t.removeItem(e),!Aw()||dd()}catch(e){return Rw()&&dd()}return!1}function Rw(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function xw(){return("http:"===kw()||"https:"===kw()||cd()||Cw())&&!(ld()||ad())&&Nw()&&!Rw()}function Pw(){return Cw()&&"undefined"!=typeof document}const Dw={LOCAL:"local",NONE:"none",SESSION:"session"},Ow=Om,Mw="persistence";async function Lw(e){await e._initializationPromise;const t=Fw();var n=dv(Mw,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function Fw(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const Uw=Om;class qw{constructor(){this.browserResolver=Um(sw),this.cordovaResolver=Um(Tw),this.underlyingResolver=null,this._redirectPersistence=jy,this._completeRedirectFn=D_}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Pw()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Uw(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Pw()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function jw(e){return e.unwrap()}function Vw(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===t.code){const a=t;a.resolver=new Ww(e,(n=t,i=$d(e),Om((o=n).customData.operationType,i,"argument-error"),Om(null===(r=o.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Py._fromError(i,o)))}else if(s){var o=Bw(t);const c=t;o&&(c.credential=o,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Bw(e){var t=(e instanceof gd?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof gd)&&"temporaryProof"in t&&"phoneNumber"in t)return g_.credentialFromResult(e);const n=t.providerId;if(!n||n===bm.PASSWORD)return null;let r;switch(n){case bm.GOOGLE:r=zv;break;case bm.FACEBOOK:r=Wv;break;case bm.GITHUB:r=Gv;break;case bm.TWITTER:r=Yv;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:o,pendingToken:a,nonce:c}=t;return s||o||i||a?a?n.startsWith("saml.")?Hv._create(n,a):Fv._fromParams({providerId:n,signInMethod:n,pendingToken:a,idToken:i,accessToken:s}):new $v(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof gd?r.credentialFromError(e):r.credentialFromResult(e)}function Kw(t,e){return e.catch(e=>{throw e instanceof gd&&Vw(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Bw(e),additionalUserInfo:Ry(e),user:zw.getOrCreate(n)}})}async function $w(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>Kw(t,n.confirm(e))}}class Ww{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Kw(jw(this.auth),this.resolver.resolveSignIn(e))}}class zw{constructor(e){var t;this._delegate=e,this.multiFactor=(t=$d(e),Oy.has(t)||Oy.set(t,Dy._fromUser(t)),Oy.get(t))}static getOrCreate(e){return zw.USER_MAP.has(e)||zw.USER_MAP.set(e,new zw(e)),zw.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Kw(this.auth,ly(this._delegate,e))}async linkWithPhoneNumber(e,t){return $w(this.auth,async function(e,t,n){const r=$d(e);await sy(!1,r,"phone");var i=await p_(r.auth,t,$d(n));return new f_(i,e=>ly(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return Kw(this.auth,async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);var i=m_(r.auth,n);const s=new T_(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,qw))}async linkWithRedirect(e){return await Lw(kv(this.auth)),P_(this._delegate,e,qw)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Kw(this.auth,uy(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return $w(this.auth,async function(e,t,n){const r=$d(e);var i=await p_(r.auth,t,$d(n));return new f_(i,e=>uy(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return Kw(this.auth,async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);var i=m_(r.auth,n);const s=new T_(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,qw))}async reauthenticateWithRedirect(e){return await Lw(kv(this.auth)),x_(this._delegate,e,qw)}sendEmailVerification(e){return wy(this._delegate,e)}async unlink(e){return await ry(this._delegate,e),this}updateEmail(e){return Ty($d(this._delegate),e,null)}updatePassword(e){return Ty($d(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await iy($d(e),t)}(this._delegate,e)}updateProfile(e){return Iy(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return by(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}zw.USER_MAP=new WeakMap;const Gw=Om;class Hw{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Gw(n,"invalid-api-key",{appName:e.name}),Gw(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?qw:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=Fw();if(!n)return[];var r=dv(Mw,e,t);switch(n.getItem(r)){case Dw.NONE:return[hv];case Dw.LOCAL:return[t_,jy];case Dw.SESSION:return[jy];default:return[]}}(e,t);"undefined"==typeof self||n.includes(t_)||n.push(t_);if("undefined"!=typeof window)for(const r of[Uy,jy])n.includes(r)||n.push(r);n.includes(hv)||n.push(hv);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(Em),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?zw.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){Av(this._delegate,e,t)}applyActionCode(e){return my(this._delegate,e)}checkActionCode(e){return vy(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await Pv($d(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Kw(this._delegate,async function(e,t,n){const r=kv(e);var i=await Jv(r,{returnSecureToken:!0,email:t,password:n}),i=await Xv._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(i.user),i}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return _y(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=jv.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Gw(xw(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=qw,await kv(e)._initializationPromise,await D_(e,t,!1));return n?Kw(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){kv(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=Qw(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=Qw(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return yy(this._delegate,e,t)}sendPasswordResetEmail(e,t){return gy(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Ow(Object.values(Dw).includes(n),t,"invalid-persistence-type"),ld()?Ow(n!==Dw.SESSION,t,"unsupported-persistence-type"):ad()?Ow(n===Dw.NONE,t,"unsupported-persistence-type"):Rw()?Ow(n===Dw.NONE||n===Dw.LOCAL&&dd(),t,"unsupported-persistence-type"):Ow(n===Dw.NONE||Nw(),t,"unsupported-persistence-type");let r;switch(e){case Dw.SESSION:r=jy;break;case Dw.LOCAL:var i=await Um(t_)._isAvailable();r=i?t_:Uy;break;case Dw.NONE:r=hv;break;default:return Nm("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Kw(this._delegate,async function(e){const t=kv(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Xv({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await Jv(t,{returnSecureToken:!0}),n=await Xv._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return Kw(this._delegate,cy(this._delegate,e))}signInWithCustomToken(e){return Kw(this._delegate,hy(this._delegate,e))}signInWithEmailAndPassword(e,t){return Kw(this._delegate,(n=this._delegate,e=e,t=t,cy($d(n),Vv.credential(e,t))));var n}signInWithEmailLink(e,t){return Kw(this._delegate,async function(e,t,n){var r=$d(e),i=Vv.credentialWithLink(t,n||qm());return Om(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),cy(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return $w(this._delegate,async function(e,t,n){const r=kv(e);var i=await p_(r,t,$d(n));return new f_(i,e=>cy(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Gw(xw(),this._delegate,"operation-not-supported-in-this-environment"),Kw(this._delegate,async function(e,t,n){var r=kv(e);Pm(e,t,Bv);var i=m_(r,n);const s=new T_(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,qw))}async signInWithRedirect(e){return Gw(xw(),this._delegate,"operation-not-supported-in-this-environment"),await Lw(this._delegate),R_(this._delegate,e,qw)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await vy($d(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function Qw(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&zw.getOrCreate(e)),error:t,complete:n}}Hw.Persistence=Dw;class Yw{constructor(){this.providerId="phone",this._delegate=new g_(jw(zf.auth()))}static credential(e,t){return g_.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Yw.PHONE_SIGN_IN_METHOD=g_.PHONE_SIGN_IN_METHOD,Yw.PROVIDER_ID=g_.PROVIDER_ID;const Jw=Om;class Xw{constructor(e,t,n=zf.app()){var r;Jw(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new d_(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(Sw=zf).INTERNAL.registerComponent(new Xd("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new Hw(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:Im.EMAIL_SIGNIN,PASSWORD_RESET:Im.PASSWORD_RESET,RECOVER_EMAIL:Im.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:Im.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:Im.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:Im.VERIFY_EMAIL}},EmailAuthProvider:Vv,FacebookAuthProvider:Wv,GithubAuthProvider:Gv,GoogleAuthProvider:zv,OAuthProvider:$v,SAMLAuthProvider:Qv,PhoneAuthProvider:Yw,PhoneMultiFactorGenerator:aw,RecaptchaVerifier:Xw,TwitterAuthProvider:Yv,Auth:Hw,AuthCredential:xv,Error:gd}).setInstantiationMode("LAZY").setMultipleInstances(!1)),Sw.registerVersion("@firebase/auth-compat","0.2.12");const Zw="@firebase/database";let eb="";function tb(e){eb=e}class nb{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),_d(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:yd(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class rb{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return bd(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var ib,sb,ob,ab,cb,lb,yt=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new nb(t)}}catch(e){}return new rb};function ub(e){var t=function(t){const n=[];let r=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);var i,s;55296<=e&&e<=56319&&(i=e-55296,o++,Yh(o<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(o)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new Rd;return n.update(t),t=n.digest(),Zh.encodeByteArray(t)}const hb=yt("localStorage"),db=yt("sessionStorage"),fb=new cf("@firebase/database"),pb=function(){let e=1;return function(){return e++}}(),gb=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=gb.apply(null,n):t+="object"==typeof n?_d(n):n,t+=" "}return t};let mb=null,vb=!0;function yb(t){return function(...e){Sb(t,...e)}}function _b(...e){var t="FIREBASE INTERNAL ERROR: "+gb(...e);fb.error(t)}function wb(e,t){return e===t?0:e<t?-1:1}function bb(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+_d(t))}function Ib(e){if("object"!=typeof e||null===e)return _d(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=_d(t[i]),n+=":",n+=Ib(e[t[i]]);return n+="}",n}function Tb(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const Eb=function(e,t){Yh(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(fb.logLevel=$h.VERBOSE,mb=fb.log.bind(fb),t&&db.set("logging_enabled",!0)):"function"==typeof e?mb=e:(mb=null,db.remove("logging_enabled"))},Sb=function(...e){var t;!0===vb&&(vb=!1,null===mb&&!0===db.get("logging_enabled")&&Eb(!0)),mb&&(t=gb.apply(null,e),mb(t))},kb=function(...e){var t=`FIREBASE FATAL ERROR: ${gb(...e)}`;throw fb.error(t),new Error(t)},Cb=function(...e){var t="FIREBASE WARNING: "+gb(...e);fb.warn(t)},Ab=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Cb("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Nb=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},Rb="[MIN_NAME]",xb="[MAX_NAME]",Pb=function(e,t){if(e===t)return 0;if(e===Rb||t===xb)return-1;if(t===Rb||e===xb)return 1;var n=qb(e),r=qb(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Db(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Ob(e){Yh(!Nb(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();const a=o.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function Mb(e,t){const n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}const Lb=new RegExp("^-?(0*)\\d{1,10}$"),Fb=-2147483648,Ub=2147483647,qb=function(e){if(Lb.test(e)){var t=Number(e);if(t>=Fb&&t<=Ub)return t}return null},jb=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw Cb("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Vb{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(e=>this.appCheck=e)}getToken(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){Cb(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Bb{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(Sb("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Cb(e)}}class Kb{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Kb.OWNER="owner";const $b=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Wb="websocket",zb="long_polling";class Gb{constructor(e,t,n,r,i=!1,s="",o=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=hb.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&hb.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function Hb(e,t,n){Yh("string"==typeof t,"typeof type must == string"),Yh("object"==typeof n,"typeof params must == object");let r;if(t===Wb)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==zb)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return Db(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class Qb{constructor(){this.counters_={}}incrementCounter(e,t=1){bd(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return nd(void 0,this.counters_)}}const Yb={},Jb={};function Xb(e){var t=e.toString();return Yb[t]||(Yb[t]=new Qb),Yb[t]}class Zb{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&jb(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class eI{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=yb(e),this.stats_=Xb(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Hb(t,zb,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Zb(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new tI((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&$b.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){eI.forceAllow_=!0}static forceDisallow(){eI.forceDisallow_=!0}static isAvailable(){return!!eI.forceAllow_||!(eI.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=_d(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=Hh(t),n=Tb(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=_d(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class tI{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=pb(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=tI.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){Sb("frame writing exception"),e.stack&&Sb(e.stack),Sb(e)}}}static createIFrame_(){const t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||Sb("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{Sb("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let nI=null;"undefined"!=typeof MozWebSocket?nI=MozWebSocket:"undefined"!=typeof WebSocket&&(nI=WebSocket);class rI{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=yb(this.connId),this.stats_=Xb(t),this.connURL=rI.connectionURL_(t,s,o,r),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r){const i={v:"5"};return"undefined"!=typeof location&&location.hostname&&$b.test(location.hostname)&&(i.r="f"),t&&(i.s=t),n&&(i.ls=n),r&&(i.ac=r),Hb(e,Wb,i)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,hb.set("previous_websocket_failure",!0);try{hd()||(n={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}},this.mySock=new nI(this.connURL,[],n))}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){rI.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==nI&&!rI.forceDisallow_}static previouslyFailed(){return hb.isInMemoryStorage||!0===hb.get("previous_websocket_failure")}markConnectionHealthy(){hb.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=yd(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(Yh(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=_d(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=Tb(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}rI.responsesRequiredToBeHealthy=2,rI.healthyTimeout=3e4;class iI{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[eI,rI]}initTransports_(e){var t=rI&&rI.isAvailable();let n=t&&!rI.previouslyFailed();if(e.webSocketOnly&&(t||Cb("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[rI];else{const r=this.transports_=[];for(const i of iI.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i)}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}class sI{constructor(e,t,n,r,i,s,o,a,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=yb("c:"+this.id+":"),this.transportManager_=new iI(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=Mb(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){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)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=bb("t",e),n=bb("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){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:{}}}))}proceedWithUpgrade_(){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()}onPrimaryMessageReceived_(e){var t=bb("t",e),n=bb("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=bb("t",e);if("d"in e){var n=e.d;if("h"===t)this.onHandshake_(n);else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?_b("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):_b("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&Cb("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Mb(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Mb(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(hb.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class oI{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class aI{constructor(e){this.allowedEvents_=e,this.listeners_={},Yh(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){Yh(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class cI extends aI{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||od()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new cI}getInitialEvent(e){return Yh("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class lI{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function uI(){return new lI("")}function hI(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function dI(e){return e.pieces_.length-e.pieceNum_}function fI(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new lI(e.pieces_,t)}function pI(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function gI(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function mI(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new lI(t,0)}function vI(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof lI)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new lI(n,0)}function yI(e){return e.pieceNum_>=e.pieces_.length}function _I(e,t){var n=hI(e),r=hI(t);if(null===n)return t;if(n===r)return _I(fI(e),fI(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function wI(e,t){var n=gI(e,0),r=gI(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Pb(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function bI(e,t){if(dI(e)!==dI(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function II(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(dI(e)>dI(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class TI{constructor(e,t){this.errorPrefix_=t,this.parts_=gI(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=Ud(this.parts_[n]);EI(this)}}function EI(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+SI(e))}function SI(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class kI extends aI{constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}static getInstance(){return new kI}getInitialEvent(e){return Yh("visible"===e,"Unknown event type: "+e),[this.visible_]}}class CI extends oI{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=CI.nextPersistentConnectionId_++,this.log_=yb("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!hd())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");kI.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&cI.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(_d(i)),Yh(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new rd,r={p:e._path.toString(),q:e._queryObject},t={action:"g",request:r,onComplete:e=>{var t=e.d;"ok"===e.s?(this.onDataUpdate_(r.p,t,!1,null),n.resolve(t)):n.reject(t)}};this.outstandingGets_.push(t),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_||setTimeout(()=>{var e=this.outstandingGets_[i];void 0!==e&&t===e&&(delete this.outstandingGets_[i],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),this.log_("get "+i+" timed out on connection"),n.reject(new Error("Client is offline.")))},3e3),this.connected_&&this.sendGet_(i),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),Yh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Yh(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var o={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),o=i._queryIdentifier;this.log_("Listen on "+s+" for "+o);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;CI.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(o))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,o),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&bd(e,"w")){const i=Id(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),Cb("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} to your security rules for better performance.`))}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=wd(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const r=this.authToken_;var e=function(e){const t=wd(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),Yh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+_d(e));var t=e.r;const n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):_b("Unrecognized action received from server: "+_d(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){Yh(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-e),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)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+CI.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var o=function(){n?n.close():(t=!0,u())};this.realtime_={close:o,sendRequest:function(e){Yh(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var a=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(a),this.appCheckTokenProvider_.getToken(a)]);t?Sb("getToken() completed but was canceled"):(Sb("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new sI(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{Cb(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&Cb(e),o())}}}interrupt(e){Sb("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){Sb("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Td(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>Ib(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new lI(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){Sb("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){Sb("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+eb.replace(/\./g,"-")]=1,od()?e["framework.cordova"]=1:ld()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=cI.getInstance().currentlyOnline();return Td(this.interruptReasons_)&&e}}CI.nextPersistentConnectionId_=0,CI.nextConnectionId_=0;class AI{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new AI(e,t)}}class NI{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new AI(Rb,e),r=new AI(Rb,t);return 0!==this.compare(n,r)}minPost(){return AI.MIN}}let RI;class xI extends NI{static get __EMPTY_NODE(){return RI}static set __EMPTY_NODE(e){RI=e}compare(e,t){return Pb(e.name,t.name)}isDefinedOn(e){throw Jh("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return AI.MIN}maxPost(){return new AI(xb,RI)}makePost(e,t){return Yh("string"==typeof e,"KeyIndex indexValue must always be a string."),new AI(e,RI)}toString(){return".key"}}const PI=new xI;class DI{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class OI{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:OI.RED,this.left=null!=r?r:MI.EMPTY_NODE,this.right=null!=i?i:MI.EMPTY_NODE}copy(e,t,n,r,i){return new OI(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return MI.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return MI.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(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,OI.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,OI.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){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");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}OI.RED=!0,OI.BLACK=!1;class MI{constructor(e,t=MI.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new MI(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,OI.BLACK,null,null))}remove(e){return new MI(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,OI.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new DI(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new DI(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new DI(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new DI(this.root_,null,this.comparator_,!0,e)}}function LI(e,t){return Pb(e.name,t.name)}function FI(e,t){return Pb(e,t)}MI.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new OI(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let UI;function qI(e){return"number"==typeof e?"number:"+Ob(e):"string:"+e}function jI(e){var t;e.isLeafNode()?(t=e.val(),Yh("string"==typeof t||"number"==typeof t||"object"==typeof t&&bd(t,".sv"),"Priority must be a string or number.")):Yh(e===UI||e.isEmpty(),"priority of unexpected type."),Yh(e===UI||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let VI;class BI{constructor(e,t=BI.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,Yh(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),jI(this.priorityNode_)}static set __childrenNodeConstructor(e){VI=e}static get __childrenNodeConstructor(){return VI}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new BI(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:BI.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return yI(e)?this:".priority"===hI(e)?this.priorityNode_:BI.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:BI.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=hI(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(Yh(".priority"!==n||1===dI(e),".priority must be the last token in a path"),this.updateImmediateChild(n,BI.__childrenNodeConstructor.EMPTY_NODE.updateChild(fI(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+qI(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Ob(this.value_):this.value_,this.lazyHash_=ub(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===BI.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof BI.__childrenNodeConstructor?-1:(Yh(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=BI.VALUE_TYPE_ORDER.indexOf(t),i=BI.VALUE_TYPE_ORDER.indexOf(n);return Yh(0<=r,"Unknown leaf type: "+t),Yh(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}BI.VALUE_TYPE_ORDER=["object","boolean","number","string"];let KI,$I;const WI=new class extends NI{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Pb(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return AI.MIN}maxPost(){return new AI(xb,new BI("[PRIORITY-POST]",$I))}makePost(e,t){var n=KI(e);return new AI(t,new BI("[PRIORITY-POST]",n))}toString(){return".priority"}},zI=Math.log(2);class GI{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/zI,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function HI(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new OI(i,r.node,OI.BLACK,null,null);var s=parseInt(n/2,10)+e,o=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new OI(i,r.node,OI.BLACK,o,n)};var n=function(e){let s=null,o=null,a=c.length;function t(e,t){var n=a-e,r=a;a-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{o=e;s=e}}(new OI(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,OI.BLACK):(t(r,OI.BLACK),t(r,OI.RED))}return o}(new GI(c.length));return new MI(t||e,n)}let QI;const YI={};class JI{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return Yh((YI,WI),"ChildrenNode.ts has not been loaded"),QI=QI||new JI({".priority":YI},{".priority":WI}),QI}get(e){var t=Id(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof MI?t:null}hasIndex(e){return bd(this.indexSet_,e.toString())}addIndex(e,t){Yh(e!==PI,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(AI.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?HI(n,e.getCompare()):YI;var a=e.toString();const c=Object.assign({},this.indexSet_);c[a]=e;const l=Object.assign({},this.indexes_);return l[a]=o,new JI(l,c)}addToIndexes(o,a){var e=Ed(this.indexes_,(t,e)=>{const n=Id(this.indexSet_,e);if(Yh(n,"Missing index implementation for "+e),t===YI){if(n.isDefinedOn(o.node)){const i=[],s=a.getIterator(AI.Wrap);let e=s.getNext();for(;e;)e.name!==o.name&&i.push(e),e=s.getNext();return i.push(o),HI(i,n.getCompare())}return YI}{var r=a.get(o.name);let e=t;return r&&(e=e.remove(new AI(o.name,r))),e.insert(o,o.node)}});return new JI(e,this.indexSet_)}removeFromIndexes(n,r){var e=Ed(this.indexes_,e=>{if(e===YI)return e;var t=r.get(n.name);return t?e.remove(new AI(n.name,t)):e});return new JI(e,this.indexSet_)}}let XI;class ZI{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&jI(this.priorityNode_),this.children_.isEmpty()&&Yh(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return XI=XI||new ZI(new MI(FI),null,JI.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||XI}updatePriority(e){return this.children_.isEmpty()?this:new ZI(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?XI:t}getChild(e){var t=hI(e);return null===t?this:this.getImmediateChild(t).getChild(fI(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(Yh(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new AI(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?XI:this.priorityNode_;return new ZI(e,i,t)}}updateChild(e,t){var n=hI(e);if(null===n)return t;Yh(".priority"!==hI(e)||1===dI(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(fI(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,o=!0;if(this.forEachChild(WI,(e,t)=>{r[e]=t.val(n),i++,o&&ZI.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):o=!1}),!n&&o&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+qI(this.getPriority().val())+":"),this.forEachChild(WI,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":ub(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new AI(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new AI(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new AI(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,AI.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,AI.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===t0?-1:0}withIndex(e){if(e===PI||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new ZI(this.children_,this.priorityNode_,t)}isIndexed(e){return e===PI||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(WI),i=n.getIterator(WI);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===PI?null:this.indexMap_.get(e.toString())}}ZI.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class e0 extends ZI{constructor(){super(new MI(FI),ZI.EMPTY_NODE,JI.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ZI.EMPTY_NODE}isEmpty(){return!1}}const t0=new e0;Object.defineProperties(AI,{MIN:{value:new AI(Rb,ZI.EMPTY_NODE)},MAX:{value:new AI(xb,t0)}}),xI.__EMPTY_NODE=ZI.EMPTY_NODE,BI.__childrenNodeConstructor=ZI,ib=t0,UI=ib,sb=t0,$I=sb;const n0=!0;function r0(i,e=null){if(null===i)return ZI.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),Yh(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new BI(t,r0(e))}if(i instanceof Array||!n0){let r=ZI.EMPTY_NODE;return Db(i,(e,t)=>{if(bd(i,e)&&"."!==e.substring(0,1)){const n=r0(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(r0(e))}{const s=[];let r=!1;if(Db(i,(e,t)=>{if("."!==e.substring(0,1)){const n=r0(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new AI(e,n)))}}),0===s.length)return ZI.EMPTY_NODE;var n=HI(s,LI,e=>e.name,FI);if(r){t=HI(s,WI.getCompare());return new ZI(n,r0(e),new JI({".priority":t},{".priority":WI}))}return new ZI(n,r0(e),JI.Default)}}KI=r0;class i0 extends NI{constructor(e){super(),this.indexPath_=e,Yh(!yI(e)&&".priority"!==hI(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?Pb(e.name,t.name):r}makePost(e,t){var n=r0(e),n=ZI.EMPTY_NODE.updateChild(this.indexPath_,n);return new AI(t,n)}maxPost(){var e=ZI.EMPTY_NODE.updateChild(this.indexPath_,t0);return new AI(xb,e)}toString(){return gI(this.indexPath_,0).join("/")}}function s0(e){if(e===""+Ub)return l0;var t=qb(e);if(null!=t)return""+(t+1);const n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e.charAt(i);if(n.length<h0)return n.push(l0),n.join("");let r=n.length-1;for(;0<=r&&n[r]===u0;)r--;return-1===r?xb:(t=n[r],t=c0.charAt(c0.indexOf(t)+1),n[r]=t,n.slice(0,r+1).join(""))}function o0(e){if(e===""+Fb)return Rb;var t=qb(e);if(null!=t)return""+(t-1);const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e.charAt(r);return n[n.length-1]===l0?1===n.length?""+Ub:(delete n[n.length-1],n.join("")):(n[n.length-1]=c0.charAt(c0.indexOf(n[n.length-1])-1),n.join("")+u0.repeat(h0-n.length))}const a0=new class extends NI{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Pb(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return AI.MIN}maxPost(){return AI.MAX}makePost(e,t){var n=r0(e);return new AI(t,n)}toString(){return".value"}},c0="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",l0="-",u0="z",h0=786,d0=function(){let s=0;const o=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=c0.charAt(e%64),e=Math.floor(e/64);Yh(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===o[n];n--)o[n]=0;o[n]++}else for(n=0;n<12;n++)o[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=c0.charAt(o[n]);return Yh(20===i.length,"nextPushId: Length should be 20."),i}}();function f0(e){return{type:"value",snapshotNode:e}}function p0(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function g0(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function m0(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class v0{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){Yh(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(g0(t,o)):Yh(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(p0(t,n)):s.trackChildChange(m0(t,n,o))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(WI,(e,t)=>{n.hasChild(e)||i.trackChildChange(g0(e,t))}),n.isLeafNode()||n.forEachChild(WI,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(m0(e,t,n))}else i.trackChildChange(p0(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ZI.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class y0{constructor(e){this.indexedFilter_=new v0(e.getIndex()),this.index_=e.getIndex(),this.startPost_=y0.getStartPost_(e),this.endPost_=y0.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0}updateChild(e,t,n,r,i,s){return this.matches(new AI(t,n))||(n=ZI.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?ZI.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(ZI.EMPTY_NODE);const i=this;return t.forEachChild(WI,(e,t)=>{i.matches(new AI(e,t))||(r=r.updateImmediateChild(e,ZI.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class _0{constructor(e){this.rangedFilter_=new y0(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new AI(t,n))||(n=ZI.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,o,t){let a;if(o.isLeafNode()||o.isEmpty())a=ZI.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<o.numChildren()&&o.isIndexed(this.index_)){a=ZI.EMPTY_NODE.withIndex(this.index_);let t;t=this.reverse_?o.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):o.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;t.hasNext()&&n<this.limit_;){var r=t.getNext();let e;if(e=this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),r)<=0:this.index_.compare(r,this.rangedFilter_.getEndPost())<=0,!e)break;a=a.updateImmediateChild(r.name,r.node),n++}}else{a=o.withIndex(this.index_),a=a.updatePriority(ZI.EMPTY_NODE);let e,t,n,r;if(this.reverse_){r=a.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),t=this.rangedFilter_.getStartPost();const l=this.index_.getCompare();n=(e,t)=>l(t,e)}else r=a.getIterator(this.index_),e=this.rangedFilter_.getStartPost(),t=this.rangedFilter_.getEndPost(),n=this.index_.getCompare();let i=0,s=!1;for(;r.hasNext();){var c=r.getNext();!s&&n(e,c)<=0&&(s=!0),s&&i<this.limit_&&n(c,t)<=0?i++:a=a.updateImmediateChild(c.name,ZI.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,a,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const o=e;Yh(o.numChildren()===this.limit_,"");var a=new AI(t,n),c=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),l=this.rangedFilter_.matches(a);if(o.hasChild(t)){var u=o.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||o.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,a);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(m0(t,n,u)),o.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(g0(t,u));const f=o.updateImmediateChild(t,ZI.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(p0(e.name,e.node)),f.updateImmediateChild(e.name,e.node)):f}}return!n.isEmpty()&&l&&0<=s(c,a)?(null!=i&&(i.trackChildChange(g0(c.name,c.node)),i.trackChildChange(p0(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,ZI.EMPTY_NODE)):e}}class w0{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=WI}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return Yh(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Yh(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Rb}hasEnd(){return this.endSet_}getIndexEndValue(){return Yh(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Yh(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:xb}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return Yh(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===WI}copy(){const e=new w0;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}}function b0(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function I0(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function T0(e,t){const n=e.copy();return n.index_=t,n}function E0(e){const t={};if(e.isDefault())return t;let n;return n=e.index_===WI?"$priority":e.index_===a0?"$value":e.index_===PI?"$key":(Yh(e.index_ instanceof i0,"Unrecognized index type!"),e.index_.toString()),t.orderBy=_d(n),e.startSet_&&(t.startAt=_d(e.indexStartValue_),e.startNameSet_&&(t.startAt+=","+_d(e.indexStartName_))),e.endSet_&&(t.endAt=_d(e.indexEndValue_),e.endNameSet_&&(t.endAt+=","+_d(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function S0(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_)),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_)),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==WI&&(n.i=t.index_.toString()),n}class k0 extends oI{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=yb("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(Yh(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const o=k0.getListenId_(e,r),a={};this.listens_[o]=a;var n=E0(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),Id(this.listens_,o)===a){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=k0.getListenId_(e,t);delete this.listens_[n]}get(e){var t=E0(e._queryParams);const r=e._path.toString(),i=new rd;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},o){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+Cd(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(o&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=yd(r.responseText)}catch(e){Cb("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&Cb("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class C0{constructor(){this.rootNode_=ZI.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function A0(){return{value:null,children:new Map}}function N0(e,t,n){var r;yI(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=hI(t),e.children.has(r)||e.children.set(r,A0()),N0(e.children.get(r),t=fI(t),n))}function R0(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{R0(t,new lI(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class x0{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&Db(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class P0{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new x0(e);var n=1e4+2e4*Math.random();Mb(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Db(e,(e,t)=>{0<t&&bd(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Mb(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function D0(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function O0(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function M0(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(z=ob=ob||{})[z.OVERWRITE=0]="OVERWRITE",z[z.MERGE=1]="MERGE",z[z.ACK_USER_WRITE=2]="ACK_USER_WRITE",z[z.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class L0{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=ob.ACK_USER_WRITE,this.source=D0()}operationForChild(e){if(yI(this.path)){if(null!=this.affectedTree.value)return Yh(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new lI(e));return new L0(uI(),t,this.revert)}return Yh(hI(this.path)===e,"operationForChild called for unrelated child."),new L0(fI(this.path),this.affectedTree,this.revert)}}class F0{constructor(e,t){this.source=e,this.path=t,this.type=ob.LISTEN_COMPLETE}operationForChild(e){return yI(this.path)?new F0(this.source,uI()):new F0(this.source,fI(this.path))}}class U0{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=ob.OVERWRITE}operationForChild(e){return yI(this.path)?new U0(this.source,uI(),this.snap.getImmediateChild(e)):new U0(this.source,fI(this.path),this.snap)}}class q0{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=ob.MERGE}operationForChild(e){if(yI(this.path)){const t=this.children.subtree(new lI(e));return t.isEmpty()?null:t.value?new U0(this.source,uI(),t.value):new q0(this.source,uI(),t)}return Yh(hI(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new q0(this.source,fI(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class j0{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(yI(e))return this.isFullyInitialized()&&!this.filtered_;var t=hI(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class V0{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function B0(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),K0(n,i,"child_removed",e,r,t),K0(n,i,"child_added",e,r,t),K0(n,i,"child_moved",s,r,t),K0(n,i,"child_changed",e,r,t),K0(n,i,"value",e,r,t),i}function K0(s,o,t,e,a,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw Jh("Should only compare child_ events.");var r=new AI(t.childName,t.snapshotNode),i=new AI(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;a.forEach(e=>{e.respondsTo(t.type)&&o.push(e.createEvent(n,s.query_))})})}function $0(e,t){return{eventCache:e,serverCache:t}}function W0(e,t,n,r){return $0(new j0(t,n,r),e.serverCache)}function z0(e,t,n,r){return $0(e.eventCache,new j0(t,n,r))}function G0(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function H0(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Q0;class Y0{constructor(e,t=(Q0=Q0||new MI(wb),Q0)){this.value=e,this.children=t}static fromObject(e){let n=new Y0(null);return Db(e,(e,t)=>{n=n.set(new lI(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:uI(),value:this.value};if(yI(e))return null;{var n=hI(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(fI(e),t);return null==r?null:{path:vI(new lI(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(yI(e))return this;{var t=hI(e);const n=this.children.get(t);return null!==n?n.subtree(fI(e)):new Y0(null)}}set(e,t){if(yI(e))return new Y0(t,this.children);{var n=hI(e);const i=this.children.get(n)||new Y0(null);var r=i.set(fI(e),t),r=this.children.insert(n,r);return new Y0(this.value,r)}}remove(t){if(yI(t))return this.children.isEmpty()?new Y0(null):new Y0(null,this.children);{var n=hI(t);const r=this.children.get(n);if(r){const i=r.remove(fI(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new Y0(null):new Y0(this.value,e)}return this}}get(e){if(yI(e))return this.value;{var t=hI(e);const n=this.children.get(t);return n?n.get(fI(e)):null}}setTree(t,n){if(yI(t))return n;{var r=hI(t);const i=this.children.get(r)||new Y0(null),s=i.setTree(fI(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new Y0(this.value,e)}}fold(e){return this.fold_(uI(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(vI(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,uI(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(yI(e))return null;{r=hI(e);const i=this.children.get(r);return i?i.findOnPath_(fI(e),vI(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,uI(),t)}foreachOnPath_(e,t,n){if(yI(e))return this;{this.value&&n(t,this.value);var r=hI(e);const i=this.children.get(r);return i?i.foreachOnPath_(fI(e),vI(t,r),n):new Y0(null)}}foreach(e){this.foreach_(uI(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(vI(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class J0{constructor(e){this.writeTree_=e}static empty(){return new J0(new Y0(null))}}function X0(t,n,r){if(yI(n))return new J0(new Y0(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=_I(s,n);return e=e.updateChild(i,r),new J0(t.writeTree_.set(s,e))}s=new Y0(r),s=t.writeTree_.setTree(n,s);return new J0(s)}function Z0(e,n,t){let r=e;return Db(t,(e,t)=>{r=X0(r,vI(n,e),t)}),r}function eT(e,t){if(yI(t))return J0.empty();var n=e.writeTree_.setTree(t,new Y0(null));return new J0(n)}function tT(e,t){return null!=nT(e,t)}function nT(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(_I(n.path,t)):null}function rT(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(WI,(e,t)=>{n.push(new AI(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new AI(e,t.value))}),n}function iT(e,t){if(yI(t))return e;var n=nT(e,t);return null!=n?new J0(new Y0(n)):new J0(e.writeTree_.subtree(t))}function sT(e){return e.writeTree_.isEmpty()}function oT(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(Yh(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(vI(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(vI(i,".priority"),n):s}}}(uI(),e.writeTree_,t)}function aT(e,t){return _T(t,e)}function cT(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);Yh(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,o=!1,a=t.allWrites.length-1;for(;s&&0<=a;){var c=t.allWrites[a];c.visible&&(a>=r&&function(e,t){{if(e.snap)return II(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&II(vI(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:II(i.path,c.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=uT(e.allWrites,lT,uI()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=eT(t.visibleWrites,i.path):Db(i.children,e=>{t.visibleWrites=eT(t.visibleWrites,vI(i.path,e))}),!0)}function lT(e){return e.visible}function uT(e,t,n){let r=J0.empty();for(let s=0;s<e.length;++s){const o=e[s];if(t(o)){var i=o.path;let e;if(o.snap)II(n,i)?(e=_I(n,i),r=X0(r,e,o.snap)):II(i,n)&&(e=_I(i,n),r=X0(r,uI(),o.snap.getChild(e)));else{if(!o.children)throw Jh("WriteRecord should have .snap or .children");if(II(n,i))e=_I(n,i),r=Z0(r,e,o.children);else if(II(i,n))if(e=_I(i,n),yI(e))r=Z0(r,uI(),o.children);else{const a=Id(o.children,hI(e));a&&(i=a.getChild(fI(e)),r=X0(r,uI(),i))}}}}return r}function hT(e,t,n,r,i){if(r||i){var s=iT(e.visibleWrites,t);if(!i&&sT(s))return n;if(i||null!=n||tT(s,uI()))return oT(uT(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(II(e.path,t)||II(t,e.path))},t),n||ZI.EMPTY_NODE);return null}s=nT(e.visibleWrites,t);if(null!=s)return s;s=iT(e.visibleWrites,t);return sT(s)?n:null!=n||tT(s,uI())?oT(s,n||ZI.EMPTY_NODE):null}function dT(e,t,n,r){return hT(e.writeTree,e.treePath,t,n,r)}function fT(e,t){return function(e,t,n){let r=ZI.EMPTY_NODE;const i=nT(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(WI,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=iT(e.visibleWrites,t);return n.forEachChild(WI,(e,t)=>{var n=oT(iT(s,new lI(e)),t);r=r.updateImmediateChild(e,n)}),rT(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return rT(iT(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function pT(e,t,n,r){return function(e,t,n,r,i){Yh(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=vI(t,n);return tT(e.visibleWrites,s)?null:sT(s=iT(e.visibleWrites,s))?i.getChild(n):oT(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function gT(e,t){return n=e.writeTree,t=vI(e.treePath,t),nT(n.visibleWrites,t);var n}function mT(e,t,n,r,i,s){return function(e,t,n,r,i,s,o){let a;var c=iT(e.visibleWrites,t),l=nT(c,uI());if(null!=l)a=l;else{if(null==n)return[];a=oT(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const u=[],h=o.getCompare(),d=s?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function vT(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=vI(e,t=t),null!=(s=nT(r.visibleWrites,i))?s:n.isCompleteForChild(t)?oT(iT(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function yT(e,t){return _T(vI(e.treePath,t),e.writeTree)}function _T(e,t){return{treePath:e,writeTree:t}}class wT{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;Yh("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),Yh(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,m0(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,g0(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,p0(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw Jh("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,m0(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const bT=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class IT{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new j0(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return vT(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:H0(this.viewCache_),r=mT(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function TT(e,t,n,r,i){const s=new wT;let o,a;if(n.type===ob.OVERWRITE){var c=n;o=c.source.fromUser?kT(e,t,c.path,c.snap,r,i,s):(Yh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered()&&!yI(c.path),ST(e,t,c.path,c.snap,r,i,a,s))}else if(n.type===ob.MERGE){c=n;o=c.source.fromUser?function(r,i,s,e,o,a,c){let l=i;return e.foreach((e,t)=>{var n=vI(s,e);CT(i,hI(n))&&(l=kT(r,l,n,t,o,a,c))}),e.foreach((e,t)=>{var n=vI(s,e);CT(i,hI(n))||(l=kT(r,l,n,t,o,a,c))}),l}(e,t,c.path,c.children,r,i,s):(Yh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered(),NT(e,t,c.path,c.children,r,i,a,s))}else if(n.type===ob.ACK_USER_WRITE){var l=n;o=l.revert?function(n,r,i,s,e,o){let a;{if(null!=gT(s,i))return r;{var c=new IT(s,r,e);const u=r.eventCache.getNode();let t;if(yI(i)||".priority"===hI(i)){let e;e=r.serverCache.isFullyInitialized()?dT(s,H0(r)):(l=r.serverCache.getNode(),Yh(l instanceof ZI,"serverChildren would be complete if leaf node"),fT(s,l)),e=e,t=n.filter.updateFullNode(u,e,o)}else{var l=hI(i);let e=vT(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,fI(i),c,o):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,ZI.EMPTY_NODE,fI(i),c,o):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(a=dT(s,H0(r)),a.isLeafNode()&&(t=n.filter.updateFullNode(t,a,o)))}return a=r.serverCache.isFullyInitialized()||null!=gT(s,uI()),W0(r,t,a,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,o,a){if(null!=gT(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(yI(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return ST(e,t,i,l.getNode().getChild(i),s,o,c,a);if(yI(i)){let n=new Y0(null);return l.getNode().forEachChild(PI,(e,t)=>{n=n.set(new lI(e),t)}),NT(e,t,i,n,s,o,c,a)}return t}{let r=new Y0(null);return n.foreach((e,t)=>{var n=vI(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),NT(e,t,i,r,s,o,c,a)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==ob.LISTEN_COMPLETE)throw Jh("Unknown operation type: "+n.type);o=function(e,t,n,r,i){const s=t.serverCache,o=z0(t,s.getNode(),s.isFullyInitialized()||yI(n),s.isFiltered());return ET(e,o,n,r,bT,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=G0(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(f0(G0(t)))}}(t,o,l),{viewCache:o,changes:l}}function ET(r,i,s,o,a,c){const l=i.eventCache;if(null!=gT(o,s))return i;{let t,n;if(yI(s)){var e;Yh(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=fT(o,(e=H0(i))instanceof ZI?e:ZI.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=dT(o,H0(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=hI(s);if(".priority"===u){Yh(1===dI(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=pT(o,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=fI(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=pT(o,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):vT(o,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,a,c):l.getNode()}}return W0(i,t,l.isFullyInitialized()||yI(s),r.filter.filtersNodes())}}function ST(e,t,n,r,i,s,o,a){const c=t.serverCache;let l;const u=o?e.filter:e.filter.getIndexedFilter();if(yI(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=hI(n);if(!c.isCompleteForPath(n)&&1<dI(n))return t;var f=fI(n);const p=c.getNode().getImmediateChild(d);h=p.updateChild(f,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,f,bT,null)}f=z0(t,l,c.isFullyInitialized()||yI(n),u.filtersNodes());return ET(e,f,n,i,new IT(i,f,s),a)}function kT(t,n,r,i,e,s,o){const a=n.eventCache;let c,l;const u=new IT(e,n,s);if(yI(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,o),c=W0(n,l,!0,t.filter.filtersNodes());else{var h=hI(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=W0(n,l,a.isFullyInitialized(),a.isFiltered());else{var d=fI(r);const f=a.getNode().getImmediateChild(h);let e;if(yI(d))e=i;else{const p=u.getCompleteChild(h);e=null!=p?".priority"===pI(d)&&p.getChild(mI(d)).isEmpty()?p:p.updateChild(d,i):ZI.EMPTY_NODE}c=f.equals(e)?n:W0(n,t.filter.updateChild(a.getNode(),h,e,d,u,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return c}function CT(e,t){return e.eventCache.isCompleteForChild(t)}function AT(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function NT(r,i,e,t,s,o,a,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=yI(e)?t:new Y0(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=AT(0,i.serverCache.getNode().getImmediateChild(e),t),l=ST(r,l,new lI(e),n,s,o,a,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&void 0===t.value;u.hasChild(e)||n||(n=AT(0,i.serverCache.getNode().getImmediateChild(e),t),l=ST(r,l,new lI(e),n,s,o,a,c))}),l}class RT{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new v0(n.getIndex()),i=(e=n).loadsAllData()?new v0(e.getIndex()):new(e.hasLimit()?_0:y0)(e);this.processor_={filter:i};const s=t.serverCache,o=t.eventCache;var a=r.updateFullNode(ZI.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(ZI.EMPTY_NODE,o.getNode(),null),a=new j0(a,s.isFullyInitialized(),r.filtersNodes()),c=new j0(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=$0(c,a),this.eventGenerator_=new V0(this.query_)}get query(){return this.query_}}function xT(e){return 0===e.eventRegistrations_.length}function PT(n,r,i){const s=[];if(i){Yh(null==r,"A cancel should cancel all event registrations.");const o=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,o);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const a=n.eventRegistrations_[t];if(a.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(a)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function DT(e,t,n,r){t.type===ob.MERGE&&null!==t.source.queryId&&(Yh(H0(e.viewCache_),"We should always have a full cache before handling merges"),Yh(G0(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=TT(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,Yh(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),Yh(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),Yh(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,OT(e,s.changes,s.viewCache.eventCache.getNode(),null)}function OT(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return B0(e.eventGenerator_,t,n,i)}let MT;class LT{constructor(){this.views=new Map}}function FT(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return Yh(null!=e,"SyncTree gave us an op for an invalid query."),DT(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(DT(s,n,r,i));return e}}function UT(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=dT(r,s?i:null),t=!1;t=!!e||(e=i instanceof ZI?fT(r,i):ZI.EMPTY_NODE,!1);o=$0(new j0(e,t,!1),new j0(i,s,!1));return new RT(n,o)}}function qT(e,t,n,r,i,s){var o=UT(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(WI,(e,t)=>{r.push(p0(e,t))})}return n.isFullyInitialized()&&r.push(f0(n.getNode())),OT(e,r,n.getNode(),t)}(o,n)}function jT(e,t,n,r){var i=t._queryIdentifier;const s=[];let o=[];var a=WT(e);if("default"===i)for(var[c,l]of e.views.entries())o=o.concat(PT(l,n,r)),xT(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(o=o.concat(PT(u,n,r)),xT(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return a&&!WT(e)&&s.push((Yh(MT,"Reference.ts has not been loaded"),new MT(t._repo,t._path))),{removed:s,events:o}}function VT(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function BT(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=H0(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!yI(t)&&!n.getImmediateChild(hI(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function KT(e,t){const n=t._queryParams;if(n.loadsAllData())return zT(e);var r=t._queryIdentifier;return e.views.get(r)}function $T(e,t){return null!=KT(e,t)}function WT(e){return null!=zT(e)}function zT(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let GT;let HT=1;class QT{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Y0(null),this.pendingWriteTree_={visibleWrites:J0.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function YT(e,t,n,r,i){var s,o,a,c;return s=e.pendingWriteTree_,o=t,a=n,c=r,r=i,Yh(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:o,snap:a,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=X0(s.visibleWrites,o,a)),s.lastWriteId=c,i?iE(e,new U0(D0(),t,n)):[]}function JT(e,t,n,r){var i,s,o;i=e.pendingWriteTree_,s=t,o=n,r=r,Yh(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:o,writeId:r,visible:!0}),i.visibleWrites=Z0(i.visibleWrites,s,o),i.lastWriteId=r;var a=Y0.fromObject(n);return iE(e,new q0(D0(),t,a))}function XT(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(cT(e.pendingWriteTree_,t)){let t=new Y0(null);return null!=r.snap?t=t.set(uI(),!0):Db(r.children,e=>{t=t.set(new lI(e),!0)}),iE(e,new L0(r.path,t,n))}return[]}function ZT(e,t,n){return iE(e,new U0(O0(),t,n))}function eE(n,e,t,r){var i=e._path,s=n.syncPointTree_.get(i);let o=[];if(s&&("default"===e._queryIdentifier||$T(s,e))){var a=jT(s,e,t,r);0===s.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(i));const h=a.removed;o=a.events;s=-1!==h.findIndex(e=>e._queryParams.loadsAllData()),a=n.syncPointTree_.findOnPath(i,(e,t)=>WT(t));if(s&&!a){const d=n.syncPointTree_.subtree(i);if(!d.isEmpty()){var c=d.fold((e,t,r)=>{if(t&&WT(t))return[zT(t)];{let n=[];return t&&(n=VT(t)),Db(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e],u=l.query,l=oE(n,l);n.listenProvider_.startListening(dE(u),aE(n,u),l.hashFn,l.onComplete)}}}!a&&0<h.length&&!r&&(s?n.listenProvider_.stopListening(dE(e),null):h.forEach(e=>{var t=n.queryToTagMap.get(cE(e));n.listenProvider_.stopListening(dE(e),t)})),function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=cE(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,h)}return o}function tE(e,t,n){const r=t._path;let i=null,s=!1;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=_I(e,r);i=i||BT(t,n),s=s||WT(t)});let o=e.syncPointTree_.get(r);o?(s=s||WT(o),i=i||BT(o,uI())):(o=new LT,e.syncPointTree_=e.syncPointTree_.set(r,o));let a;if(null!=i)a=!0;else{a=!1,i=ZI.EMPTY_NODE;const d=e.syncPointTree_.subtree(r);d.foreachChild((e,t)=>{var n=BT(t,uI());n&&(i=i.updateImmediateChild(e,n))})}var c,l=$T(o,t);l||t._queryParams.loadsAllData()||(u=cE(t),Yh(!e.queryToTagMap.has(u),"View does not exist, but we have a tag"),c=HT++,e.queryToTagMap.set(u,c),e.tagToQueryMap.set(c,u));var u=aT(e.pendingWriteTree_,r);let h=qT(o,t,n,u,i,a);return l||s||(l=KT(o,t),h=h.concat(function(t,e,n){const r=e._path,i=aE(t,e),s=oE(t,n),o=t.listenProvider_.startListening(dE(e),i,s.hashFn,s.onComplete),a=t.syncPointTree_.subtree(r);if(i)Yh(!WT(a.value),"If we're adding a query, it shouldn't be shadowed");else{var c=a.fold((e,t,r)=>{if(!yI(e)&&t&&WT(t))return[zT(t).query];{let n=[];return t&&(n=n.concat(VT(t).map(e=>e.query))),Db(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(dE(l),aE(t,l))}}return o}(e,t,l))),h}function nE(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=BT(t,_I(e,r));if(n)return n});return hT(n,r,i,t,!0)}function rE(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=_I(e,r);i=i||BT(t,n)});let n=e.syncPointTree_.get(r);n?i=i||BT(n,uI()):(n=new LT,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const o=s?new j0(i,!0,!1):null;var a=aT(e.pendingWriteTree_,t._path);return G0(UT(n,t,a,s?o.getNode():ZI.EMPTY_NODE,s).viewCache_)}function iE(e,t){return function t(n,r,i,s){{if(yI(n.path))return sE(n,r,i,s);{const o=r.get(uI());null==i&&null!=o&&(i=BT(o,uI()));let e=[];const a=hI(n.path),c=n.operationForChild(a),l=r.children.get(a);if(l&&c){const u=i?i.getImmediateChild(a):null,h=yT(s,a);e=e.concat(t(c,l,u,h))}return o&&(e=e.concat(FT(o,n,s,i))),e}}}(t,e.syncPointTree_,null,aT(e.pendingWriteTree_,uI()))}function sE(s,e,o,a){var t=e.get(uI());null==o&&null!=t&&(o=BT(t,uI()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=yT(a,e),i=s.operationForChild(e);i&&(c=c.concat(sE(i,t,n,r)))}),t&&(c=c.concat(FT(t,s,a,o))),c}function oE(i,t){const s=t.query,o=aE(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||ZI.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return o?function(e,t,n){if(s=lE(e,n)){var r=uE(s),i=r.path,s=r.queryId,r=_I(i,t);return hE(e,i,new F0(M0(s),r))}return[]}(i,s._path,o):(t=i,n=s._path,iE(t,new F0(O0(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return eE(i,s,null,r)}}}function aE(e,t){var n=cE(t);return e.queryToTagMap.get(n)}function cE(e){return e._path.toString()+"$"+e._queryIdentifier}function lE(e,t){return e.tagToQueryMap.get(t)}function uE(e){var t=e.indexOf("$");return Yh(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new lI(e.substr(0,t))}}function hE(e,t,n){var r=e.syncPointTree_.get(t);return Yh(r,"Missing sync point for query tag that we're tracking"),FT(r,n,aT(e.pendingWriteTree_,t),null)}function dE(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(Yh(GT,"Reference.ts has not been loaded"),new GT(e._repo,e._path)):e}class fE{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new fE(t)}node(){return this.node_}}class pE{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=vI(this.path_,e);return new pE(this.syncTree_,t)}node(){return nE(this.syncTree_,this.path_)}}function gE(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function mE(e,t,n){return e&&"object"==typeof e?(Yh(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?vE(e[".sv"],t,n):"object"==typeof e[".sv"]?yE(e[".sv"],t):void Yh(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const vE=function(e,t,n){if("timestamp"===e)return n.timestamp;Yh(!1,"Unexpected server value: "+e)},yE=function(e,t,n){e.hasOwnProperty("increment")||Yh(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&Yh(!1,"Unexpected increment value: "+r);const i=t.node();if(Yh(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var o=s.getValue();return"number"!=typeof o?r:o+r},_E=function(e,t,n,r){return bE(t,new pE(n,e),r)},wE=function(e,t,n){return bE(e,new fE(t),n)};function bE(e,r,i){var t=e.getPriority().val(),n=mE(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const o=e;t=mE(o.getValue(),r,i);return t!==o.getValue()||n!==o.getPriority().val()?new BI(t,r0(n)):e}{const a=e;return s=a,n!==a.getPriority().val()&&(s=s.updatePriority(new BI(n))),a.forEachChild(WI,(e,t)=>{var n=bE(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class IE{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function TE(e,t){let n=t instanceof lI?t:new lI(t),r=e,i=hI(n);for(;null!==i;){var s=Id(r.node.children,i)||{children:{},childCount:0};r=new IE(i,r,s),n=fI(n),i=hI(n)}return r}function EE(e){return e.node.value}function SE(e,t){e.node.value=t,NE(e)}function kE(e){return 0<e.node.childCount}function CE(n,r){Db(n.node.children,(e,t)=>{r(new IE(e,n,t))})}function AE(e){return new lI(null===e.parent?e.name:AE(e.parent)+"/"+e.name)}function NE(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===EE(e)&&!kE(e)}(e=e),i=bd(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,NE(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,NE(t)))}function RE(e,t,n,r){r&&void 0===t||KE(Md(e,"value"),t,n)}function xE(e,t,r,n){if(!n||void 0!==t){const i=Md(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];Db(t,(e,t)=>{const n=new lI(e);if(KE(i,t,vI(r,n)),".priority"===pI(n)&&!BE(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=gI(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!qE(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(wI);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&II(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function PE(e,t,n){if(!n||void 0!==t){if(Nb(t))throw new Error(Md(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!BE(t))throw new Error(Md(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function DE(e,t,n,r){if(!(r&&void 0===n||qE(n)))throw new Error(Md(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function OE(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),$E(e,t,n,r)}function ME(e,t){if(".info"===hI(t))throw new Error(e+" failed = Can't modify data under /.info/")}const LE=/[\[\].#$\/\u0000-\u001F\u007F]/,FE=/[\[\].#$\u0000-\u001F\u007F]/,UE=10485760,qE=function(e){return"string"==typeof e&&0!==e.length&&!LE.test(e)},jE=function(e){return"string"==typeof e&&0!==e.length&&!FE.test(e)},VE=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),jE(e)},BE=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Nb(e)||e&&"object"==typeof e&&bd(e,".sv")},KE=function(o,e,t){const a=t instanceof lI?new TI(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+SI(a));if("function"==typeof e)throw new Error(o+"contains a function "+SI(a)+" with contents = "+e.toString());if(Nb(e))throw new Error(o+"contains "+e.toString()+" "+SI(a));if("string"==typeof e&&e.length>UE/3&&Ud(e)>UE)throw new Error(o+"contains a string greater than "+UE+" utf8 bytes "+SI(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Db(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!qE(e)))throw new Error(o+" contains an invalid key ("+e+") "+SI(a)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=a,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=Ud(e),EI(n),KE(o,t,a),t=a,r=t.parts_.pop(),t.byteLength_-=Ud(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(o+' contains ".value" child '+SI(a)+" in addition to actual children.")}},$E=function(e,t,n,r){if(!(r&&void 0===n||jE(n)))throw new Error(Md(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},WE=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!qE(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!VE(n))throw new Error(Md(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class zE{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function GE(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||bI(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function HE(e,t,n){GE(e,n),YE(e,e=>bI(e,t))}function QE(e,t,n){GE(e,n),YE(e,e=>II(e,t)||II(t,e))}function YE(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),mb&&Sb("event: "+r.toString()),jb(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const JE="repo_interrupt",XE=25;class ZE{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new zE,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=A0(),this.transactionQueueTree_=new IE,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function eS(o,e,t){if(o.stats_=Xb(o.repoInfo_),o.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())o.server_=new k0(o.repoInfo_,(e,t,n,r)=>{rS(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>iS(o,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{_d(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}o.persistentConnection_=new CI(o.repoInfo_,e,(e,t,n,r)=>{rS(o,e,t,n,r)},e=>{iS(o,e)},e=>{var n;n=o,Db(e,(e,t)=>{sS(n,e,t)})},o.authTokenProvider_,o.appCheckProvider_,t),o.server_=o.persistentConnection_}var n;o.authTokenProvider_.addTokenChangeListener(e=>{o.server_.refreshAuthToken(e)}),o.appCheckProvider_.addTokenChangeListener(e=>{o.server_.refreshAppCheckToken(e.token)}),o.statsReporter_=(e=o.repoInfo_,t=()=>new P0(o.stats_,o.server_),n=e.toString(),Jb[n]||(Jb[n]=t()),Jb[n]),o.infoData_=new C0,o.infoSyncTree_=new QT({startListening:(e,t,n,r)=>{let i=[];const s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=ZT(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),sS(o,"connected",!1),o.serverSyncTree_=new QT({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);QE(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function tS(e){const t=e.infoData_.getNode(new lI(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function nS(e){return gE({timestamp:tS(e)})}function rS(e,t,n,r,i){e.dataUpdateCount++;var s,o,a=new lI(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=Ed(n,e=>r0(e)),function(e,t,n,r){if(a=lE(e,r)){var i=uE(a),s=i.path,o=i.queryId,a=_I(s,t),i=Y0.fromObject(n);return hE(e,s,new q0(M0(o),a,i))}return[]}(e.serverSyncTree_,a,s,i)):(s=r0(n),function(e,t,n,r){if(null==(s=lE(e,r)))return[];var i=(o=uE(s)).path,s=o.queryId,o=_I(i,t);return hE(e,i,new U0(M0(s),o,n))}(e.serverSyncTree_,a,s,i)):r?(o=Ed(n,e=>r0(e)),t=e.serverSyncTree_,i=a,r=o,o=Y0.fromObject(r),iE(t,new q0(O0(),i,o))):(o=r0(n),ZT(e.serverSyncTree_,a,o));let l=a;0<c.length&&(l=mS(e,a)),QE(e.eventQueue_,l,c)}function iS(e,t){sS(e,"connected",t),!1===t&&function(r){dS(r,"onDisconnectEvents");const i=nS(r),s=A0();R0(r.onDisconnect_,uI(),(e,t)=>{var n=_E(e,t,r.serverSyncTree_,i);N0(s,e,n)});let o=[];R0(s,uI(),(e,t)=>{o=o.concat(ZT(r.serverSyncTree_,e,t));var n=wS(r,e);mS(r,n)}),r.onDisconnect_=A0(),QE(r.eventQueue_,uI(),o)}(e)}function sS(e,t,n){var r=new lI("/.info/"+t),i=r0(n);e.infoData_.updateSnapshot(r,i);i=ZT(e.infoSyncTree_,r,i);QE(e.eventQueue_,r,i)}function oS(e){return e.nextWriteId_++}function aS(r,i,e,t,s){dS(r,"set",{path:i.toString(),value:e,priority:t});var n=nS(r);const o=r0(e,t);var a=nE(r.serverSyncTree_,i),n=wE(o,a,n);const c=oS(r);n=YT(r.serverSyncTree_,i,n,c,!0);GE(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e;n||Cb("set at "+i+" failed: "+e);n=XT(r.serverSyncTree_,c,!n);QE(r.eventQueue_,i,n),fS(0,s,e,t)});n=wS(r,i);mS(r,n),QE(r.eventQueue_,n,[])}function cS(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(yI(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(WI,(e,t)=>{N0(n,new lI(e),t)}),e(n,t)}}if(0<n.children.size){var r=hI(t);return t=fI(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),fS(0,i,e,t)})}function lS(n,r,e,i){const s=r0(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&N0(n.onDisconnect_,r,s),fS(0,i,e,t)})}function uS(e,t,n){let r;r=".info"===hI(t._path)?eE(e.infoSyncTree_,t,n):eE(e.serverSyncTree_,t,n),HE(e.eventQueue_,t._path,r)}function hS(e){e.persistentConnection_&&e.persistentConnection_.interrupt(JE)}function dS(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),Sb(n,...t)}function fS(e,r,i,s){r&&jb(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function pS(e,t,n){return nE(e.serverSyncTree_,t,n)||ZI.EMPTY_NODE}function gS(t,e=t.transactionQueueTree_){if(e||_S(t,e),EE(e)){const n=yS(t,e);Yh(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,o){const e=o.map(e=>e.currentWriteId),t=pS(i,s,e);let n=t;var r=t.hash();for(let u=0;u<o.length;u++){const h=o[u];Yh(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var a=_I(s,h.path);n=n.updateChild(a,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{dS(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<o.length;e++)o[e].status=2,n=n.concat(XT(i.serverSyncTree_,o[e].currentWriteId)),o[e].onComplete&&r.push(()=>o[e].onComplete(null,!0,o[e].currentOutputSnapshotResolved)),o[e].unwatcher();_S(i,TE(i.transactionQueueTree_,s)),gS(i,i.transactionQueueTree_),QE(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)jb(r[t])}else{if("datastale"===t)for(let e=0;e<o.length;e++)3===o[e].status?o[e].status=4:o[e].status=0;else{Cb("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<o.length;e++)o[e].status=4,o[e].abortReason=t}mS(i,s)}},r)}(t,AE(e),n)}else kE(e)&&CE(e,e=>{gS(t,e)})}function mS(e,t){var n=vS(e,t),r=AE(n);return function(i,s,o){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var a=_I(o,h.path);let e=!1,t;if(Yh(null!==a,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(XT(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=XE)e=!0,t="maxretry",n=n.concat(XT(i.serverSyncTree_,h.currentWriteId,!0));else{const d=pS(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){KE("transaction failed: Data returned ",c,h.path);let e=r0(c);"object"==typeof c&&null!=c&&bd(c,".priority")||(e=e.updatePriority(d.getPriority()));a=h.currentWriteId,c=nS(i),c=wE(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=oS(i),u.splice(u.indexOf(a),1),n=n.concat(YT(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(XT(i.serverSyncTree_,a,!0))}else e=!0,t="nodata",n=n.concat(XT(i.serverSyncTree_,h.currentWriteId,!0))}QE(i.eventQueue_,o,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}_S(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)jb(l[e]);gS(i,i.transactionQueueTree_)}}(e,yS(e,n),r),r}function vS(e,t){let n,r=e.transactionQueueTree_;for(n=hI(t);null!==n&&void 0===EE(r);)r=TE(r,n),t=fI(t),n=hI(t);return r}function yS(e,t){const n=[];return function t(n,e,r){const i=EE(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);CE(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function _S(t,n){const r=EE(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,SE(n,0<r.length?r:void 0)}CE(n,e=>{_S(t,e)})}function wS(t,e){var n=AE(vS(t,e)),r=TE(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{bS(t,e)}),bS(t,r),function t(e,n,r,i){r&&!i&&n(e),CE(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{bS(t,e)}),n}function bS(i,s){const o=EE(s);if(o){const a=[];let e=[],t=-1;for(let n=0;n<o.length;n++)3===o[n].status||(1===o[n].status?(Yh(t===n-1,"All SENT items should be at beginning of queue."),t=n,o[n].status=3,o[n].abortReason="set"):(Yh(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(XT(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?SE(s,void 0):o.length=t+1,QE(i.eventQueue_,AE(s),e);for(let r=0;r<a.length;r++)jb(a[r])}}const IS=function(e,t){var n=TS(e),r=n.namespace;"firebase.com"===n.domain&&kb(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||kb("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Ab();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Gb(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new lI(n.pathString)}},TS=function(r){let i="",s="",o="",a="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(a=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,f=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):Cb(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const p=i.slice(0,e);"localhost"===p.toLowerCase()?s="localhost":p.split(".").length<=2?s=p:(d=i.indexOf("."),o=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=o),"ns"in f&&(c=f.ns)}return{host:i,port:h,domain:s,subdomain:o,secure:l,scheme:u,pathString:a,namespace:c}};class ES{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+_d(this.snapshot.exportVal())}}class SS{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class kS{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return Yh(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class CS{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new rd;return cS(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){ME("OnDisconnect.remove",this._path);const e=new rd;return lS(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){ME("OnDisconnect.set",this._path),RE("OnDisconnect.set",e,this._path,!1);const t=new rd;return lS(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){ME("OnDisconnect.setWithPriority",this._path),RE("OnDisconnect.setWithPriority",e,this._path,!1),PE("OnDisconnect.setWithPriority",t,!1);const n=new rd;return function(n,r,e,t,i){const s=r0(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&N0(n.onDisconnect_,r,s),fS(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){ME("OnDisconnect.update",this._path),xE("OnDisconnect.update",e,this._path,!1);const t=new rd;return function(r,i,n,s){if(Td(n))return Sb("onDisconnect().update() called with empty data. Don't do anything."),fS(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Db(n,(e,t)=>{var n=r0(t);N0(r.onDisconnect_,vI(i,e),n)}),fS(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class AS{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return yI(this._path)?null:pI(this._path)}get ref(){return new PS(this._repo,this._path)}get _queryIdentifier(){var e=S0(this._queryParams),e=Ib(e);return"{}"===e?"default":e}get _queryObject(){return S0(this._queryParams)}isEqual(e){if(!((e=$d(e))instanceof AS))return!1;var t=this._repo===e._repo,n=bI(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function NS(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function RS(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===PI){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==Rb)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==xb)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===WI){if(null!=t&&!BE(t)||null!=n&&!BE(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(Yh(e.getIndex()instanceof i0||e.getIndex()===a0,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function xS(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class PS extends AS{constructor(e,t){super(e,t,new w0,!1)}get parent(){var e=mI(this._path);return null===e?null:new PS(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class DS{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new lI(e),n=LS(this.ref,e);return new DS(this._node.getChild(t),n,WI)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new DS(t,LS(this.ref,e),WI)))}hasChild(e){var t=new lI(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function OS(e,t){return(e=$d(e))._checkNotDeleted("ref"),void 0!==t?LS(e._root,t):e._root}function MS(e,t){(e=$d(e))._checkNotDeleted("refFromURL");const n=IS(t,e._repo.repoInfo_.nodeAdmin);WE("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||kb("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),OS(e,n.path.toString())}function LS(e,t){return(null===hI((e=$d(e))._path)?OE:$E)("child","path",t,!1),new PS(e._repo,vI(e._path,t))}function FS(e,t){e=$d(e),ME("set",e._path),RE("set",t,e._path,!1);const n=new rd;return aS(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function US(e,t){xE("update",t,e._path,!1);const n=new rd;return function(i,s,e,o){dS(i,"update",{path:s.toString(),value:e});let n=!0;const r=nS(i),a={};if(Db(e,(e,t)=>{n=!1,a[e]=_E(vI(s,e),r0(t),i.serverSyncTree_,r)}),n)Sb("update() called with empty data. Don't do anything."),fS(0,o,"ok",void 0);else{const c=oS(i);var t=JT(i.serverSyncTree_,s,a,c);GE(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||Cb("update at "+s+" failed: "+e);var r=XT(i.serverSyncTree_,c,!n),n=0<r.length?mS(i,s):s;QE(i.eventQueue_,n,r),fS(0,o,e,t)}),Db(e,e=>{var t=wS(i,vI(s,e));mS(i,t)}),QE(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function qS(t){return t=$d(t),r=t._repo,i=t,(null!=(e=rE(r.serverSyncTree_,i))?Promise.resolve(e):r.server_.get(i).then(e=>{var t=r0(e).withIndex(i._queryParams.getIndex()),n=ZT(r.serverSyncTree_,i._path,t);return HE(r.eventQueue_,i._path,n),Promise.resolve(t)},e=>(dS(r,"get for query "+_d(i)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new DS(e,new PS(t._repo,t._path),t._queryParams.getIndex()));var r,i,e}class jS{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new ES("value",this,new DS(e.snapshotNode,new PS(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new SS(this,e,t):null}matches(e){return e instanceof jS&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class VS{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new SS(this,e,t):null}createEvent(e,t){Yh(null!=e.childName,"Child events should have a childName.");var n=LS(new PS(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new ES(e.type,this,new DS(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof VS&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function BS(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var o=(e,t)=>{uS(n._repo,n,a),c(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new kS(t,s||void 0);const a="value"===e?new jS(o):new VS(e,o);return function(e,t,n){let r;r=".info"===hI(t._path)?tE(e.infoSyncTree_,t,n):tE(e.serverSyncTree_,t,n),HE(e.eventQueue_,t._path,r)}(n._repo,n,a),()=>uS(n._repo,n,a)}function KS(e,t,n,r){return BS(e,"value",t,n,r)}function $S(e,t,n,r){return BS(e,"child_added",t,n,r)}function WS(e,t,n,r){return BS(e,"child_changed",t,n,r)}function zS(e,t,n,r){return BS(e,"child_moved",t,n,r)}function GS(e,t,n,r){return BS(e,"child_removed",t,n,r)}function HS(e,t,n){let r=null;var i=n?new kS(n):null;"value"===t?r=new jS(i):t&&(r=new VS(t,i)),uS(e._repo,e,r)}class QS{}class YS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("endAt",this._value,e._path,!0);var t=I0(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class JS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r,i;return i=e.index_===PI?I0(e,t="string"==typeof t?o0(t):t,n):(r=null==n?Rb:o0(n),I0(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class XS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("startAt",this._value,e._path,!0);var t=b0(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class ZS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("startAfter",this._value,e._path,!1);var t=function(t,n,r){let i;if(t.index_===PI)"string"==typeof n&&(n=s0(n)),i=b0(t,n,r);else{let e;e=null==r?xb:s0(r),i=b0(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class ek extends QS{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new AS(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class tk extends QS{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new AS(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class nk extends QS{constructor(e){super(),this._path=e}_apply(e){NS(e,"orderByChild");var t=new lI(this._path);if(yI(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new i0(t),t=T0(e._queryParams,t);return RS(t),new AS(e._repo,e._path,t,!0)}}class rk extends QS{_apply(e){NS(e,"orderByKey");var t=T0(e._queryParams,PI);return RS(t),new AS(e._repo,e._path,t,!0)}}class ik extends QS{_apply(e){NS(e,"orderByPriority");var t=T0(e._queryParams,WI);return RS(t),new AS(e._repo,e._path,t,!0)}}class sk extends QS{_apply(e){NS(e,"orderByValue");var t=T0(e._queryParams,a0);return RS(t),new AS(e._repo,e._path,t,!0)}}class ok extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(RE("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new YS(this._value,this._key)._apply(new XS(this._value,this._key)._apply(e))}}function ak(e,...t){let n=$d(e);for(const r of t)n=r._apply(n);return n}ab=PS,Yh(!MT,"__referenceConstructor has already been defined"),MT=ab,cb=PS,Yh(!GT,"__referenceConstructor has already been defined"),GT=cb;const ck="FIREBASE_DATABASE_EMULATOR_HOST",lk={};let uk=!1;function hk(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||kb("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Sb("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o=IS(s,i),a=o.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[ck]),l?(c=!0,s=`http://${l}?ns=${a.namespace}`,o=IS(s,i),a=o.repoInfo):c=!o.repoInfo.secure;var u=i&&c?new Kb(Kb.OWNER):new Bb(e.name,e.options,t);WE("Invalid Firebase Database URL",o),yI(o.path)||kb("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=lk[t.name];i||(i={},lk[t.name]=i);var s=i[e.toURLString()];s&&kb("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new ZE(e,uk,n,r),i[e.toURLString()]=s}(a,e,u,new Vb(e.name,n));return new dk(u,e)}class dk{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(eS(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new PS(this._repo,uI())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=lk[t];n&&n[e.key]===e||kb(`Database ${t}(${e.repoInfo_}) has already been deleted.`),hS(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&kb("Cannot call "+e+" on a deleted database.")}}function fk(e,t,n,r={}){(e=$d(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&kb("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let o=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&kb('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Kb(Kb.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:id(r.mockUserToken,e.app.options.projectId),o=new Kb(i)),r=s,e=t,t=n,n=o,r.repoInfo_=new Gb(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams),n&&(r.authTokenProvider_=n)}function pk(e){(e=$d(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(JE)}function gk(e,t){Eb(e,t)}const mk={".sv":"timestamp"};class vk{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function yk(i,e,t){if(i=$d(i),ME("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new rd;var r=KS(i,()=>{});return function(t,n,e,r,i,s){dS(t,"transaction on "+n);const o={path:n,update:e,onComplete:r,status:null,order:pb(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=pS(t,n,void 0);o.currentInputSnapshot=a;var c=o.update(a.val());if(void 0===c)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{KE("transaction failed: Data returned ",c,o.path),o.status=0;var l=TE(t.transactionQueueTree_,n);const u=EE(l)||[];u.push(o),SE(l,u);let e;if("object"==typeof c&&null!==c&&bd(c,".priority"))e=Id(c,".priority"),Yh(BE(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=nE(t.serverSyncTree_,n)||ZI.EMPTY_NODE;e=h.getPriority().val()}l=nS(t),c=r0(c,e),l=wE(c,a,l);o.currentOutputSnapshotRaw=c,o.currentOutputSnapshotResolved=l,o.currentWriteId=oS(t);l=YT(t.serverSyncTree_,n,l,o.currentWriteId,o.applyLocally);QE(t.eventQueue_,n,l),gS(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new DS(n,new PS(i._repo,i._path),WI),s.resolve(new vk(t,r)))},r,n),s.promise}CI.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},CI.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},tb(Tf),_f(new Xd("database",(e,{instanceIdentifier:t})=>{return hk(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),Cf(Zw,"0.12.8",lb),Cf(Zw,"0.12.8","esm2017");function _k(e){var t="FIREBASE WARNING: "+e;wk.warn(t)}const wk=new cf("@firebase/database-compat");class bk{constructor(e){this._delegate=e}cancel(t){Od("OnDisconnect.cancel",0,1,arguments.length),Ld("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Od("OnDisconnect.remove",0,1,arguments.length),Ld("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Od("OnDisconnect.set",1,2,arguments.length),Ld("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Od("OnDisconnect.setWithPriority",2,3,arguments.length),Ld("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Od("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,_k("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}Ld("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class Ik{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Od("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class Tk{constructor(e,t){this._database=e,this._delegate=t}val(){return Od("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Od("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Od("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Od("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Od("DataSnapshot.child",0,1,arguments.length),e=String(e),$E("DataSnapshot.child","path",e,!1),new Tk(this._database,this._delegate.child(e))}hasChild(e){return Od("DataSnapshot.hasChild",1,1,arguments.length),$E("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Od("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Od("DataSnapshot.forEach",1,1,arguments.length),Ld("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new Tk(this._database,e)))}hasChildren(){return Od("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Od("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Od("DataSnapshot.ref",0,0,arguments.length),new Sk(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class Ek{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Od("Query.on",2,4,arguments.length),Ld("Query.on","callback",n,!1);const s=Ek.getCancelAndContextArgs_("Query.on",t,r);var o=(e,t)=>{n.call(s.context,new Tk(this.database,e),t)};o.userCallback=n,o.context=s.context;var a=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return KS(this._delegate,o,a),n;case"child_added":return $S(this._delegate,o,a),n;case"child_removed":return GS(this._delegate,o,a),n;case"child_changed":return WS(this._delegate,o,a),n;case"child_moved":return zS(this._delegate,o,a),n;default:throw new Error(Md("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Od("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(Md(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),Ld("Query.off","callback",t,!0),Fd("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,HS(this._delegate,e,r)):HS(this._delegate,e)}get(){return qS(this._delegate).then(e=>new Tk(this.database,e))}once(e,r,t,n){Od("Query.once",1,4,arguments.length),Ld("Query.once","callback",r,!0);const i=Ek.getCancelAndContextArgs_("Query.once",t,n),s=new rd;var o=(e,t)=>{var n=new Tk(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};o.userCallback=r,o.context=i.context;var a=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":KS(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":$S(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":GS(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":WS(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":zS(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(Md("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return Od("Query.limitToFirst",1,1,arguments.length),new Ek(this.database,ak(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new ek(e)}(e)))}limitToLast(e){return Od("Query.limitToLast",1,1,arguments.length),new Ek(this.database,ak(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new tk(e)}(e)))}orderByChild(e){return Od("Query.orderByChild",1,1,arguments.length),new Ek(this.database,ak(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return $E("orderByChild","path",e,!1),new nk(e)}(e)))}orderByKey(){return Od("Query.orderByKey",0,0,arguments.length),new Ek(this.database,ak(this._delegate,new rk))}orderByPriority(){return Od("Query.orderByPriority",0,0,arguments.length),new Ek(this.database,ak(this._delegate,new ik))}orderByValue(){return Od("Query.orderByValue",0,0,arguments.length),new Ek(this.database,ak(this._delegate,new sk))}startAt(e=null,t){return Od("Query.startAt",0,2,arguments.length),new Ek(this.database,ak(this._delegate,([e=null,t]=[e,t],DE("startAt","key",t,!0),new XS(e,t))))}startAfter(e=null,t){return Od("Query.startAfter",0,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("startAfter","key",t,!0),new ZS(e,t))))}endAt(e=null,t){return Od("Query.endAt",0,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("endAt","key",t,!0),new YS(e,t))))}endBefore(e=null,t){return Od("Query.endBefore",0,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("endBefore","key",t,!0),new JS(e,t))))}equalTo(e,t){return Od("Query.equalTo",1,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("equalTo","key",t,!0),new ok(e,t))))}toString(){return Od("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Od("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Od("Query.isEqual",1,1,arguments.length),e instanceof Ek)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,Ld(e,"cancel",r.cancel,!0),r.context=n,Fd(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(Md(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new Sk(this.database,new PS(this._delegate._repo,this._delegate._path))}}class Sk extends Ek{constructor(e,t){super(e,new AS(t._repo,t._path,new w0,!1)),this.database=e,this._delegate=t}getKey(){return Od("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Od("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new Sk(this.database,LS(this._delegate,e))}getParent(){Od("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new Sk(this.database,e):null}getRoot(){return Od("Reference.root",0,0,arguments.length),new Sk(this.database,this._delegate.root)}set(e,t){Od("Reference.set",1,2,arguments.length),Ld("Reference.set","onComplete",t,!0);const n=FS(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Od("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,_k("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}ME("Reference.update",this._delegate._path),Ld("Reference.update","onComplete",n,!0);const e=US(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Od("Reference.setWithPriority",2,3,arguments.length),Ld("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(ME("setWithPriority",e._path),RE("setWithPriority",t,e._path,!1),PE("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new rd;return aS(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Od("Reference.remove",0,1,arguments.length),Ld("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,ME("remove",n._path),FS(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Od("Reference.transaction",1,3,arguments.length),Ld("Reference.transaction","transactionUpdate",e,!1),Ld("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(Md(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=yk(this._delegate,e,{applyLocally:n}).then(e=>new Ik(e.committed,new Tk(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Od("Reference.setPriority",1,2,arguments.length),Ld("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=$d(e),ME("setPriority",e._path),PE("setPriority",t,!1);const n=new rd;return aS(e._repo,vI(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Od("Reference.push",0,2,arguments.length),Ld("Reference.push","onComplete",t,!0);const n=function(e,t){e=$d(e),ME("push",e._path),RE("push",t,e._path,!0);var n=tS(e._repo),n=d0(n);const r=LS(e,n),i=LS(e,n);let s;return s=null!=t?FS(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new Sk(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new Sk(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return ME("Reference.onDisconnect",this._delegate._path),new bk(new CS(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class kk{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete()}}useEmulator(e,t,n={}){fk(this._delegate,e,t,n)}ref(e){if(Od("database.ref",0,1,arguments.length),e instanceof Sk){var t=MS(this._delegate,e.toString());return new Sk(this,t)}t=OS(this._delegate,e);return new Sk(this,t)}refFromURL(e){Od("database.refFromURL",1,1,arguments.length);var t=MS(this._delegate,e);return new Sk(this,t)}goOffline(){var e;Od("database.goOffline",0,0,arguments.length),(e=$d(e=this._delegate))._checkNotDeleted("goOffline"),hS(e._repo)}goOnline(){return Od("database.goOnline",0,0,arguments.length),pk(this._delegate)}}kk.ServerValue={TIMESTAMP:mk,increment:e=>({".sv":{increment:e}})};var Ck,Ak=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){tb(n);const o=new ef("auth-internal",new tf("database-standalone"));return o.setComponent(new Xd("auth-internal",()=>r,"PRIVATE")),{instance:new kk(hk(e,o,void 0,t,s),e),namespace:i}}});const Nk=kk.ServerValue;(Ck=zf).INTERNAL.registerComponent(new Xd("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new kk(r,n)},"PUBLIC").setServiceProps({Reference:Sk,Query:Ek,Database:kk,DataSnapshot:Tk,enableLogging:gk,INTERNAL:Ak,ServerValue:Nk}).setMultipleInstances(!0)),Ck.registerVersion("@firebase/database-compat","0.1.8");var l="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Rk={},xk=l||self;function Pk(){}function Dk(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Ok(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Mk="closure_uid_"+(1e9*Math.random()>>>0),Lk=0;function Fk(e,t,n){return e.call.apply(e.bind,arguments)}function Uk(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function qk(e,t,n){return(qk=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Fk:Uk).apply(null,arguments)}function jk(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function Vk(e,s){function t(){}t.prototype=s.prototype,e.Z=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Vb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function Bk(){this.s=this.s,this.o=this.o}var Kk={};Bk.prototype.s=!1,Bk.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,Mk)&&t[Mk]||(t[Mk]=++Lk),delete Kk[e])},Bk.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const $k=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1},Wk=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){var r=e.length,i="string"==typeof e?e.split(""):e;for(let s=0;s<r;s++)s in i&&t.call(n,i[s],s,e)};function zk(){return Array.prototype.concat.apply([],arguments)}function Gk(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function Hk(e){return/^[\s\xa0]*$/.test(e)}var Qk,Yk=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function Jk(e,t){return-1!=e.indexOf(t)}function Xk(e,t){return e<t?-1:t<e?1:0}e:{var Zk=xk.navigator;if(Zk){Zk=Zk.userAgent;if(Zk){Qk=Zk;break e}}Qk=""}function eC(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function tC(e){const t={};for(const n in e)t[n]=e[n];return t}var nC="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function rC(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<nC.length;e++)n=nC[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function iC(e){return iC[" "](e),e}iC[" "]=Pk;var sC,oC=Jk(Qk,"Opera"),aC=Jk(Qk,"Trident")||Jk(Qk,"MSIE"),cC=Jk(Qk,"Edge"),lC=cC||aC,uC=Jk(Qk,"Gecko")&&!(Jk(Qk.toLowerCase(),"webkit")&&!Jk(Qk,"Edge"))&&!(Jk(Qk,"Trident")||Jk(Qk,"MSIE"))&&!Jk(Qk,"Edge"),hC=Jk(Qk.toLowerCase(),"webkit")&&!Jk(Qk,"Edge");function dC(){var e=xk.document;return e?e.documentMode:void 0}e:{var fC="",pC=(pC=Qk,uC?/rv:([^\);]+)(\)|;)/.exec(pC):cC?/Edge\/([\d\.]+)/.exec(pC):aC?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(pC):hC?/WebKit\/(\S+)/.exec(pC):oC?/(?:Version)[ \/]?(\S+)/.exec(pC):void 0);if(pC&&(fC=pC?pC[1]:""),aC){pC=dC();if(null!=pC&&pC>parseFloat(fC)){sC=String(pC);break e}}sC=fC}var gC={};function mC(){return e=function(){let e=0;var t=Yk(String(sC)).split("."),n=Yk("9").split("."),r=Math.max(t.length,n.length);for(let o=0;0==e&&o<r;o++)for(var i=t[o]||"",s=n[o]||"";i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],(0!=i[0].length||0!=s[0].length)&&(e=Xk(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||Xk(0==i[2].length,0==s[2].length)||Xk(i[2],s[2]),i=i[3],s=s[3],0==e););return 0<=e},t=gC,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var vC=xk.document&&aC&&(dC()||parseInt(sC,10))||void 0,yC=function(){if(!xk.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{xk.addEventListener("test",Pk,t),xk.removeEventListener("test",Pk,t)}catch(e){}return e}();function _C(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function wC(e,t){if(_C.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(uC){e:{try{iC(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:bC[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&wC.Z.h.call(this)}}_C.prototype.h=function(){this.defaultPrevented=!0},Vk(wC,_C);var bC={2:"touch",3:"pen",4:"mouse"};wC.prototype.h=function(){wC.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var IC="closure_listenable_"+(1e6*Math.random()|0),TC=0;function EC(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ia=i,this.key=++TC,this.ca=this.fa=!1}function SC(e){e.ca=!0,e.listener=null,e.proxy=null,e.src=null,e.ia=null}function kC(e){this.src=e,this.g={},this.h=0}function CC(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=$k(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(SC(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function AC(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.ca&&s.listener==t&&s.capture==!!n&&s.ia==r)return i}return-1}kC.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=AC(e,t,r,i);return-1<o?(t=e[o],n||(t.fa=!1)):((t=new EC(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var NC="closure_lm_"+(1e6*Math.random()|0),RC={};function xC(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);return null}r=UC(r);return t&&t[IC]?t.O(n,r,Ok(i)?!!i.capture:!!i,s):PC(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)xC(e,t[s],n,r,i);return null}return n=UC(n),e&&e[IC]?e.N(t,n,Ok(r)?!!r.capture:!!r,i):PC(e,t,n,!1,r,i)}function PC(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o,a=Ok(i)?!!i.capture:!!i,c=LC(e);if(c||(e[NC]=c=new kC(e)),(n=c.add(t,n,r,a,s)).proxy)return n;if(o=MC,r=function e(t){return o.call(e.src,e.listener,t)},(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!yC?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(OC(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function DC(e){var t,n,r;"number"!=typeof e&&e&&!e.ca&&((t=e.src)&&t[IC]?CC(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(OC(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=LC(t))?(CC(n,e),0==n.h&&(n.src=null,t[NC]=null)):SC(e)))}function OC(e){return e in RC?RC[e]:RC[e]="on"+e}function MC(e,t){var n,r;return e=!!e.ca||(t=new wC(t,this),n=e.listener,r=e.ia||e.src,e.fa&&DC(e),n.call(r,t))}function LC(e){return(e=e[NC])instanceof kC?e:null}var FC="__closure_events_fn_"+(1e9*Math.random()>>>0);function UC(t){return"function"==typeof t?t:(t[FC]||(t[FC]=function(e){return t.handleEvent(e)}),t[FC])}function qC(){Bk.call(this),this.i=new kC(this),(this.P=this).I=null}function jC(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new _C(t,e):t instanceof _C?t.target=t.target||e:(o=t,rC(t=new _C(r,e),o)),o=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],o=VC(s,r,!0,t)&&o;if(o=VC(s=t.g=e,r,!0,t)&&o,o=VC(s,r,!1,t)&&o,n)for(i=0;i<n.length;i++)o=VC(s=t.g=n[i],r,!1,t)&&o}function VC(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o,a,c=t[s];c&&!c.ca&&c.capture==n&&(o=c.listener,a=c.ia||c.src,c.fa&&CC(e.i,c),i=!1!==o.call(a,r)&&i)}return i&&!r.defaultPrevented}Vk(qC,Bk),qC.prototype[IC]=!0,qC.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);else i=Ok(i)?!!i.capture:!!i,r=UC(r),t&&t[IC]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=AC(o=t.g[n],r,i,s))&&(SC(o[r]),Array.prototype.splice.call(o,r,1),0==o.length&&(delete t.g[n],t.h--))):(t=t&&LC(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?AC(n,r,i,s):t)?n[t]:null)&&DC(r))}(this,e,t,n,r)},qC.prototype.M=function(){if(qC.Z.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)SC(n[r]);delete t.g[e],t.h--}}this.I=null},qC.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},qC.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var BC=xk.JSON.stringify;var KC,$C=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new WC,e=>e.reset());class WC{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function zC(e,t){var n;KC||(n=xk.Promise.resolve(void 0),KC=function(){n.then(QC)}),GC||(KC(),GC=!0),HC.add(e,t)}var GC=!1,HC=new class{constructor(){this.h=this.g=null}add(e,t){const n=$C.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function QC(){for(var e;e=function(){var e=HC;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){xk.setTimeout(()=>{throw e},0)}(e)}var t=$C;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}GC=!1}function YC(e,t){qC.call(this),this.h=e||1,this.g=t||xk,this.j=qk(this.kb,this),this.l=Date.now()}function JC(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function XC(e,t,n){if("function"==typeof e)n&&(e=qk(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=qk(e.handleEvent,e)}return 2147483647<Number(t)?-1:xk.setTimeout(e,t||0)}Vk(YC,qC),(ze=YC.prototype).da=!1,ze.S=null,ze.kb=function(){var e;this.da&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.S=this.g.setTimeout(this.j,this.h-e):(this.S&&(this.g.clearTimeout(this.S),this.S=null),jC(this,"tick"),this.da&&(JC(this),this.start())))},ze.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},ze.M=function(){YC.Z.M.call(this),JC(this),delete this.g};class ZC extends Bk{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=XC(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(xk.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function eA(e){Bk.call(this),this.h=e,this.g={}}Vk(eA,Bk);var tA=[];function nA(e,t,n,r){Array.isArray(n)||(n&&(tA[0]=n.toString()),n=tA);for(var i=0;i<n.length;i++){var s=xC(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function rA(e){eC(e.g,function(e,t){this.g.hasOwnProperty(t)&&DC(e)},e),e.g={}}function iA(){this.g=!0}function sA(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return BC(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}eA.prototype.M=function(){eA.Z.M.call(this),rA(this)},eA.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},iA.prototype.Aa=function(){this.g=!1},iA.prototype.info=function(){};var oA={},aA=null;function cA(){return aA=aA||new qC}function lA(e){_C.call(this,oA.Ma,e)}function uA(){var e=cA();jC(e,new lA(e))}function hA(e,t){_C.call(this,oA.STAT_EVENT,e),this.stat=t}function dA(e){var t=cA();jC(t,new hA(t,e))}function fA(e,t){_C.call(this,oA.Na,e),this.size=t}function pA(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return xk.setTimeout(function(){e()},t)}oA.Ma="serverreachability",Vk(lA,_C),oA.STAT_EVENT="statevent",Vk(hA,_C),oA.Na="timingevent",Vk(fA,_C);c={NO_ERROR:0,lb:1,yb:2,xb:3,sb:4,wb:5,zb:6,Ja:7,TIMEOUT:8,Cb:9},yt={qb:"complete",Mb:"success",Ka:"error",Ja:"abort",Eb:"ready",Fb:"readystatechange",TIMEOUT:"timeout",Ab:"incrementaldata",Db:"progress",tb:"downloadprogress",Ub:"uploadprogress"};function gA(){}function mA(e){return e.h||(e.h=e.i())}function vA(){}gA.prototype.h=null;l={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function yA(){_C.call(this,"d")}function _A(){_C.call(this,"c")}function wA(){}function bA(e,t,n,r){this.l=e,this.j=t,this.m=n,this.X=r||1,this.V=new eA(this),this.P=EA,this.W=new YC(e=lC?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.Y=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.N=-1,this.I=!1,this.O=0,this.L=null,this.aa=this.J=this.$=this.U=!1,this.h=new IA}function IA(){this.i=null,this.g="",this.h=!1}Vk(yA,_C),Vk(_A,_C),Vk(wA,gA),wA.prototype.g=function(){return new XMLHttpRequest},wA.prototype.i=function(){return{}};var TA=new wA,EA=45e3,SA={},kA={};function CA(e,t,n){e.K=1,e.v=QA(KA(t)),e.s=n,e.U=!0,AA(e,null)}function AA(e,t){e.F=Date.now(),xA(e),e.A=KA(e.v);var o,a,c,l,u,h,n=e.A,r=e.X;Array.isArray(r)||(r=[String(r)]),cN(n.h,"t",r),e.C=0,n=e.l.H,e.h=new IA,e.g=cR(e.l,n?t:null,!e.s),0<e.O&&(e.L=new ZC(qk(e.Ia,e,e.g),e.O)),nA(e.V,e.g,"readystatechange",e.gb),t=e.H?tC(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.s,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),uA(),o=e.j,a=e.u,c=e.A,l=e.m,u=e.X,h=e.s,o.info(function(){if(o.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+a+"\n"+c+"\n"+e})}function NA(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function RA(e,t,n){let r=!0,i;for(;!e.I&&e.C<n.length;){if(i=(o=n,c=a=void 0,a=(s=e).C,-1==(c=o.indexOf("\n",a))?kA:(a=Number(o.substring(a,c)),isNaN(a)?SA:(c+=1)+a>o.length?kA:(o=o.substr(c,a),s.C=c+a,o))),i==kA){4==t&&(e.o=4,dA(14),r=!1),sA(e.j,e.m,null,"[Incomplete Response]");break}if(i==SA){e.o=4,dA(15),sA(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}sA(e.j,e.m,i,null),LA(e,i)}var s,o,a,c;NA(e)&&i!=kA&&i!=SA&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,dA(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.aa&&(e.aa=!0,(t=e.l).g==e&&t.$&&!t.L&&(t.h.info("Great, no buffering proxy detected. Bytes received: "+n.length),eR(t),t.L=!0,dA(11))):(sA(e.j,e.m,n,"[Invalid Chunked Response]"),MA(e),OA(e))}function xA(e){e.Y=Date.now()+e.P,PA(e,e.P)}function PA(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=pA(qk(e.eb,e),t)}function DA(e){e.B&&(xk.clearTimeout(e.B),e.B=null)}function OA(e){0==e.l.G||e.I||rR(e.l,e)}function MA(e){DA(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,JC(e.W),rA(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function LA(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||gN(n.i,e)))if(n.I=e.N,!e.J&&gN(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;nR(n),WN(n)}ZN(n),dA(18)}}else n.ta=i[1],0<n.ta-n.U&&i[2]<37500&&n.N&&0==n.A&&!n.v&&(n.v=pA(qk(n.ab,n),6e3));if(pN(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else sR(n,11)}else if(!e.J&&n.g!=e||nR(n),!Hk(t))for(i=n.Ca.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.U=s[0],s=s[1],2==n.G)if("c"==s[0]){n.J=s[1],n.la=s[2];var o=s[3];null!=o&&(n.ma=o,n.h.info("VER="+n.ma));var a=s[4];null!=a&&(n.za=a,n.h.info("SVER="+n.za));var c,l,u,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.K=r,n.h.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;g&&(!(c=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(l=r.i).g&&(Jk(c,"spdy")||Jk(c,"quic")||Jk(c,"h2"))&&(l.j=l.l,l.g=new Set,l.h&&(mN(l,l.h),l.h=null)),!r.D||(u=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=u,HA(r.F,r.D,u))),n.G=3,n.j&&n.j.xa(),n.$&&(n.O=Date.now()-e.F,n.h.info("Handshake RTT: "+n.O+"ms"));var d,f,p=e;(r=n).oa=aR(r,r.H?r.la:null,r.W),p.J?(vN(r.i,p),d=p,(f=r.K)&&d.setTimeout(f),d.B&&(DA(d),xA(d)),r.g=p):XN(r),0<n.l.length&&HN(n)}else"stop"!=s[0]&&"close"!=s[0]||sR(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?sR(n,7):$N(n):"noop"!=s[0]&&n.j&&n.j.wa(s),n.A=0)}uA()}catch(e){}}function FA(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Dk(e)||"string"==typeof e)Wk(e,t,void 0);else{if(e.T&&"function"==typeof e.T)var n=e.T();else if(e.R&&"function"==typeof e.R)n=void 0;else if(Dk(e)||"string"==typeof e)for(var n=[],r=e.length,i=0;i<r;i++)n.push(i);else for(i in n=[],r=0,e)n[r++]=i;for(var i=(r=function(e){if(e.R&&"function"==typeof e.R)return e.R();if("string"==typeof e)return e.split("");if(Dk(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e)).length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}}function UA(e,t){this.h={},this.g=[],this.i=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(e)if(e instanceof UA)for(n=e.T(),r=0;r<n.length;r++)this.set(n[r],e.get(n[r]));else for(r in e)this.set(r,e[r])}function qA(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];jA(e.h,r)&&(e.g[n++]=r),t++}e.g.length=n}if(e.i!=e.g.length){for(var i={},n=t=0;t<e.g.length;)jA(i,r=e.g[t])||(i[e.g[n++]=r]=1),t++;e.g.length=n}}function jA(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(ze=bA.prototype).setTimeout=function(e){this.P=e},ze.gb=function(e){e=e.target;const t=this.L;t&&3==qN(e)?t.l():this.Ia(e)},ze.Ia=function(e){try{if(e==this.g)e:{var t=qN(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||lC||this.g&&(this.h.h||this.g.ga()||jN(this.g)))){this.I||4!=t||7==n||uA(),DA(this);var r=this.g.ba();this.N=r;t:if(NA(this)){var i=jN(this.g);e="";var s=i.length,o=4==qN(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){MA(this),OA(this);var a="";break t}this.h.i=new xk.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:o&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.ga();if(this.i=200==r,h=this.j,d=this.u,f=this.A,p=this.m,g=this.X,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+g+"]: "+d+"\n"+f+"\n"+m+" "+v}),this.i){if(this.$&&!this.J){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!Hk(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,dA(12),MA(this),OA(this);break e}sA(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,LA(this,r)}this.U?(RA(this,t,a),lC&&this.i&&3==t&&(nA(this.V,this.W,"tick",this.fb),this.W.start())):(sA(this.j,this.m,a,null),LA(this,a)),4==t&&MA(this),this.i&&!this.I&&(4==t?rR(this.l,this):(this.i=!1,xA(this)))}else 400==r&&0<a.indexOf("Unknown SID")?(this.o=3,dA(12)):(this.o=0,dA(13)),MA(this),OA(this)}}}catch(e){}var h,d,f,p,g,m,v},ze.fb=function(){var e,t;this.g&&(e=qN(this.g),t=this.g.ga(),this.C<t.length&&(DA(this),RA(this,e,t),this.i&&4!=e&&xA(this)))},ze.cancel=function(){this.I=!0,MA(this)},ze.eb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.K&&(uA(),dA(17)),MA(this),this.o=2,OA(this)):PA(this,this.Y-n)},(ze=UA.prototype).R=function(){qA(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},ze.T=function(){return qA(this),this.g.concat()},ze.get=function(e,t){return jA(this.h,e)?this.h[e]:t},ze.set=function(e,t){jA(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},ze.forEach=function(e,t){for(var n=this.T(),r=0;r<n.length;r++){var i=n[r],s=this.get(i);e.call(t,s,i,this)}};var VA=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function BA(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof BA?(this.g=void 0!==t?t:e.g,$A(this,e.j),this.s=e.s,WA(this,e.i),zA(this,e.m),this.l=e.l,t=e.h,(n=new iN).i=t.i,t.g&&(n.g=new UA(t.g),n.h=t.h),GA(this,n),this.o=e.o):e&&(n=String(e).match(VA))?(this.g=!!t,$A(this,n[1]||"",!0),this.s=YA(n[2]||""),WA(this,n[3]||"",!0),zA(this,n[4]),this.l=YA(n[5]||"",!0),GA(this,n[6]||"",!0),this.o=YA(n[7]||"")):(this.g=!!t,this.h=new iN(null,this.g))}function KA(e){return new BA(e)}function $A(e,t,n){e.j=n?YA(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function WA(e,t,n){e.i=n?YA(t,!0):t}function zA(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function GA(e,t,n){var r,i;t instanceof iN?(e.h=t,r=e.h,(i=e.g)&&!r.j&&(sN(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(oN(this,t),cN(this,n,e))},r)),r.j=i):(n||(t=JA(t,nN)),e.h=new iN(t,e.g))}function HA(e,t,n){e.h.set(t,n)}function QA(e){return HA(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function YA(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function JA(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,XA),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function XA(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}BA.prototype.toString=function(){var e=[],t=this.j;t&&e.push(JA(t,ZA,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(JA(t,ZA,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&e.push("/"),e.push(JA(n,"/"==n.charAt(0)?tN:eN,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",JA(n,rN)),e.join("")};var ZA=/[#\/\?@]/g,eN=/[#\?:]/g,tN=/[#\?]/g,nN=/[#\?@]/g,rN=/#/g;function iN(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function sN(n){n.g||(n.g=new UA,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function oN(e,t){sN(e),t=lN(e,t),jA(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,jA((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&qA(e)))}function aN(e,t){return sN(e),t=lN(e,t),jA(e.g.h,t)}function cN(e,t,n){oN(e,t),0<n.length&&(e.i=null,e.g.set(lN(e,t),Gk(n)),e.h+=n.length)}function lN(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(ze=iN.prototype).add=function(e,t){sN(this),this.i=null,e=lN(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},ze.forEach=function(n,r){sN(this),this.g.forEach(function(e,t){Wk(e,function(e){n.call(r,e,t,this)},this)},this)},ze.T=function(){sN(this);for(var e=this.g.R(),t=this.g.T(),n=[],r=0;r<t.length;r++)for(var i=e[r],s=0;s<i.length;s++)n.push(t[r]);return n},ze.R=function(e){sN(this);var t=[];if("string"==typeof e)aN(this,e)&&(t=zk(t,this.g.get(lN(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=zk(t,e[n])}return t},ze.set=function(e,t){return sN(this),this.i=null,aN(this,e=lN(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},ze.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},ze.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=this.g.T(),n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),r=this.R(r),s=0;s<r.length;s++){var o=i;""!==r[s]&&(o+="="+encodeURIComponent(String(r[s]))),e.push(o)}return this.i=e.join("&")};var uN=class{constructor(e,t){this.h=e,this.g=t}};function hN(e){this.l=e||10,e=xk.PerformanceNavigationTiming?0<(e=xk.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(xk.g&&xk.g.Ea&&xk.g.Ea()&&xk.g.Ea().Zb),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var dN;function fN(e){return e.h||e.g&&e.g.size>=e.j}function pN(e){return e.h?1:e.g?e.g.size:0}function gN(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function mN(e,t){e.g?e.g.add(t):e.h=t}function vN(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function yN(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Gk(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function _N(){}function wN(){this.g=new _N}function bN(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function IN(e){this.l=e.$b||null,this.j=e.ib||!1}function TN(e,t){qC.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=EN,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}hN.prototype.cancel=function(){if(this.i=yN(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},_N.prototype.stringify=function(e){return xk.JSON.stringify(e,void 0)},_N.prototype.parse=function(e){return xk.JSON.parse(e,void 0)},Vk(IN,gA),IN.prototype.g=function(){return new TN(this.l,this.j)},IN.prototype.i=(dN={},function(){return dN}),Vk(TN,qC);var EN=0;function SN(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function kN(e){e.readyState=4,e.l=null,e.j=null,e.A=null,CN(e)}function CN(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(ze=TN.prototype).open=function(e,t){if(this.readyState!=EN)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,CN(this)},ze.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||xk).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},ze.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,kN(this)),this.readyState=EN},ze.Va=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,CN(this)),this.g&&(this.readyState=3,CN(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==xk.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;SN(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},ze.Sa=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?kN:CN)(this),3==this.readyState&&SN(this))},ze.Ua=function(e){this.g&&(this.response=this.responseText=e,kN(this))},ze.Ta=function(e){this.g&&(this.response=e,kN(this))},ze.ha=function(){this.g&&kN(this)},ze.setRequestHeader=function(e,t){this.v.append(e,t)},ze.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},ze.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(TN.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var AN=xk.JSON.parse;function NN(e){qC.call(this),this.headers=new UA,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=RN,this.K=this.L=!1}Vk(NN,qC);var RN="",xN=/^https?$/i,PN=["POST","PUT"];function DN(e){return"content-type"==e.toLowerCase()}function ON(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,MN(e),FN(e)}function MN(e){e.D||(e.D=!0,jC(e,"complete"),jC(e,"error"))}function LN(e){if(e.h&&void 0!==Rk&&(!e.C[1]||4!=qN(e)||2!=e.ba()))if(e.v&&4==qN(e))XC(e.Fa,0,e);else if(jC(e,"readystatechange"),4==qN(e)){e.h=!1;try{var t,n,r,i,s=e.ba();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break e;default:o=!1}if((t=o)||((n=0===s)&&(!(i=String(e.H).match(VA)[1]||null)&&xk.self&&xk.self.location&&(i=(r=xk.self.location.protocol).substr(0,r.length-1)),n=!xN.test(i?i.toLowerCase():"")),t=n),t)jC(e,"complete"),jC(e,"success");else{e.m=6;try{var a=2<qN(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.ba()+"]",MN(e)}}finally{FN(e)}}}function FN(e,t){if(e.g){UN(e);const n=e.g,r=e.C[0]?Pk:null;e.g=null,e.C=null,t||jC(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function UN(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(xk.clearTimeout(e.A),e.A=null)}function qN(e){return e.g?e.g.readyState:0}function jN(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case RN:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function VN(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return eC(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):HA(e,t,n))}function BN(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function KN(e){this.za=0,this.l=[],this.h=new iA,this.la=this.oa=this.F=this.W=this.g=this.sa=this.D=this.aa=this.o=this.P=this.s=null,this.Za=this.V=0,this.Xa=BN("failFast",!1,e),this.N=this.v=this.u=this.m=this.j=null,this.X=!0,this.I=this.ta=this.U=-1,this.Y=this.A=this.C=0,this.Pa=BN("baseRetryDelayMs",5e3,e),this.$a=BN("retryDelaySeedMs",1e4,e),this.Ya=BN("forwardChannelMaxRetries",2,e),this.ra=BN("forwardChannelRequestTimeoutMs",2e4,e),this.qa=e&&e.xmlHttpFactory||void 0,this.Ba=e&&e.Yb||!1,this.K=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.J="",this.i=new hN(e&&e.concurrentRequestLimit),this.Ca=new wN,this.ja=e&&e.fastHandshake||!1,this.Ra=e&&e.Wb||!1,e&&e.Aa&&this.h.Aa(),e&&e.forceLongPolling&&(this.X=!1),this.$=!this.ja&&this.X&&e&&e.detectBufferingProxy||!1,this.ka=void 0,this.O=0,this.L=!1,this.B=null,this.Wa=!e||!1!==e.Xb}function $N(e){var t,n;zN(e),3==e.G&&(t=e.V++,HA(n=KA(e.F),"SID",e.J),HA(n,"RID",t),HA(n,"TYPE","terminate"),YN(e,n),(t=new bA(e,e.h,t,void 0)).K=2,t.v=QA(KA(n)),n=!1,!(n=xk.navigator&&xk.navigator.sendBeacon?xk.navigator.sendBeacon(t.v.toString(),""):n)&&xk.Image&&((new Image).src=t.v,n=!0),n||(t.g=cR(t.l,null),t.g.ea(t.v)),t.F=Date.now(),xA(t)),oR(e)}function WN(e){e.g&&(eR(e),e.g.cancel(),e.g=null)}function zN(e){WN(e),e.u&&(xk.clearTimeout(e.u),e.u=null),nR(e),e.i.cancel(),e.m&&("number"==typeof e.m&&xk.clearTimeout(e.m),e.m=null)}function GN(e,t){e.l.push(new uN(e.Za++,t)),3==e.G&&HN(e)}function HN(e){fN(e.i)||e.m||(e.m=!0,zC(e.Ha,e),e.C=0)}function QN(e,t){var n=t?t.m:e.V++,r=KA(e.F);HA(r,"SID",e.J),HA(r,"RID",n),HA(r,"AID",e.U),YN(e,r),e.o&&e.s&&VN(r,e.o,e.s),n=new bA(e,e.h,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.l=t.D.concat(e.l)),t=JN(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),mN(e.i,n),CA(n,r,t)}function YN(e,n){e.j&&FA({},function(e,t){HA(n,t,e)})}function JN(e,t,r){r=Math.min(e.l.length,r);var i=e.j?qk(e.j.Oa,e.j,e):null;e:{var s=e.l;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].h,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var o=s[t].h,a=s[t].g;if((o-=n)<0)n=Math.max(0,s[t].h-100),e=!1;else try{!function(e,r,t){const i=t||"";try{FA(e,function(e,t){let n=e;Ok(e)&&(n=BC(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(a,c,"req"+o+"_")}catch(e){i&&i(a)}}if(e){i=c.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,i}function XN(e){e.g||e.u||(e.Y=1,zC(e.Ga,e),e.A=0)}function ZN(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=pA(qk(e.Ga,e),iR(e,e.A)),e.A++,1)}function eR(e){null!=e.B&&(xk.clearTimeout(e.B),e.B=null)}function tR(e){e.g=new bA(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=KA(e.oa);HA(t,"RID","rpc"),HA(t,"SID",e.J),HA(t,"CI",e.N?"0":"1"),HA(t,"AID",e.U),YN(e,t),HA(t,"TYPE","xmlhttp"),e.o&&e.s&&VN(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=QA(KA(t)),n.s=null,n.U=!0,AA(n,e)}function nR(e){null!=e.v&&(xk.clearTimeout(e.v),e.v=null)}function rR(e,t){var n,r,i,s=null;if(e.g==t){nR(e),eR(e),e.g=null;var o=2}else{if(!gN(e.i,t))return;s=t.D,vN(e.i,t),o=1}if(e.I=t.N,0!=e.G)if(t.i)1==o?(s=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,jC(o=cA(),new fA(o,s)),HN(e)):XN(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=o||(i=t,pN((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.l=i.D.concat(r.l),0):1==r.G||2==r.G||r.C>=(r.Xa?0:r.Ya)||(r.m=pA(qk(r.Ha,r,i),iR(r,r.C)),r.C++,0))))&&(2!=o||!ZN(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:sR(e,5);break;case 4:sR(e,10);break;case 3:sR(e,6);break;default:sR(e,2)}}function iR(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function sR(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=qk(e.jb,e),n||(n=new BA("//www.google.com/images/cleardot.gif"),xk.location&&"http"==xk.location.protocol||$A(n,"https"),QA(n)),function(e,t){var n=new iA;if(xk.Image){const r=new Image;r.onload=jk(bN,n,r,"TestLoadImage: loaded",!0,t),r.onerror=jk(bN,n,r,"TestLoadImage: error",!1,t),r.onabort=jk(bN,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=jk(bN,n,r,"TestLoadImage: timeout",!1,t),xk.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):dA(2),e.G=0,e.j&&e.j.va(t),oR(e),zN(e)}function oR(e){e.G=0,e.I=-1,e.j&&(0==yN(e.i).length&&0==e.l.length||(e.i.i.length=0,Gk(e.l),e.l.length=0),e.j.ua())}function aR(e,t,n){let r=(a=n)instanceof BA?KA(a):new BA(a,void 0);var i,s,o,a,c;return""!=r.i?(t&&WA(r,t+"."+r.i),zA(r,r.m)):(c=xk.location,r=(i=c.protocol,s=t?t+"."+c.hostname:c.hostname,o=+c.port,a=n,c=new BA(null,void 0),i&&$A(c,i),s&&WA(c,s),o&&zA(c,o),a&&(c.l=a),c)),e.aa&&eC(e.aa,function(e,t){HA(r,t,e)}),t=e.D,n=e.sa,t&&n&&HA(r,t,n),HA(r,"VER",e.ma),YN(e,r),r}function cR(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ba&&!e.qa?new NN(new IN({ib:!0})):new NN(e.qa)).L=e.H,t}function lR(){}function uR(){if(aC&&!(10<=Number(vC)))throw Error("Environmental error: no available transport.")}function hR(e,t){qC.call(this),this.g=new KN(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.P=e,(e=t&&t.httpHeadersOverwriteParam)&&!Hk(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Hk(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new pR(this)}function dR(e){yA.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function fR(){_A.call(this),this.status=1}function pR(e){this.g=e}(ze=NN.prototype).ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||TA).g(),this.C=this.u?mA(this.u):mA(TA),this.g.onreadystatechange=qk(this.Fa,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void ON(this,e)}e=n||"";const i=new UA(this.headers);r&&FA(r,function(e,t){i.set(t,e)}),r=function(t){e:{var n=DN,r=t.length,i="string"==typeof t?t.split(""):t;for(let e=0;e<r;e++)if(e in i&&n.call(void 0,i[e],e,t)){n=e;break e}n=-1}return n<0?null:"string"==typeof t?t.charAt(n):t[n]}(i.T()),n=xk.FormData&&e instanceof xk.FormData,0<=$k(PN,t)&&!r&&!n&&i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(e,t){this.g.setRequestHeader(t,e)},this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{UN(this),0<this.B&&((this.K=(s=this.g,aC&&mC()&&"number"==typeof s.timeout&&void 0!==s.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=qk(this.pa,this)):this.A=XC(this.pa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){ON(this,e)}var s},ze.pa=function(){void 0!==Rk&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,jC(this,"timeout"),this.abort(8))},ze.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,jC(this,"complete"),jC(this,"abort"),FN(this))},ze.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),FN(this,!0)),NN.Z.M.call(this)},ze.Fa=function(){this.s||(this.F||this.v||this.l?LN(this):this.cb())},ze.cb=function(){LN(this)},ze.ba=function(){try{return 2<qN(this)?this.g.status:-1}catch(e){return-1}},ze.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},ze.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),AN(t)}},ze.Da=function(){return this.m},ze.La=function(){return"string"==typeof this.j?this.j:String(this.j)},(ze=KN.prototype).ma=8,ze.G=1,ze.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},ze.Ha=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;const s=new bA(this,this.h,t,void 0);let e=this.s;if(this.P&&(e?(e=tC(e),rC(e,this.P)):e=this.P),null===this.o&&(s.H=e),this.ja)e:{for(var n=0,r=0;r<this.l.length;r++){var i=this.l[r];if("__data__"in i.g&&"string"==typeof(i=i.g.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.l.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=JN(this,s,n),HA(r=KA(this.F),"RID",t),HA(r,"CVER",22),this.D&&HA(r,"X-HTTP-Session-Id",this.D),YN(this,r),this.o&&e&&VN(r,this.o,e),mN(this.i,s),this.Ra&&HA(r,"TYPE","init"),this.ja?(HA(r,"$req",n),HA(r,"SID","null"),s.$=!0,CA(s,r,null)):CA(s,r,n),this.G=2}}else 3==this.G&&(t?QN(this,t):0==this.l.length||fN(this.i)||QN(this))},ze.Ga=function(){var e;this.u=null,tR(this),this.$&&!(this.L||null==this.g||this.O<=0)&&(e=2*this.O,this.h.info("BP detection timer enabled: "+e),this.B=pA(qk(this.bb,this),e))},ze.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,dA(10),WN(this),tR(this))},ze.ab=function(){null!=this.v&&(this.v=null,WN(this),ZN(this),dA(19))},ze.jb=function(e){e?(this.h.info("Successfully pinged google.com"),dA(2)):(this.h.info("Failed to ping google.com"),dA(1))},(ze=lR.prototype).xa=function(){},ze.wa=function(){},ze.va=function(){},ze.ua=function(){},ze.Oa=function(){},uR.prototype.g=function(e,t){return new hR(e,t)},Vk(hR,qC),hR.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),zC(qk(e.hb,e,t))),dA(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=aR(e,null,e.W),HN(e)},hR.prototype.close=function(){$N(this.g)},hR.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,GN(this.g,t)):this.v?((t={}).__data__=BC(e),GN(this.g,t)):GN(this.g,e)},hR.prototype.M=function(){this.g.j=null,delete this.j,$N(this.g),delete this.g,hR.Z.M.call(this)},Vk(dR,yA),Vk(fR,_A),Vk(pR,lR),pR.prototype.xa=function(){jC(this.g,"a")},pR.prototype.wa=function(e){jC(this.g,new dR(e))},pR.prototype.va=function(e){jC(this.g,new fR)},pR.prototype.ua=function(){jC(this.g,"b")},uR.prototype.createWebChannel=uR.prototype.g,hR.prototype.send=hR.prototype.u,hR.prototype.open=hR.prototype.m,c.NO_ERROR=0,c.TIMEOUT=8,c.HTTP_ERROR=6,yt.COMPLETE="complete",(vA.EventType=l).OPEN="a",l.CLOSE="b",l.ERROR="c",l.MESSAGE="d",qC.prototype.listen=qC.prototype.N,NN.prototype.listenOnce=NN.prototype.O,NN.prototype.getLastError=NN.prototype.La,NN.prototype.getLastErrorCode=NN.prototype.Da,NN.prototype.getStatus=NN.prototype.ba,NN.prototype.getResponseJson=NN.prototype.Qa,NN.prototype.getResponseText=NN.prototype.ga,NN.prototype.send=NN.prototype.ea;var gR,mR=cA,vR=c,yR=yt,_R=oA,wR=10,bR=11,IR=IN,TR=vA,ER=NN;const SR="@firebase/firestore";class kR{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}kR.UNAUTHENTICATED=new kR(null),kR.GOOGLE_CREDENTIALS=new kR("google-credentials-uid"),kR.FIRST_PARTY=new kR("first-party-uid"),kR.MOCK_USER=new kR("mock-user");let CR="9.6.11";const AR=new cf("@firebase/firestore");function NR(){return AR.logLevel}function RR(e,...t){var n;AR.logLevel<=$h.DEBUG&&(n=t.map(DR),AR.debug(`Firestore (${CR}): ${e}`,...n))}function xR(e,...t){var n;AR.logLevel<=$h.ERROR&&(n=t.map(DR),AR.error(`Firestore (${CR}): ${e}`,...n))}function PR(e,...t){var n;AR.logLevel<=$h.WARN&&(n=t.map(DR),AR.warn(`Firestore (${CR}): ${e}`,...n))}function DR(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function OR(e="Unexpected state"){var t=`FIRESTORE (${CR}) INTERNAL ASSERTION FAILED: `+e;throw xR(t),new Error(t)}function MR(e){e||OR()}const LR={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FR extends gd{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class UR{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class qR{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class jR{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(kR.UNAUTHENTICATED))}shutdown(){}}class VR{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class BR{constructor(e){this.t=e,this.currentUser=kR.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new UR;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new UR,t.enqueueRetryable(()=>i(this.currentUser))};const o=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},a=e=>{RR("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),o()};this.t.onInit(e=>a(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?a(e):(RR("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new UR))},0),o()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(RR("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(MR("string"==typeof e.accessToken),new qR(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return MR(null===e||"string"==typeof e),new kR(e)}}class KR{constructor(e,t,n){this.type="FirstParty",this.user=kR.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);var r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class $R{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new KR(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(kR.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class WR{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class zR{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null,this.p=null}start(t,n){const r=e=>{null!=e.error&&RR("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.p;return this.p=e.token,RR("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{RR("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?i(e):RR("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(MR("string"==typeof e.token),this.p=e.token,new WR(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class GR{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.I(e),this.T=e=>t.writeSequenceNumber(e))}I(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}GR.A=-1;class HR{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function QR(e,t){return e<t?-1:t<e?1:0}function YR(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function JR(e){return e+"\0"}class XR{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new FR(LR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new FR(LR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new FR(LR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new FR(LR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return XR.fromMillis(Date.now())}static fromDate(e){return XR.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new XR(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?QR(this.nanoseconds,e.nanoseconds):QR(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class ZR{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ZR(e)}static min(){return new ZR(new XR(0,0))}static max(){return new ZR(new XR(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function ex(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tx(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function nx(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class rx{constructor(e,t,n){void 0===t?t=0:t>e.length&&OR(),void 0===n?n=e.length-t:n>e.length-t&&OR(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===rx.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof rx?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ix extends rx{construct(e,t,n){return new ix(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new FR(LR.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new ix(t)}static emptyPath(){return new ix([])}}const sx=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ox extends rx{construct(e,t,n){return new ox(e,t,n)}static isValidIdentifier(e){return sx.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!ox.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new ox(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new FR(LR.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new FR(LR.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new FR(LR.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new FR(LR.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new ox(t)}static emptyPath(){return new ox([])}}class ax{constructor(e){(this.fields=e).sort(ox.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return YR(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class cx{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new cx(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new cx(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return QR(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}cx.EMPTY_BYTE_STRING=new cx("");const lx=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ux(t){if(MR(!!t),"string"!=typeof t)return{seconds:hx(t.seconds),nanos:hx(t.nanos)};{let e=0;var n=lx.exec(t);MR(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function hx(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function dx(e){return"string"==typeof e?cx.fromBase64String(e):cx.fromUint8Array(e)}function fx(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function px(e){var t=ux(e.mapValue.fields.__local_write_time__.timestampValue);return new XR(t.seconds,t.nanos)}class gx{constructor(e,t,n,r,i,s,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class mx{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new mx("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof mx&&e.projectId===this.projectId&&e.database===this.database}}function vx(e){return null==e}function yx(e){return 0===e&&1/e==-1/0}function _x(e){return"number"==typeof e&&Number.isInteger(e)&&!yx(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class wx{constructor(e){this.path=e}static fromPath(e){return new wx(ix.fromString(e))}static fromName(e){return new wx(ix.fromString(e).popFirst(5))}static empty(){return new wx(ix.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ix.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ix.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new wx(new ix(e.slice()))}}const bx={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Ix={nullValue:"NULL_VALUE"};function Tx(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?fx(e)?4:Lx(e)?9:10:OR()}function Ex(r,i){if(r===i)return!0;var e,t,n=Tx(r);if(n!==Tx(i))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return px(r).isEqual(px(i));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=ux(r.timestampValue),n=ux(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,dx(r.bytesValue).isEqual(dx(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,hx((t=r).geoPointValue.latitude)===hx(e.geoPointValue.latitude)&&hx(t.geoPointValue.longitude)===hx(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return hx(e.integerValue)===hx(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=hx(e.doubleValue),r=hx(t.doubleValue);return n===r?yx(n)===yx(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return YR(r.arrayValue.values||[],i.arrayValue.values||[],Ex);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(ex(t)!==ex(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!Ex(t[e],n[e])))return!1;return!0}(r);default:return OR()}}function Sx(e,t){return void 0!==(e.values||[]).find(e=>Ex(e,t))}function kx(e,t){if(e===t)return 0;var n,r,i,s,o=Tx(e),a=Tx(t);if(o!==a)return QR(o,a);switch(o){case 0:case 9007199254740991:return 0;case 1:return QR(e.booleanValue,t.booleanValue);case 2:return r=t,i=hx(e.integerValue||e.doubleValue),s=hx(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Cx(e.timestampValue,t.timestampValue);case 4:return Cx(px(e),px(t));case 5:return QR(e.stringValue,t.stringValue);case 6:return function(e,t){const n=dx(e),r=dx(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=QR(n[i],r[i]);if(0!==t)return t}return QR(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=QR(hx(n.latitude),hx(r.latitude)))?s:QR(hx(n.longitude),hx(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=kx(n[i],r[i]);if(t)return t}return QR(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let a=0;a<r.length&&a<s.length;++a){const t=QR(r[a],s[a]);if(0!==t)return t;var o=kx(n[r[a]],i[s[a]]);if(0!==o)return o}return QR(r.length,s.length)}(e.mapValue,t.mapValue);default:throw OR()}}function Cx(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return QR(e,t);var n=ux(e),r=ux(t),i=QR(n.seconds,r.seconds);return 0!==i?i:QR(n.nanos,r.nanos)}function Ax(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=ux(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?dx(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,wx.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):OR();var t}(e)}function Nx(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Rx(e){return e&&"integerValue"in e}function xx(e){return!!e&&"arrayValue"in e}function Px(e){return e&&"nullValue"in e}function Dx(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Ox(e){return e&&"mapValue"in e}function Mx(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return tx(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Mx(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Mx(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Lx(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Fx(e,t){return void 0!==e&&(void 0===t||0<kx(e,t))?e:t}function Ux(e,t){return void 0!==e&&(void 0===t||kx(e,t)<0)?e:t}class qx{constructor(e){this.value=e}static empty(){return new qx({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!Ox(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Mx(t)}setAll(e){let n=ox.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Mx(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Ox(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ex(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];Ox(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){tx(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new qx(Mx(this.value))}}class jx{constructor(e,t,n,r,i,s){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=i,this.documentState=s}static newInvalidDocument(e){return new jx(e,0,ZR.min(),ZR.min(),qx.empty(),0)}static newFoundDocument(e,t,n){return new jx(e,1,t,ZR.min(),n,0)}static newNoDocument(e,t){return new jx(e,2,t,ZR.min(),qx.empty(),0)}static newUnknownDocument(e,t){return new jx(e,3,t,ZR.min(),qx.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=qx.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=qx.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof jx&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new jx(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Vx{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Bx(e){return e.fields.find(e=>2===e.kind)}function Kx(e){return e.fields.filter(e=>2!==e.kind)}Vx.UNKNOWN_ID=-1;class $x{constructor(e,t){this.fieldPath=e,this.kind=t}}class Wx{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Wx(0,Gx.min())}}function zx(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=ZR.fromTimestamp(1e9===r?new XR(n+1,0):new XR(n,r));return new Gx(r,wx.empty(),t)}class Gx{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Gx(ZR.min(),wx.empty(),-1)}static max(){return new Gx(ZR.max(),wx.empty(),-1)}}class Hx{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.P=null}}function Qx(e,t=null,n=[],r=[],i=null,s=null,o=null){return new Hx(e,t,n,r,i,s,o)}function Yx(e){const t=e;if(null===t.P){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>{return(t=e).field.canonicalString()+t.op.toString()+Ax(t.value);var t}).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),vx(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ax(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ax(e)).join(",")),t.P=e}return t.P}function Jx(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let o=0;o<e.orderBy.length;o++)if(n=e.orderBy[o],r=t.orderBy[o],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,i,s;if(e.filters.length!==t.filters.length)return!1;for(let a=0;a<e.filters.length;a++)if(i=e.filters[a],s=t.filters[a],i.op!==s.op||!i.field.isEqual(s.field)||!Ex(i.value,s.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!pP(e.startAt,t.startAt)&&pP(e.endAt,t.endAt)}function Xx(e){return wx.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Zx(e,t){return e.filters.filter(e=>e instanceof nP&&e.field.isEqual(t))}function eP(t,n,r){let i,s=!0;for(const r of Zx(t,n)){let e,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(o=r.value)?Ix:"booleanValue"in o?{booleanValue:!1}:"integerValue"in o||"doubleValue"in o?{doubleValue:NaN}:"timestampValue"in o?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in o?{stringValue:""}:"bytesValue"in o?{bytesValue:""}:"referenceValue"in o?Nx(mx.empty(),wx.empty()):"geoPointValue"in o?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in o?{arrayValue:{}}:"mapValue"in o?{mapValue:{}}:OR();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Ix}Fx(i,e)===e&&(i=e,s=t)}var o;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Fx(i,t)===t&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function tP(t,n,r){let i,s=!0;for(const r of Zx(t,n)){let e,t=!0;switch(r.op){case">=":case">":e="nullValue"in(o=r.value)?{booleanValue:!1}:"booleanValue"in o?{doubleValue:NaN}:"integerValue"in o||"doubleValue"in o?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in o?{stringValue:""}:"stringValue"in o?{bytesValue:""}:"bytesValue"in o?Nx(mx.empty(),wx.empty()):"referenceValue"in o?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in o?{arrayValue:{}}:"arrayValue"in o?{mapValue:{}}:"mapValue"in o?bx:OR(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=bx}Ux(i,e)===e&&(i=e,s=t)}var o;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Ux(i,t)===t&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class nP extends class{}{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.V(e,t,n):new rP(e,t,n):"array-contains"===t?new aP(e,n):"in"===t?new cP(e,n):"not-in"===t?new lP(e,n):"array-contains-any"===t?new uP(e,n):new nP(e,t,n)}static V(e,t,n){return new("in"===t?iP:sP)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.v(kx(t,this.value)):null!==t&&Tx(this.value)===Tx(t)&&this.v(kx(t,this.value))}v(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return OR()}}S(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class rP extends nP{constructor(e,t,n){super(e,t,n),this.key=wx.fromName(n.referenceValue)}matches(e){var t=wx.comparator(e.key,this.key);return this.v(t)}}class iP extends nP{constructor(e,t){super(e,"in",t),this.keys=oP(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class sP extends nP{constructor(e,t){super(e,"not-in",t),this.keys=oP(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function oP(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>wx.fromName(e.referenceValue))}class aP extends nP{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return xx(t)&&Sx(t.arrayValue,this.value)}}class cP extends nP{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Sx(this.value.arrayValue,t)}}class lP extends nP{constructor(e,t){super(e,"not-in",t)}matches(e){if(Sx(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Sx(this.value.arrayValue,t)}}class uP extends nP{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!xx(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Sx(this.value.arrayValue,e))}}class hP{constructor(e,t){this.position=e,this.inclusive=t}}class dP{constructor(e,t="asc"){this.field=e,this.dir=t}}function fP(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?wx.comparator(wx.fromName(o.referenceValue),n.key):kx(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function pP(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ex(e.position[n],t.position[n]))return!1;return!0}class gP{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.D=null,this.C=null,this.startAt,this.endAt}}function mP(e,t,n,r,i,s,o,a){return new gP(e,t,n,r,i,s,o,a)}function vP(e){return new gP(e)}function yP(e){return!vx(e.limit)&&"F"===e.limitType}function _P(e){return!vx(e.limit)&&"L"===e.limitType}function wP(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function bP(e){for(const t of e.filters)if(t.S())return t.field;return null}function IP(e){return null!==e.collectionGroup}function TP(t){const n=t;if(null===n.D){n.D=[];const t=bP(n),e=wP(n);if(null!==t&&null===e)t.isKeyField()||n.D.push(new dP(t)),n.D.push(new dP(ox.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.D.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.D.push(new dP(ox.keyField(),t))}}}return n.D}function EP(e){const t=e;if(!t.C)if("F"===t.limitType)t.C=Qx(t.path,t.collectionGroup,TP(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of TP(t)){const t="desc"===i.dir?"asc":"desc";e.push(new dP(i.field,t))}var n=t.endAt?new hP(t.endAt.position,!t.endAt.inclusive):null,r=t.startAt?new hP(t.startAt.position,!t.startAt.inclusive):null;t.C=Qx(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.C}function SP(e,t,n){return new gP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function kP(e,t){return Jx(EP(e),EP(t))&&e.limitType===t.limitType}function CP(e){return`${Yx(EP(e))}|lt:${e.limitType}`}function AP(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>{return`${(t=e).field.canonicalString()} ${t.op} ${Ax(t.value)}`;var t}).join(", ")}]`),vx(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ax(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ax(e)).join(",")),`Target(${t})`}(EP(e))}; limitType=${e.limitType})`}function NP(n,e){return e.isFoundDocument()&&(i=n,o=(s=e).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(o):wx.isDocumentKey(i.path)?i.path.isEqual(o):i.path.isImmediateParentOf(o))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(i=e,(!(e=n).startAt||(t=e.startAt,r=fP(t,TP(e),i),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=fP(t,TP(e),i),t.inclusive?0<=r:0<r)));var t,r,i,s,o}function RP(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function xP(i){return(e,t)=>{let n=!1;for(const r of TP(i)){const i=function(e,i,t){var n=e.field.isKeyField()?wx.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?kx(n,r):OR()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return OR()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}function PP(e,t){if(e.N){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:yx(t)?"-0":t}}function DP(e){return{integerValue:""+e}}function OP(e,t){return _x(t)?DP(t):PP(e,t)}class MP{constructor(){this._=void 0}}function LP(e,t){return e instanceof BP?Rx(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class FP extends MP{}class UP extends MP{constructor(e){super(),this.elements=e}}function qP(e,t){const n=$P(t);for(const t of e.elements)n.some(e=>Ex(e,t))||n.push(t);return{arrayValue:{values:n}}}class jP extends MP{constructor(e){super(),this.elements=e}}function VP(e,t){let n=$P(t);for(const t of e.elements)n=n.filter(e=>!Ex(e,t));return{arrayValue:{values:n}}}class BP extends MP{constructor(e,t){super(),this.M=e,this.k=t}}function KP(e){return hx(e.integerValue||e.doubleValue)}function $P(e){return xx(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class WP{constructor(e,t){this.field=e,this.transform=t}}class zP{constructor(e,t){this.version=e,this.transformResults=t}}class GP{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new GP}static exists(e){return new GP(void 0,e)}static updateTime(e){return new GP(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function HP(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class QP{}function YP(e,t,n){e instanceof eD?function(e,t,n){const r=e.value.clone(),i=rD(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof tD?function(e,t,n){if(!HP(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=rD(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(nD(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function JP(e,t,n){e instanceof eD?function(e,t,n){if(HP(e.precondition,t)){const r=e.value.clone(),i=iD(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(ZP(t),r).setHasLocalMutations()}}(e,t,n):e instanceof tD?function(e,t,n){if(HP(e.precondition,t)){const r=iD(e.fieldTransforms,n,t),i=t.data;i.setAll(nD(e)),i.setAll(r),t.convertToFoundDocument(ZP(t),i).setHasLocalMutations()}}(e,t,n):(t=t,HP(e.precondition,t)&&t.convertToNoDocument(ZR.min()))}function XP(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&YR(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof UP&&t instanceof UP||e instanceof jP&&t instanceof jP?YR(e.elements,t.elements,Ex):e instanceof BP&&t instanceof BP?Ex(e.k,t.k):e instanceof FP&&t instanceof FP)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}function ZP(e){return e.isFoundDocument()?e.version:ZR.min()}class eD extends QP{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class tD extends QP{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}}function nD(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function rD(e,t,n){const r=new Map;MR(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,o=t.data.field(i.field);r.set(i.field,(a=s,c=o,l=n[u],a instanceof UP?qP(a,c):a instanceof jP?VP(a,c):l))}var a,c,l;return r}function iD(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,o=t,c=a=void 0,i instanceof FP?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}};return s&&(e.fields.__previous_value__=s),{mapValue:e}}():i instanceof UP?qP(i,s):i instanceof jP?VP(i,s):(a=LP(i=i,s),c=KP(a)+KP(i.k),Rx(a)&&Rx(i.k)?DP(c):PP(i.M,c))))}var i,s,o,a,c;return r}class sD extends QP{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class oD extends QP{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class aD{constructor(e){this.count=e}}function cD(e){switch(e){default:return OR(),0;case LR.CANCELLED:case LR.UNKNOWN:case LR.DEADLINE_EXCEEDED:case LR.RESOURCE_EXHAUSTED:case LR.INTERNAL:case LR.UNAVAILABLE:case LR.UNAUTHENTICATED:return;case LR.INVALID_ARGUMENT:case LR.NOT_FOUND:case LR.ALREADY_EXISTS:case LR.PERMISSION_DENIED:case LR.FAILED_PRECONDITION:case LR.ABORTED:case LR.OUT_OF_RANGE:case LR.UNIMPLEMENTED:case LR.DATA_LOSS:return 1}}function lD(e){if(void 0===e)return xR("GRPC error has no .code"),LR.UNKNOWN;switch(e){case gR.OK:return LR.OK;case gR.CANCELLED:return LR.CANCELLED;case gR.UNKNOWN:return LR.UNKNOWN;case gR.DEADLINE_EXCEEDED:return LR.DEADLINE_EXCEEDED;case gR.RESOURCE_EXHAUSTED:return LR.RESOURCE_EXHAUSTED;case gR.INTERNAL:return LR.INTERNAL;case gR.UNAVAILABLE:return LR.UNAVAILABLE;case gR.UNAUTHENTICATED:return LR.UNAUTHENTICATED;case gR.INVALID_ARGUMENT:return LR.INVALID_ARGUMENT;case gR.NOT_FOUND:return LR.NOT_FOUND;case gR.ALREADY_EXISTS:return LR.ALREADY_EXISTS;case gR.PERMISSION_DENIED:return LR.PERMISSION_DENIED;case gR.FAILED_PRECONDITION:return LR.FAILED_PRECONDITION;case gR.ABORTED:return LR.ABORTED;case gR.OUT_OF_RANGE:return LR.OUT_OF_RANGE;case gR.UNIMPLEMENTED:return LR.UNIMPLEMENTED;case gR.DATA_LOSS:return LR.DATA_LOSS;default:return OR()}}(c=gR=gR||{})[c.OK=0]="OK",c[c.CANCELLED=1]="CANCELLED",c[c.UNKNOWN=2]="UNKNOWN",c[c.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",c[c.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",c[c.NOT_FOUND=5]="NOT_FOUND",c[c.ALREADY_EXISTS=6]="ALREADY_EXISTS",c[c.PERMISSION_DENIED=7]="PERMISSION_DENIED",c[c.UNAUTHENTICATED=16]="UNAUTHENTICATED",c[c.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",c[c.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",c[c.ABORTED=10]="ABORTED",c[c.OUT_OF_RANGE=11]="OUT_OF_RANGE",c[c.UNIMPLEMENTED=12]="UNIMPLEMENTED",c[c.INTERNAL=13]="INTERNAL",c[c.UNAVAILABLE=14]="UNAVAILABLE",c[c.DATA_LOSS=15]="DATA_LOSS";class uD{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){tx(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return nx(this.inner)}size(){return this.innerSize}}class hD{constructor(e,t){this.comparator=e,this.root=t||fD.EMPTY}insert(e,t){return new hD(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,fD.BLACK,null,null))}remove(e){return new hD(this.comparator,this.root.remove(e,this.comparator).copy(null,null,fD.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new dD(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new dD(this.root,e,this.comparator,!1)}getReverseIterator(){return new dD(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new dD(this.root,e,this.comparator,!0)}}class dD{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class fD{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:fD.RED,this.left=null!=r?r:fD.EMPTY,this.right=null!=i?i:fD.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new fD(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return fD.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return fD.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,fD.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,fD.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw OR();if(this.right.isRed())throw OR();var e=this.left.check();if(e!==this.right.check())throw OR();return e+(this.isRed()?0:1)}}fD.EMPTY=null,fD.RED=!0,fD.BLACK=!1,fD.EMPTY=new class{constructor(){this.size=0}get key(){throw OR()}get value(){throw OR()}get color(){throw OR()}get left(){throw OR()}get right(){throw OR()}copy(e,t,n,r,i){return this}insert(e,t,n){return new fD(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class pD{constructor(e){this.comparator=e,this.data=new hD(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new gD(this.data.getIterator())}getIteratorFrom(e){return new gD(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof pD))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new pD(this.comparator);return t.data=e,t}}class gD{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function mD(e){return e.hasNext()?e.getNext():void 0}const vD=new hD(wx.comparator);const yD=new hD(wx.comparator);function _D(){return new uD(e=>e.toString(),(e,t)=>e.isEqual(t))}const wD=new hD(wx.comparator),bD=new pD(wx.comparator);function ID(...e){let t=bD;for(const n of e)t=t.add(n);return t}const TD=new pD(QR);class ED{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,SD.createSynthesizedTargetChangeForCurrentChange(e,t)),new ED(ZR.min(),n,TD,vD,ID())}}class SD{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t){return new SD(cx.EMPTY_BYTE_STRING,t,ID(),ID(),ID())}}class kD{constructor(e,t,n,r){this.O=e,this.removedTargetIds=t,this.key=n,this.F=r}}class CD{constructor(e,t){this.targetId=e,this.$=t}}class AD{constructor(e,t,n=cx.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ND{constructor(){this.B=0,this.L=PD(),this.U=cx.EMPTY_BYTE_STRING,this.q=!1,this.K=!0}get current(){return this.q}get resumeToken(){return this.U}get G(){return 0!==this.B}get j(){return this.K}W(e){0<e.approximateByteSize()&&(this.K=!0,this.U=e)}H(){let n=ID(),r=ID(),i=ID();return this.L.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:OR()}}),new SD(this.U,this.q,n,r,i)}J(){this.K=!1,this.L=PD()}Y(e,t){this.K=!0,this.L=this.L.insert(e,t)}X(e){this.K=!0,this.L=this.L.remove(e)}Z(){this.B+=1}tt(){--this.B}et(){this.K=!0,this.q=!0}}class RD{constructor(e){this.nt=e,this.st=new Map,this.it=vD,this.rt=xD(),this.ot=new pD(QR)}ut(e){for(const t of e.O)e.F&&e.F.isFoundDocument()?this.at(t,e.F):this.ct(t,e.key,e.F);for(const n of e.removedTargetIds)this.ct(n,e.key,e.F)}ht(n){this.forEachTarget(n,e=>{const t=this.lt(e);switch(n.state){case 0:this.ft(e)&&t.W(n.resumeToken);break;case 1:t.tt(),t.G||t.J(),t.W(n.resumeToken);break;case 2:t.tt(),t.G||this.removeTarget(e);break;case 3:this.ft(e)&&(t.et(),t.W(n.resumeToken));break;case 4:this.ft(e)&&(this.dt(e),t.W(n.resumeToken));break;default:OR()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.st.forEach((e,t)=>{this.ft(t)&&n(t)})}_t(e){const t=e.targetId,n=e.$.count,r=this.wt(t);if(r){const e=r.target;if(Xx(e))if(0===n){const n=new wx(e.path);this.ct(t,n,jx.newNoDocument(n,ZR.min()))}else MR(1===n);else this.gt(t)!==n&&(this.dt(t),this.ot=this.ot.add(t))}}yt(r){const i=new Map;this.st.forEach((e,t)=>{var n=this.wt(t);if(n){if(e.current&&Xx(n.target)){const i=new wx(n.target.path);null!==this.it.get(i)||this.It(t,i)||this.ct(t,i,jx.newNoDocument(i,r))}e.j&&(i.set(t,e.H()),e.J())}});let s=ID();this.rt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.wt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.it.forEach((e,t)=>t.setReadTime(r));var e=new ED(r,i,this.ot,this.it,s);return this.it=vD,this.rt=xD(),this.ot=new pD(QR),e}at(e,t){var n;this.ft(e)&&(n=this.It(e,t.key)?2:0,this.lt(e).Y(t.key,n),this.it=this.it.insert(t.key,t),this.rt=this.rt.insert(t.key,this.Tt(t.key).add(e)))}ct(e,t,n){if(this.ft(e)){const r=this.lt(e);this.It(e,t)?r.Y(t,1):r.X(t),this.rt=this.rt.insert(t,this.Tt(t).delete(e)),n&&(this.it=this.it.insert(t,n))}}removeTarget(e){this.st.delete(e)}gt(e){var t=this.lt(e).H();return this.nt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Z(e){this.lt(e).Z()}lt(e){let t=this.st.get(e);return t||(t=new ND,this.st.set(e,t)),t}Tt(e){let t=this.rt.get(e);return t||(t=new pD(QR),this.rt=this.rt.insert(e,t)),t}ft(e){var t=null!==this.wt(e);return t||RR("WatchChangeAggregator","Detected inactive target",e),t}wt(e){var t=this.st.get(e);return t&&t.G?null:this.nt.Et(e)}dt(t){this.st.set(t,new ND),this.nt.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}It(e,t){return this.nt.getRemoteKeysForTarget(e).has(t)}}function xD(){return new hD(wx.comparator)}function PD(){return new hD(wx.comparator)}const DD={asc:"ASCENDING",desc:"DESCENDING"},OD={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class MD{constructor(e,t){this.databaseId=e,this.N=t}}function LD(e,t){return e.N?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function FD(e,t){return e.N?t.toBase64():t.toUint8Array()}function UD(e){return MR(!!e),ZR.fromTimestamp((t=ux(e),new XR(t.seconds,t.nanos)));var t}function qD(e,t){return e=e,new ix(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function jD(e){var t=ix.fromString(e);return MR(i1(t)),t}function VD(e,t){return qD(e.databaseId,t.path)}function BD(e,t){const n=jD(t);if(n.get(1)!==e.databaseId.projectId)throw new FR(LR.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new FR(LR.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new wx(zD(n))}function KD(e,t){return qD(e.databaseId,t)}function $D(e){var t=jD(e);return 4===t.length?ix.emptyPath():zD(t)}function WD(e){return new ix(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function zD(e){return MR(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function GD(e,t,n){return{name:VD(e,t),fields:n.value.mapValue.fields}}function HD(e,t,n){const r=BD(e,t.name),i=UD(t.updateTime),s=new qx({mapValue:{fields:t.fields}}),o=jx.newFoundDocument(r,i,s);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function QD(e,t){let n;if(t instanceof eD)n={update:GD(e,t.key,t.value)};else if(t instanceof sD)n={delete:VD(e,t.key)};else if(t instanceof tD)n={update:GD(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof oD))return OR();n={verify:VD(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof FP)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof UP)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof jP)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof BP)return{fieldPath:e.field.canonicalString(),increment:t.k};throw OR()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,LD(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:OR()),n;var r}function YD(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?GP.updateTime(UD(i.updateTime)):void 0!==i.exists?GP.exists(i.exists):GP.none():GP.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)MR("REQUEST_TIME"===t.setToServerValue),n=new FP;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new UP(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new jP(e)}else"increment"in t?n=new BP(e,t.increment):OR();var r=ox.fromServerFormat(t.fieldPath);return new WP(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=BD(t,n.update.name),o=new qx({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new ax(e.map(e=>ox.fromServerFormat(e)))}();return new tD(s,o,t,e,r)}return new eD(s,o,e,r)}if(n.delete){const r=BD(t,n.delete);return new sD(r,e)}if(n.verify){const r=BD(t,n.verify);return new oD(r,e)}return OR()}function JD(e,t){return{documents:[KD(e,t.path)]}}function XD(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=KD(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=KD(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if(Dx(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NAN"}};if(Px(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Dx(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NOT_NAN"}};if(Px(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:e1(e.field),op:(t=e.op,OD[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:e1(e.field),direction:(e=e.dir,DD[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.N||vx(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(i=t.startAt).inclusive,values:i.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function ZD(e){let t=$D(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){MR(1===r);const p=n.from[0];p.allDescendants?i=p.collectionId:t=t.child(p.collectionId)}let s=[];n.where&&(s=function t(e){return e?void 0!==e.unaryFilter?[r1(e)]:void 0!==e.fieldFilter?[n1(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):OR():[]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new dP(t1(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let a=null;var c,l,u,h;n.limit&&(a=(e=n.limit,vx(c="object"==typeof e?e.value:e)?null:c));let d=null;n.startAt&&(d=(l=n.startAt,h=!!l.before,u=l.values||[],new hP(u,h)));let f=null;return n.endAt&&(f=(l=n.endAt,u=!l.before,h=l.values||[],new hP(h,u))),mP(t,i,o,s,a,"F",d,f)}function e1(e){return{fieldPath:e.canonicalString()}}function t1(e){return ox.fromServerFormat(e.fieldPath)}function n1(e){return nP.create(t1(e.fieldFilter.field),function(){switch(e.fieldFilter.op){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return OR()}}(),e.fieldFilter.value)}function r1(e){switch(e.unaryFilter.op){case"IS_NAN":var t=t1(e.unaryFilter.field);return nP.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=t1(e.unaryFilter.field);return nP.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=t1(e.unaryFilter.field);return nP.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=t1(e.unaryFilter.field);return nP.create(n,"!=",{nullValue:"NULL_VALUE"});default:return OR()}}function i1(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function s1(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=o1(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return o1(t)}function o1(e){return e+""}function a1(t){const n=t.length;if(MR(2<=n),2===n)return MR(""===t.charAt(0)&&""===t.charAt(1)),ix.emptyPath();const r=n-2,i=[];let s="";for(let o=0;o<n;){const n=t.indexOf("",o);switch((n<0||n>r)&&OR(),t.charAt(n+1)){case"":const r=t.substring(o,n);let e;0===s.length?e=r:(s+=r,e=s,s=""),i.push(e);break;case"":s+=t.substring(o,n),s+="\0";break;case"":s+=t.substring(o,n+1);break;default:OR()}o=n+2}return new ix(i)}const c1=["userId","batchId"];function l1(e,t){return[e,s1(t)]}function u1(e,t,n){return[e,s1(t),n]}const h1={},d1=["prefixPath","collectionGroup","readTime","documentId"],f1=["prefixPath","collectionGroup","documentId"],p1=["collectionGroup","readTime","prefixPath","documentId"],g1=["canonicalId","targetId"],m1=["targetId","path"],v1=["path","targetId"],y1=["collectionId","parent"],_1=["indexId","uid"],w1=["uid","sequenceNumber"],b1=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],I1=["indexId","uid","orderedDocumentKey"],T1=["userId","collectionPath","documentId"],E1=["userId","collectionPath","largestBatchId"],S1=["userId","collectionGroup","largestBatchId"],k1=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],C1=[...k1,"documentOverlays"],A1=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],N1=[...A1,"indexConfiguration","indexState","indexEntries"],R1="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class x1{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class P1{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&OR(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new P1((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof P1?t:P1.resolve(t)}catch(e){return P1.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):P1.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):P1.reject(t)}static resolve(n){return new P1((e,t)=>{e(n)})}static reject(n){return new P1((e,t)=>{t(n)})}static waitFor(e){return new P1((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=P1.resolve(!1);for(const n of e)t=t.next(e=>e?P1.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}}class D1{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.At=new UR,this.transaction.oncomplete=()=>{this.At.resolve()},this.transaction.onabort=()=>{e.error?this.At.reject(new L1(n,e.error)):this.At.resolve()},this.transaction.onerror=e=>{var t=V1(e.target.error);this.At.reject(new L1(n,t))}}static open(e,t,n,r){try{return new D1(t,e.transaction(r,n))}catch(e){throw new L1(t,e)}}get Rt(){return this.At.promise}abort(e){e&&this.At.reject(e),this.aborted||(RR("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}Pt(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new U1(t)}}class O1{constructor(e,t,n){this.name=e,this.version=t,this.bt=n,12.2===O1.Vt(sd())&&xR("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return RR("SimpleDb","Removing database:",e),q1(window.indexedDB.deleteDatabase(e)).toPromise()}static vt(){if(!dd())return!1;if(O1.St())return!0;const e=sd(),t=O1.Vt(e),n=0<t&&t<10,r=O1.Dt(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static St(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Ct)}static xt(e,t){return e.store(t)}static Vt(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static Dt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Nt(s){return this.db||(RR("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new L1(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new FR(LR.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new FR(LR.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new L1(s,t))},i.onupgradeneeded=e=>{RR("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.bt.kt(t,i.transaction,e.oldVersion,this.version).next(()=>{RR("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Mt&&(this.db.onversionchange=e=>this.Mt(e)),this.db}Ot(t){this.Mt=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.Nt(e);const t=D1.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.Pt(),e)).catch(e=>(t.abort(e),P1.reject(e))).toPromise();return s.catch(()=>{}),await t.Rt,s}catch(e){const t="FirebaseError"!==e.name&&s<3;if(RR("SimpleDb","Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}class M1{constructor(e){this.Ft=e,this.$t=!1,this.Bt=null}get isDone(){return this.$t}get Lt(){return this.Bt}set cursor(e){this.Ft=e}done(){this.$t=!0}Ut(e){this.Bt=e}delete(){return q1(this.Ft.delete())}}class L1 extends FR{constructor(e,t){super(LR.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function F1(e){return"IndexedDbTransactionError"===e.name}class U1{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(RR("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(RR("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),q1(n)}add(e){return RR("SimpleDb","ADD",this.store.name,e,e),q1(this.store.add(e))}get(t){return q1(this.store.get(t)).next(e=>(RR("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return RR("SimpleDb","DELETE",this.store.name,e),q1(this.store.delete(e))}count(){return RR("SimpleDb","COUNT",this.store.name),q1(this.store.count())}qt(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.Kt(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new P1((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}Gt(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new P1((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Qt(e,t){RR("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.jt=!1;var r=this.cursor(n);return this.Kt(r,(e,t,n)=>n.delete())}Wt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Kt(r,t)}zt(i){const e=this.cursor({});return new P1((n,r)=>{e.onerror=e=>{var t=V1(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}Kt(e,s){const o=[];return new P1((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new M1(t),r=s(t.primaryKey,t.value,n);if(r instanceof P1){const e=r.catch(e=>(n.done(),P1.reject(e)));o.push(e)}n.isDone?i():null===n.Lt?t.continue():t.continue(n.Lt)}else i()}}).next(()=>P1.waitFor(o))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.jt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function q1(e){return new P1((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=V1(e.target.error);r(t)}})}let j1=!1;function V1(e){const t=O1.Vt(sd());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new FR("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return j1||(j1=!0,setTimeout(()=>{throw e},0)),e}}return e}class B1 extends x1{constructor(e,t){super(),this.Ht=e,this.currentSequenceNumber=t}}function K1(e,t){var n=e;return O1.xt(n.Ht,t)}class $1{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&YP(i,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&JP(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&JP(n,e,this.localWriteTime)}applyToLocalDocumentSet(r){this.mutations.forEach(e=>{const t=r.get(e.key),n=t;this.applyToLocalView(n),t.isValidDocument()||n.convertToNoDocument(ZR.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),ID())}isEqual(e){return this.batchId===e.batchId&&YR(this.mutations,e.mutations,(e,t)=>XP(e,t))&&YR(this.baseMutations,e.baseMutations,(e,t)=>XP(e,t))}}class W1{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){MR(e.mutations.length===n.length);let r=wD;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new W1(e,t,n,r)}}class z1{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class G1{constructor(e,t,n,r,i=ZR.min(),s=ZR.min(),o=cx.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o}withSequenceNumber(e){return new G1(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new G1(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new G1(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class H1{constructor(e){this.Jt=e}}function Q1(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Y1(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:VD(i=e.Jt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:LD(i,e.version.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:J1(t.version)};else{if(!t.isUnknownDocument())return OR();r.unknownDocument={path:n.path.toArray(),version:J1(t.version)}}var i;return r}function Y1(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function J1(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function X1(e){var t=new XR(e.seconds,e.nanoseconds);return ZR.fromTimestamp(t)}function Z1(t,e){const n=(e.baseMutations||[]).map(e=>YD(t.Jt,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>YD(t.Jt,e)),i=XR.fromMillis(e.localWriteTimeMs);return new $1(e.batchId,i,n,r)}function eO(e){var t,n=X1(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?X1(e.lastLimboFreeSnapshotVersion):ZR.min();let i;return i=void 0!==e.query.documents?(MR(1===(t=e.query).documents.length),EP(vP($D(t.documents[0])))):EP(ZD(e.query)),new G1(i,e.targetId,0,e.lastListenSequenceNumber,n,r,cx.fromBase64String(e.resumeToken))}function tO(e,t){var n=J1(t.snapshotVersion),r=J1(t.lastLimboFreeSnapshotVersion),i=(Xx(t.target)?JD:XD)(e.Jt,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Yx(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function nO(e){var t=ZD({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?SP(t,t.limit,"L"):t}function rO(e,t){return new z1(t.largestBatchId,YD(e.Jt,t.overlayMutation))}function iO(e,t){var n=t.path.lastSegment();return[e,s1(t.path.popLast()),n]}class sO{getBundleMetadata(e,t){return oO(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:X1(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return oO(e).put({bundleId:(n=t).id,createTime:J1(UD(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return aO(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:nO(t.bundledQuery),readTime:X1(t.readTime)};var t})}saveNamedQuery(e,t){return aO(e).put({name:(t=t).name,readTime:J1(UD(t.readTime)),bundledQuery:t.bundledQuery})}}function oO(e){return K1(e,"bundles")}function aO(e){return K1(e,"namedQueries")}class cO{constructor(e,t){this.M=e,this.userId=t}static Yt(e,t){var n=t.uid||"";return new cO(e,n)}getOverlay(e,t){return lO(e).get(iO(this.userId,t)).next(e=>e?rO(this.M,e):null)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new z1(i,t);s.push(this.Xt(r,n))}),P1.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(s1(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(lO(n).Qt("collectionPathOverlayIndex",t))}),P1.waitFor(i)}getOverlaysForCollection(e,t,n){const r=_D(),i=s1(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return lO(e).qt("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=rO(this.M,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=_D();let o;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return lO(e).Wt({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=rO(this.M,t);s.size()<i||r.largestBatchId===o?(s.set(r.getKey(),r),o=r.largestBatchId):n.done()}).next(()=>s)}Xt(e,t){return lO(e).put(function(e,t,n){var[,r,i]=iO(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:QD(e.Jt,n.mutation)}}(this.M,this.userId,t))}}function lO(e){return K1(e,"documentOverlays")}class uO{constructor(){}Zt(e,t){this.te(e,t),t.ee()}te(e,t){var n,r;"nullValue"in e?this.ne(t,5):"booleanValue"in e?(this.ne(t,10),t.se(e.booleanValue?1:0)):"integerValue"in e?(this.ne(t,15),t.se(hx(e.integerValue))):"doubleValue"in e?(n=hx(e.doubleValue),isNaN(n)?this.ne(t,13):(this.ne(t,15),yx(n)?t.se(0):t.se(n))):"timestampValue"in e?(r=e.timestampValue,this.ne(t,20),"string"==typeof r?t.ie(r):(t.ie(`${r.seconds||""}`),t.se(r.nanos||0))):"stringValue"in e?(this.re(e.stringValue,t),this.oe(t)):"bytesValue"in e?(this.ne(t,30),t.ue(dx(e.bytesValue)),this.oe(t)):"referenceValue"in e?this.ae(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.ne(t,45),t.se(r.latitude||0),t.se(r.longitude||0)):"mapValue"in e?Lx(e)?this.ne(t,Number.MAX_SAFE_INTEGER):(this.ce(e.mapValue,t),this.oe(t)):"arrayValue"in e?(this.he(e.arrayValue,t),this.oe(t)):OR()}re(e,t){this.ne(t,25),this.le(e,t)}le(e,t){t.ie(e)}ce(e,t){var n=e.fields||{};this.ne(t,55);for(const e of Object.keys(n))this.re(e,t),this.te(n[e],t)}he(e,t){var n=e.values||[];this.ne(t,50);for(const e of n)this.te(e,t)}ae(e,t){this.ne(t,37),wx.fromName(e).path.forEach(e=>{this.ne(t,60),this.le(e,t)})}ne(e,t){e.se(t)}oe(e){e.se(2)}}function hO(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}uO.fe=new uO;class dO{constructor(){this.buffer=new Uint8Array(1024),this.position=0}de(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this._e(n.value),n=t.next();this.we()}me(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.ge(n.value),n=t.next();this.ye()}pe(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this._e(e);else if(e<2048)this._e(960|e>>>6),this._e(128|63&e);else if(t<"\ud800"||"\udbff"<t)this._e(480|e>>>12),this._e(128|63&e>>>6),this._e(128|63&e);else{const e=t.codePointAt(0);this._e(240|e>>>18),this._e(128|63&e>>>12),this._e(128|63&e>>>6),this._e(128|63&e)}}this.we()}Ie(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.ge(e);else if(e<2048)this.ge(960|e>>>6),this.ge(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.ge(480|e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e);else{const e=t.codePointAt(0);this.ge(240|e>>>18),this.ge(128|63&e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e)}}this.ye()}Te(e){var t=this.Ee(e),n=hO(t);this.Ae(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Re(e){var t=this.Ee(e),n=hO(t);this.Ae(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}Pe(){this.be(255),this.be(255)}Ve(){this.ve(255),this.ve(255)}reset(){this.position=0}seed(e){this.Ae(e.length),this.buffer.set(e,this.position),this.position+=e.length}Se(){return this.buffer.slice(0,this.position)}Ee(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}_e(e){var t=255&e;0==t?(this.be(0),this.be(255)):255==t?(this.be(255),this.be(0)):this.be(t)}ge(e){var t=255&e;0==t?(this.ve(0),this.ve(255)):255==t?(this.ve(255),this.ve(0)):this.ve(e)}we(){this.be(0),this.be(1)}ye(){this.ve(0),this.ve(1)}be(e){this.Ae(1),this.buffer[this.position++]=e}ve(e){this.Ae(1),this.buffer[this.position++]=~e}Ae(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class fO{constructor(e){this.De=e}ue(e){this.De.de(e)}ie(e){this.De.pe(e)}se(e){this.De.Te(e)}ee(){this.De.Pe()}}class pO{constructor(e){this.De=e}ue(e){this.De.me(e)}ie(e){this.De.Ie(e)}se(e){this.De.Re(e)}ee(){this.De.Ve()}}class gO{constructor(){this.De=new dO,this.Ce=new fO(this.De),this.xe=new pO(this.De)}seed(e){this.De.seed(e)}Ne(e){return 0===e?this.Ce:this.xe}Se(){return this.De.Se()}reset(){this.De.reset()}}class mO{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}ke(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new mO(this.indexId,this.documentKey,this.arrayValue,n)}}function vO(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=yO(e.arrayValue,t.arrayValue),0!==n?n:(n=yO(e.directionalValue,t.directionalValue),0!==n?n:wx.comparator(e.documentKey,t.documentKey)))}function yO(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class _O{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Me=e.orderBy,this.Oe=[];for(const t of e.filters){const e=t;e.S()?this.Fe=e:this.Oe.push(e)}}$e(e){var t=Bx(e);if(void 0!==t&&!this.Be(t))return!1;var n=Kx(e);let r=0,i=0;for(;r<n.length&&this.Be(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Fe){const e=n[r];if(!this.Le(this.Fe,e)||!this.Ue(this.Me[i++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(i>=this.Me.length||!this.Ue(this.Me[i++],e))return!1}return!0}Be(e){for(const t of this.Oe)if(this.Le(t,e))return!0;return!1}Le(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}Ue(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}class wO{constructor(){this.qe=new bO}addToCollectionParentIndex(e,t){return this.qe.add(t),P1.resolve()}getCollectionParents(e,t){return P1.resolve(this.qe.getEntries(t))}addFieldIndex(e,t){return P1.resolve()}deleteFieldIndex(e,t){return P1.resolve()}getDocumentsMatchingTarget(e,t){return P1.resolve(null)}getFieldIndex(e,t){return P1.resolve(null)}getFieldIndexes(e,t){return P1.resolve([])}getNextCollectionGroupToUpdate(e){return P1.resolve(null)}updateCollectionGroup(e,t,n){return P1.resolve()}updateIndexEntries(e,t){return P1.resolve()}}class bO{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new pD(ix.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new pD(ix.comparator)).toArray()}}const IO=new Uint8Array(0);class TO{constructor(e,t){this.user=e,this.databaseId=t,this.Ke=new bO,this.Ge=new uD(e=>Yx(e),(e,t)=>Jx(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Ke.has(t))return P1.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ke.add(t)});r={collectionId:n,parent:s1(r)};return EO(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[JR(n),""],!1,!0);return EO(e).qt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(a1(t.parent))}return r})}addFieldIndex(e,t){const n=kO(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};return delete r.indexId,n.add(r).next()}deleteFieldIndex(e,t){const n=kO(e),r=CO(e),i=SO(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,l){const u=SO(e);let h=!0;const n=new Map;return P1.forEach(this.Qe(l),t=>this.getFieldIndex(e,t).next(e=>{h=h&&!!e,n.set(t,e)})).next(()=>{if(h){let c=ID();const h=[];return P1.forEach(n,(e,t)=>{RR("IndexedDbIndexManager",`Using index ${a=e,`id=${a.indexId}|cg=${a.collectionGroup}|f=${a.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Yx(l)}`);var n=function(e,t){var n=Bx(t);if(void 0===n)return null;for(const t of Zx(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of Kx(t))for(const t of Zx(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),i=function(e,t){const n=[];let r=!0;for(const i of Kx(t)){const t=(0===i.kind?eP:tP)(e,i.fieldPath,e.startAt);if(!t.value)return null;n.push(t.value),r=r&&t.inclusive}return new hP(n,r)}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of Kx(t)){const t=(0===i.kind?tP:eP)(e,i.fieldPath,e.endAt);if(!t.value)return null;n.push(t.value),r=r&&t.inclusive}return new hP(n,r)}(t,e),o=this.je(e,t,i),a=this.je(e,t,s),r=this.We(e,t,r),r=this.ze(e.indexId,n,o,!!i&&i.inclusive,a,!!s&&s.inclusive,r);return P1.forEach(r,e=>u.Gt(e,l.limit).next(e=>{e.forEach(e=>{var t=wx.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),h.push(t))})}))}).next(()=>h)}return P1.resolve(null)})}Qe(e){var t;return(t=this.Ge.get(e))||(this.Ge.set(e,t=[e]),t)}ze(t,e,n,r,i,s,o){const a=(null!=e?e.length:1)*Math.max(null!=n?n.length:1,null!=i?i.length:1),c=a/(null!=e?e.length:1),l=[];for(let u=0;u<a;++u){const a=e?this.He(e[u/c]):IO,h=n?this.Je(t,a,n[u%c],r):this.Ye(t),d=i?this.Xe(t,a,i[u%c],s):this.Ye(t+1);l.push(...this.createRange(h,d,o.map(e=>this.Je(t,a,e,!0))))}return l}Je(e,t,n,r){const i=new mO(e,wx.empty(),t,n);return r?i:i.ke()}Xe(e,t,n,r){const i=new mO(e,wx.empty(),t,n);return r?i.ke():i}Ye(e){return new mO(e,wx.empty(),IO,IO)}getFieldIndex(e,t){const n=new _O(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{const t=e.filter(e=>n.$e(e));return t.sort((e,t)=>t.fields.length-e.fields.length),0<t.length?t[0]:null})}Ze(e,t){const n=new gO;for(const i of Kx(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Ne(i.kind);uO.fe.Zt(e,r)}return n.Se()}He(e){const t=new gO;return uO.fe.Zt(e,t.Ne(0)),t.Se()}tn(e,t){const n=new gO;return uO.fe.Zt(Nx(this.databaseId,t),n.Ne(0===(r=Kx(e)).length?0:r[r.length-1].kind)),n.Se();var r}We(e,t,n){if(null===n)return[];let r=[];r.push(new gO);let i=0;for(const s of Kx(e)){const e=n[i++];for(const n of r)if(this.en(t,s.fieldPath)&&xx(e))r=this.nn(r,s,e);else{const t=n.Ne(s.kind);uO.fe.Zt(e,t)}}return this.sn(r)}je(e,t,n){return null==n?null:this.We(e,t,n.position)}sn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Se();return t}nn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new gO;r.seed(n.Se()),uO.fe.Zt(e,r.Ne(t.kind)),i.push(r)}return i}en(e,t){return!!e.filters.find(e=>e instanceof nP&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=kO(e),r=CO(e);return(t?n.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.qt()).next(e=>{const s=[];return P1.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new Wx(e.sequenceNumber,new Gx(X1(e.readTime),new wx(a1(e.documentKey)),e.largestBatchId)):Wx.empty(),r=t.fields.map(([e,t])=>new $x(ox.fromServerFormat(e),t)),new Vx(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:QR(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){const i=kO(e),s=CO(e);return this.rn(e).next(r=>i.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(e=>P1.forEach(e,e=>s.put(function(e,t,n){return{indexId:e,uid:t.uid||"",sequenceNumber:r,readTime:J1(n.readTime),documentKey:s1(n.documentKey.path),largestBatchId:n.largestBatchId}}(e.indexId,this.user,n)))))}updateIndexEntries(i,e){const n=new Map;return P1.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?P1.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),P1.forEach(e,n=>this.on(i,t,n).next(e=>{var t=this.un(r,n);return e.isEqual(t)?P1.resolve():this.an(i,r,n,e,t)}))))})}cn(e,t,n,r){return SO(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.tn(n,t.key),documentKey:t.key.path.toArray()})}hn(e,t,n,r){return SO(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.tn(n,t.key),t.key.path.toArray()])}on(e,n,r){const t=SO(e);let i=new pD(vO);return t.Wt({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.tn(r,n)])},(e,t)=>{i=i.add(new mO(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}un(e,t){let n=new pD(vO);var r=this.Ze(t,e);if(null==r)return n;const i=Bx(t);if(null!=i){var s=e.data.field(i.fieldPath);if(xx(s))for(const i of s.arrayValue.values||[])n=n.add(new mO(t.indexId,e.key,this.He(i),r))}else n=n.add(new mO(t.indexId,e.key,IO,r));return n}an(t,n,r,l,e){RR("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const i=[];return function(e,n,r,i){var s=l.getIterator(),o=e.getIterator();let a=mD(s),c=mD(o);for(;a||c;){let e=!1,t=!1;if(a&&c){const r=n(a,c);r<0?t=!0:0<r&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(c),c=mD(o)):t?(i(a),a=mD(s)):(a=mD(s),c=mD(o))}}(e,vO,e=>{i.push(this.cn(t,n,r,e))},e=>{i.push(this.hn(t,n,r,e))}),P1.waitFor(i)}rn(e){let r=1;return CO(e).Wt({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>vO(e,t)).filter((e,t,n)=>!t||0!==vO(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=vO(i,e),s=vO(i,t);if(0===n)r[0]=e.ke();else if(0<n&&s<0)r.push(i),r.push(i.ke());else if(0<s)break}r.push(t);const i=[];for(let o=0;o<r.length;o+=2)i.push(IDBKeyRange.bound([r[o].indexId,this.uid,r[o].arrayValue,r[o].directionalValue,IO,[]],[r[o+1].indexId,this.uid,r[o+1].arrayValue,r[o+1].directionalValue,IO,[]]));return i}}function EO(e){return K1(e,"collectionParents")}function SO(e){return K1(e,"indexEntries")}function kO(e){return K1(e,"indexConfiguration")}function CO(e){return K1(e,"indexState")}const AO={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class NO{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new NO(e,NO.DEFAULT_COLLECTION_PERCENTILE,NO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function RO(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.Wt({range:o},(e,t,n)=>(a++,n.delete()));s.push(c.next(()=>{MR(1===a)}));const l=[];for(const e of n.mutations){const r=u1(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return P1.waitFor(s).next(()=>l)}function xO(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw OR();t=e.noDocument}return JSON.stringify(t).length}NO.DEFAULT_COLLECTION_PERCENTILE=10,NO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,NO.DEFAULT=new NO(41943040,NO.DEFAULT_COLLECTION_PERCENTILE,NO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),NO.DISABLED=new NO(-1,0,0);class PO{constructor(e,t,n,r){this.userId=e,this.M=t,this.indexManager=n,this.referenceDelegate=r,this.ln={}}static Yt(e,t,n,r){MR(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new PO(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return OO(e).Wt({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,f){const p=MO(u),g=OO(u);return g.add({}).next(e=>{MR("number"==typeof e);const t=new $1(e,h,d,f),n=(i=this.M,s=this.userId,o=t,a=o.baseMutations.map(e=>QD(i.Jt,e)),c=o.mutations.map(e=>QD(i.Jt,e)),{userId:s,batchId:o.batchId,localWriteTimeMs:o.localWriteTime.toMillis(),baseMutations:a,mutations:c}),r=[];var i,s,o,a,c;let l=new pD((e,t)=>QR(e.canonicalString(),t.canonicalString()));for(const u of f){const h=u1(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(p.put(h,h1))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.ln[e]=t.keys()}),P1.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return OO(e).get(t).next(e=>e?(MR(e.userId===this.userId),Z1(this.M,e)):null)}fn(e,n){return this.ln[n]?P1.resolve(this.ln[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.ln[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return OO(e).Wt({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(MR(t.batchId>=r),i=Z1(this.M,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return OO(e).Wt({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return OO(e).qt("userMutationsIndex",t).next(e=>e.map(e=>Z1(this.M,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=l1(this.userId,a.path),t=IDBKeyRange.lowerBound(e),c=[];return MO(o).Wt({range:t},(e,t,n)=>{var[r,i,s]=e,i=a1(i);if(r===this.userId&&a.path.isEqual(i))return OO(o).get(s).next(e=>{if(!e)throw OR();MR(e.userId===this.userId),c.push(Z1(this.M,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new pD(QR);const n=[];return e.forEach(o=>{var e=l1(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=MO(t).Wt({range:e},(e,t,n)=>{var[r,i,s]=e,i=a1(i);r===this.userId&&o.path.isEqual(i)?a=a.add(s):n.done()});n.push(e)}),P1.waitFor(n).next(()=>this.dn(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=l1(this.userId,o),r=IDBKeyRange.lowerBound(n);let c=new pD(QR);return MO(e).Wt({range:r},(e,t,n)=>{var[r,i,s]=e,i=a1(i);r===this.userId&&o.isPrefixOf(i)?i.length===a&&(c=c.add(s)):n.done()}).next(()=>this.dn(e,c))}dn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(OO(t).get(e).next(e=>{if(null===e)throw OR();MR(e.userId===this.userId),n.push(Z1(this.M,e))}))}),P1.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return RO(t.Ht,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this._n(n.batchId)}),P1.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}_n(e){delete this.ln[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return P1.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return MO(n).Wt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=a1(e[1]);r.push(t)}else n.done()}).next(()=>{MR(0===r.length)})})}containsKey(e,t){return DO(e,this.userId,t)}wn(e){return LO(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function DO(e,s,t){const n=l1(s,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return MO(e).Wt({range:r,jt:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===o&&(a=!0),n.done()}).next(()=>a)}function OO(e){return K1(e,"mutations")}function MO(e){return K1(e,"documentMutations")}function LO(e){return K1(e,"mutationQueues")}class FO{constructor(e){this.mn=e}next(){return this.mn+=2,this.mn}static gn(){return new FO(0)}static yn(){return new FO(-1)}}class UO{constructor(e,t){this.referenceDelegate=e,this.M=t}allocateTargetId(n){return this.pn(n).next(e=>{const t=new FO(e.highestTargetId);return e.highestTargetId=t.next(),this.In(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.pn(e).next(e=>ZR.fromTimestamp(new XR(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.pn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.pn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.In(t,e)))}addTargetData(t,n){return this.Tn(t,n).next(()=>this.pn(t).next(e=>(e.targetCount+=1,this.En(n,e),this.In(t,e))))}updateTargetData(e,t){return this.Tn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>qO(t).delete(e.targetId)).next(()=>this.pn(t)).next(e=>(MR(0<e.targetCount),--e.targetCount,this.In(t,e)))}removeTargets(r,i,s){let o=0;const a=[];return qO(r).Wt((e,t)=>{var n=eO(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>P1.waitFor(a)).next(()=>o)}forEachTarget(e,r){return qO(e).Wt((e,t)=>{var n=eO(t);r(n)})}pn(e){return jO(e).get("targetGlobalKey").next(e=>(MR(null!==e),e))}In(e,t){return jO(e).put("targetGlobalKey",t)}Tn(e,t){return qO(e).put(tO(this.M,t))}En(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.pn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=Yx(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return qO(e).Wt({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=eO(t);Jx(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=VO(n);return e.forEach(e=>{var t=s1(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),P1.waitFor(i)}removeMatchingKeys(n,e,r){const i=VO(n);return P1.forEach(e,e=>{var t=s1(e.path);return P1.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=VO(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=VO(e);let i=ID();return r.Wt({range:n,jt:!0},(e,t,n)=>{var r=a1(e[1]),r=new wx(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=s1(t.path),n=IDBKeyRange.bound([n],[JR(n)],!1,!0);let r=0;return VO(e).Wt({index:"documentTargetsIndex",jt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Et(e,t){return qO(e).get(t).next(e=>e?eO(e):null)}}function qO(e){return K1(e,"targets")}function jO(e){return K1(e,"targetGlobal")}function VO(e){return K1(e,"targetDocuments")}async function BO(e){if(e.code!==LR.FAILED_PRECONDITION||e.message!==R1)throw e;RR("LocalStore","Unexpectedly lost primary lease")}function KO([e,t],[n,r]){var i=QR(e,n);return 0===i?QR(t,r):i}class $O{constructor(e){this.An=e,this.buffer=new pD(KO),this.Rn=0}Pn(){return++this.Rn}bn(e){var t=[e,this.Pn()];if(this.buffer.size<this.An)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();KO(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class WO{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.Vn=!1,this.vn=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Sn(e)}stop(){this.vn&&(this.vn.cancel(),this.vn=null)}get started(){return null!==this.vn}Sn(e){var t=this.Vn?3e5:6e4;RR("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.vn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.vn=null,this.Vn=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){F1(e)?RR("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await BO(e)}await this.Sn(e)})}}class zO{constructor(e,t){this.Dn=e,this.params=t}calculateTargetCount(e,t){return this.Dn.Cn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return P1.resolve(GR.A);const n=new $O(t);return this.Dn.forEachTarget(e,e=>n.bn(e.sequenceNumber)).next(()=>this.Dn.xn(e,e=>n.bn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Dn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Dn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(RR("LruGarbageCollector","Garbage collection skipped; disabled"),P1.resolve(AO)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(RR("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),AO):this.Nn(t,n))}getCacheSize(e){return this.Dn.getCacheSize(e)}Nn(t,n){let r,i,s,o,a,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(RR("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,o=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,a=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),NR()<=$h.DEBUG&&RR("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-u}ms\n\tDetermined least recently used ${i} in `+(a-o)+"ms\n"+`\tRemoved ${s} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),P1.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class GO{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new zO(e,t))}Cn(e){const n=this.kn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}kn(e){let t=0;return this.xn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}xn(e,n){return this.Mn(e,(e,t)=>n(t))}addReference(e,t,n){return HO(e,n)}removeReference(e,t,n){return HO(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return HO(e,t)}On(t,n){let r=!1;return LO(t).zt(e=>DO(t,e,n).next(e=>(e&&(r=!0),P1.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let o=0;return this.Mn(n,(t,e)=>{if(e<=r){const r=this.On(n,t).next(e=>{if(!e)return o++,i.getEntry(n,t).next(()=>(i.removeEntry(t,ZR.min()),VO(n).delete([0,s1(t.path)])))});s.push(r)}}).next(()=>P1.waitFor(s)).next(()=>i.apply(n)).next(()=>o)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return HO(e,t)}Mn(e,r){const t=VO(e);let i,s=GR.A;return t.Wt({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==GR.A&&r(new wx(a1(i)),s),s=n,i=t):s=GR.A}).next(()=>{s!==GR.A&&r(new wx(a1(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function HO(e,t){return VO(e).put((e=e.currentSequenceNumber,{targetId:0,path:s1(t.path),sequenceNumber:e}))}class QO{constructor(){this.changes=new uD(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,jx.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?P1.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class YO{constructor(e){this.M=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return ZO(e).put(n)}removeEntry(e,n,t){return ZO(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],Y1(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Fn(t,e)))}getEntry(e,n){let r=jx.newInvalidDocument(n);return ZO(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(eM(n))},(e,t)=>{r=this.$n(n,t)}).next(()=>r)}Bn(e,n){let r={size:0,document:jx.newInvalidDocument(n)};return ZO(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(eM(n))},(e,t)=>{r={document:this.$n(n,t),size:xO(t)}}).next(()=>r)}getEntries(e,t){let r=vD;return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n)}).next(()=>r)}Un(e,t){let r=vD,i=new hD(wx.comparator);return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n),i=i.insert(e,xO(t))}).next(()=>({documents:r,qn:i}))}Ln(e,t,i){if(t.isEmpty())return P1.resolve();let n=new pD(nM);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(eM(n.first()),eM(n.last())),s=n.getIterator();let o=s.getNext();return ZO(e).Wt({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=wx.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);o&&nM(o,r)<0;)i(o,null),o=s.getNext();o&&o.isEqual(r)&&(i(o,t),o=s.hasNext()?s.getNext():null),o?n.Ut(eM(o)):n.done()}).next(()=>{for(;o;)i(o,null),o=s.hasNext()?s.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),Y1(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],i=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return ZO(e).qt(IDBKeyRange.bound(r,i,!0)).next(e=>{let t=vD;for(const n of e){const e=this.$n(wx.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,i){let s=vD;var r=tM(t,n),o=tM(t,Gx.max());return ZO(e).Wt({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,o,!0)},(e,t,n)=>{var r=this.$n(wx.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new JO(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return XO(e).get("remoteDocumentGlobalKey").next(e=>(MR(!!e),e))}Fn(e,t){return XO(e).put("remoteDocumentGlobalKey",t)}$n(e,t){if(t){const e=function(e,t){let n;if(t.document)n=HD(e.Jt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=wx.fromSegments(t.noDocument.path),i=X1(t.noDocument.readTime);n=jx.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return OR();{const e=wx.fromSegments(t.unknownDocument.path),s=X1(t.unknownDocument.version);n=jx.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new XR(t[0],t[1]),ZR.fromTimestamp(r))),n;var r}(this.M,t);if(!e.isNoDocument()||!e.version.isEqual(ZR.min()))return e}return jx.newInvalidDocument(e)}}class JO extends QO{constructor(e,t){super(),this.Kn=e,this.trackRemovals=t,this.Gn=new uD(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const o=[];let a=0,c=new pD((e,t)=>QR(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Gn.get(e);if(o.push(this.Kn.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Q1(this.Kn.M,t);c=c.add(e.path.popLast());var i=xO(r);a+=i-n.size,o.push(this.Kn.addEntry(s,e,r))}else if(a-=n.size,this.trackRemovals){const a=Q1(this.Kn.M,t.convertToNoDocument(ZR.min()));o.push(this.Kn.addEntry(s,e,a))}}),c.forEach(e=>{o.push(this.Kn.indexManager.addToCollectionParentIndex(s,e))}),o.push(this.Kn.updateMetadata(s,a)),P1.waitFor(o)}getFromCache(e,t){return this.Kn.Bn(e,t).next(e=>(this.Gn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Kn.Un(e,t).next(({documents:n,qn:e})=>(e.forEach((e,t)=>{this.Gn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function XO(e){return K1(e,"remoteDocumentGlobal")}function ZO(e){return K1(e,"remoteDocumentsV14")}function eM(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function tM(e,t){const n=t.documentKey.path.toArray();return[e,Y1(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function nM(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=QR(n[s],r[s]),i)return i;return i=QR(n.length,r.length),i||(i=QR(n[n.length-2],r[r.length-2]),i||QR(n[n.length-1],r[r.length-1]))}class rM{constructor(e){this.M=e}kt(t,e,n,r){const i=new D1("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",c1,{unique:!0}),s.createObjectStore("documentMutations"),iM(t),t.createObjectStore("remoteDocuments"));let o=P1.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),iM(t)),o=o.next(()=>function(){const e=i.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ZR.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(o=o.next(()=>function(r,i){return i.store("mutations").qt().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",c1,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return P1.waitFor(n)})}(t,i))),o=o.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(o=o.next(()=>this.Qn(i))),n<6&&6<=r&&(o=o.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.jn(i)))),n<7&&7<=r&&(o=o.next(()=>this.Wn(i))),n<8&&8<=r&&(o=o.next(()=>this.zn(t,i))),n<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(o=o.next(()=>this.Hn(i))),n<11&&11<=r&&(o=o.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(o=o.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:T1});e.createIndex("collectionPathOverlayIndex",E1,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",S1,{unique:!1})}()})),n<13&&13<=r&&(o=o.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:d1});e.createIndex("documentKeyIndex",f1),e.createIndex("collectionGroupIndex",p1)}()).next(()=>this.Jn(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(o=o.next(()=>{var e;(e=t).createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:_1}).createIndex("sequenceNumberIndex",w1,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:b1}).createIndex("documentKeyIndex",I1,{unique:!1})})),o}jn(t){let n=0;return t.store("remoteDocuments").Wt((e,t)=>{n+=xO(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Qn(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.qt().next(e=>P1.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.qt("userMutationsIndex",e).next(e=>P1.forEach(e,e=>{MR(e.userId===n.userId);var t=Z1(this.M,e);return RO(r,n.userId,t).next(()=>{})}))}))}Wn(e){const o=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Wt((e,t)=>{const n=new ix(e),r=[0,s1(n)];s.push(o.get(r).next(e=>e?P1.resolve():(e=>o.put({targetId:0,path:s1(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>P1.waitFor(s))})}zn(e,t){e.createObjectStore("collectionParents",{keyPath:y1});const n=t.store("collectionParents"),r=new bO,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:s1(r)})}};return t.store("remoteDocuments").Wt({jt:!0},(e,t)=>{const n=new ix(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Wt({jt:!0},([,e],t)=>{const n=a1(e);return i(n.popLast())}))}Hn(e){const r=e.store("targets");return r.Wt((e,t)=>{var n=eO(t),n=tO(this.M,n);return r.put(n)})}Jn(e,s){const t=s.store("remoteDocuments"),o=[];return t.Wt((e,t)=>{const n=s.store("remoteDocumentsV14"),r=((i=t).document?new wx(ix.fromString(i.document.name).popFirst(5)):i.noDocument?wx.fromSegments(i.noDocument.path):i.unknownDocument?wx.fromSegments(i.unknownDocument.path):OR()).path.toArray();var i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};o.push(n.put(i))}).next(()=>P1.waitFor(o))}}function iM(e){e.createObjectStore("targetDocuments",{keyPath:m1}).createIndex("documentTargetsIndex",v1,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",g1,{unique:!0}),e.createObjectStore("targetGlobal")}const sM="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class oM{constructor(e,t,n,r,i,s,o,a,c,l,u=13){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Yn=i,this.window=s,this.document=o,this.Xn=c,this.Zn=l,this.ts=u,this.es=null,this.ns=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ss=null,this.inForeground=!1,this.rs=null,this.os=null,this.us=Number.NEGATIVE_INFINITY,this.cs=e=>Promise.resolve(),!oM.vt())throw new FR(LR.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new GO(this,r),this.hs=t+"main",this.M=new H1(a),this.ls=new O1(this.hs,this.ts,new rM(this.M)),this.fs=new UO(this.referenceDelegate,this.M),this.ds=(a=this.M,new YO(a)),this._s=new sO,this.window&&this.window.localStorage?this.ws=this.window.localStorage:(this.ws=null,!1===l&&xR("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.gs().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new FR(LR.FAILED_PRECONDITION,sM);return this.ys(),this.ps(),this.Is(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.fs.getHighestSequenceNumber(e))}).then(e=>{this.es=new GR(e,this.Xn)}).then(()=>{this.ns=!0}).catch(e=>(this.ls&&this.ls.close(),Promise.reject(e)))}Ts(t){return this.cs=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ls.Ot(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Yn.enqueueAndForget(async()=>{this.started&&await this.gs()}))}gs(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>cM(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Es(t).next(e=>{e||(this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)))})}).next(()=>this.As(t)).next(e=>this.isPrimary&&!e?this.Rs(t).next(()=>!1):!!e&&this.Ps(t).next(()=>!0))).catch(e=>{if(F1(e))return RR("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return RR("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Yn.enqueueRetryable(()=>this.cs(e)),this.isPrimary=e})}Es(e){return aM(e).get("owner").next(e=>P1.resolve(this.bs(e)))}Vs(e){return cM(e).delete(this.clientId)}async vs(){if(this.isPrimary&&!this.Ss(this.us,18e5)){this.us=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=K1(e,"clientMetadata");return r.qt().next(e=>{const t=this.Ds(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return P1.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.ws)for(const t of e)this.ws.removeItem(this.Cs(t.clientId))}}Is(){this.os=this.Yn.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.gs().then(()=>this.vs()).then(()=>this.Is()))}bs(e){return!!e&&e.ownerId===this.clientId}As(t){return this.Zn?P1.resolve(!0):aM(t).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)){if(this.bs(e)&&this.networkEnabled)return!0;if(!this.bs(e)){if(!e.allowTabSynchronization)throw new FR(LR.FAILED_PRECONDITION,sM);return!1}}return!(!this.networkEnabled||!this.inForeground)||cM(t).qt().next(e=>void 0===this.Ds(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&RR("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.ns=!1,this.Ns(),this.os&&(this.os.cancel(),this.os=null),this.ks(),this.Ms(),await this.ls.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new B1(e,GR.A);return this.Rs(t).next(()=>this.Vs(t))}),this.ls.close(),this.Os()}Ds(e,t){return e.filter(e=>this.Ss(e.updateTimeMs,t)&&!this.xs(e.clientId))}Fs(){return this.runTransaction("getActiveClients","readonly",e=>cM(e).qt().next(e=>this.Ds(e,18e5).map(e=>e.clientId)))}get started(){return this.ns}getMutationQueue(e,t){return PO.Yt(e,this.M,t,this.referenceDelegate)}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getIndexManager(e){return new TO(e,this.M.Jt.databaseId)}getDocumentOverlayCache(e){return cO.Yt(this.M,e)}getBundleCache(){return this._s}runTransaction(t,n,r){RR("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",e=14===(e=this.ts)?N1:13===e?A1:12===e?C1:11===e?k1:void OR();let s;return this.ls.runTransaction(t,i,e,e=>(s=new B1(e,this.es?this.es.next():GR.A),"readwrite-primary"===n?this.Es(s).next(e=>!!e||this.As(s)).next(e=>{if(!e)throw xR(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)),new FR(LR.FAILED_PRECONDITION,R1);return r(s)}).next(e=>this.Ps(s).next(()=>e)):this.$s(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}$s(e){return aM(e).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)&&!this.bs(e)&&!(this.Zn||this.allowTabSynchronization&&e.allowTabSynchronization))throw new FR(LR.FAILED_PRECONDITION,sM)})}Ps(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return aM(e).put("owner",t)}static vt(){return O1.vt()}Rs(e){const t=aM(e);return t.get("owner").next(e=>this.bs(e)?(RR("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):P1.resolve())}Ss(e,t){var n=Date.now();return!(e<n-t||n<e&&(xR(`Detected an update time that is in the future: ${e} > ${n}`),1))}ys(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.rs=()=>{this.Yn.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.gs()))},this.document.addEventListener("visibilitychange",this.rs),this.inForeground="visible"===this.document.visibilityState)}ks(){this.rs&&(this.document.removeEventListener("visibilitychange",this.rs),this.rs=null)}ps(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ss=()=>{this.Ns(),!ad()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match(/Version\/1[45]/)&&this.Yn.enterRestrictedMode(!0),this.Yn.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ss))}Ms(){this.ss&&(this.window.removeEventListener("pagehide",this.ss),this.ss=null)}xs(e){var t;try{var n=null!==(null===(t=this.ws)||void 0===t?void 0:t.getItem(this.Cs(e)));return RR("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return xR("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ns(){if(this.ws)try{this.ws.setItem(this.Cs(this.clientId),String(Date.now()))}catch(e){xR("Failed to set zombie client id.",e)}}Os(){if(this.ws)try{this.ws.removeItem(this.Cs(this.clientId))}catch(e){}}Cs(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function aM(e){return K1(e,"owner")}function cM(e){return K1(e,"clientMetadata")}function lM(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class uM{constructor(e,t,n){this.ds=e,this.Bs=t,this.indexManager=n}Ls(t,n){return this.Bs.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.Us(t,n,e))}Us(e,t,n){return this.ds.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}qs(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Ks(t,e){return this.ds.getEntries(t,e).next(e=>this.Gs(t,e).next(()=>e))}Gs(e,t){return this.Bs.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.qs(t,e))}Qs(e,t,n){return r=t,wx.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.js(e,t.path):IP(t)?this.Ws(e,t,n):this.zs(e,t,n);var r}js(e,t){return this.Ls(e,new wx(t)).next(e=>{let t=yD;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Ws(r,i,s){const o=i.collectionGroup;let a=yD;return this.indexManager.getCollectionParents(r,o).next(e=>P1.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new gP(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.zs(r,n,s).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}zs(t,n,e){let i;return this.ds.getAllFromCollection(t,n.path,e).next(e=>(i=e,this.Bs.getAllMutationBatchesAffectingQuery(t,n))).next(t=>{for(const r of t)for(const t of r.mutations){var n=t.key;let e=i.get(n);null==e&&(e=jx.newInvalidDocument(n),i=i.insert(n,e)),JP(t,e,r.localWriteTime),e.isFoundDocument()||(i=i.remove(n))}}).next(()=>(i.forEach((e,t)=>{NP(n,t)||(i=i.remove(e))}),i))}}class hM{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Hs=n,this.Js=r}static Ys(e,t){let n=ID(),r=ID();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new hM(e,t.fromCache,n,r)}}class dM{Xs(e){this.Zs=e}Qs(t,r,i,s){return 0===(e=r).filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())||i.isEqual(ZR.min())?this.ti(t,r):this.Zs.Ks(t,s).next(e=>{const n=this.ei(r,e);return(yP(r)||_P(r))&&this.ni(r.limitType,n,s,i)?this.ti(t,r):(NR()<=$h.DEBUG&&RR("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),AP(r)),this.Zs.Qs(t,r,zx(i,-1)).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}ei(n,e){let r=new pD(xP(n));return e.forEach((e,t)=>{NP(n,t)&&(r=r.add(t))}),r}ni(e,t,n,r){if(n.size!==t.size)return!0;const i="F"===e?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}ti(e,t){return NR()<=$h.DEBUG&&RR("QueryEngine","Using full collection scan to execute query:",AP(t)),this.Zs.Qs(e,t,Gx.min())}}class fM{constructor(e,t,n,r){this.persistence=e,this.si=t,this.M=r,this.ii=new hD(QR),this.ri=new uD(e=>Yx(e),Jx),this.oi=new Map,this.ui=e.getRemoteDocumentCache(),this.fs=e.getTargetCache(),this._s=e.getBundleCache(),this.ai(n)}ai(e){this.indexManager=this.persistence.getIndexManager(e),this.Bs=this.persistence.getMutationQueue(e,this.indexManager),this.ci=new uM(this.ui,this.Bs,this.indexManager),this.ui.setIndexManager(this.indexManager),this.si.Xs(this.ci)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ii))}}function pM(e,t,n,r){return new fM(e,t,n,r)}async function gM(e,t){const o=e;return o.persistence.runTransaction("Handle user change","readonly",i=>{let s;return o.Bs.getAllMutationBatches(i).next(e=>(s=e,o.ai(t),o.Bs.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=ID();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return o.ci.Ks(i,r).next(e=>({hi:e,removedBatchIds:t,addedBatchIds:n}))})})}function mM(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.fs.getLastRemoteSnapshotVersion(e))}function vM(e,l){const u=e,h=l.snapshotVersion;let d=u.ii;return u.persistence.runTransaction("Apply remote event","readwrite-primary",a=>{const e=u.ui.newChangeBuffer({trackRemovals:!0});d=u.ii;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.fs.removeMatchingKeys(a,t.removedDocuments,n).next(()=>u.fs.addMatchingKeys(a,t.addedDocuments,n)));let e=r.withSequenceNumber(a.currentSequenceNumber);var i,s,o;l.targetMismatches.has(n)?e=e.withResumeToken(cx.EMPTY_BYTE_STRING,ZR.min()).withLastLimboFreeSnapshotVersion(ZR.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,o=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||c.push(u.fs.updateTargetData(a,e))}});let t=vD;if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(a,e))}),c.push(yM(a,e,l.documentUpdates).next(e=>{t=e})),!h.isEqual(ZR.min())){const l=u.fs.getLastRemoteSnapshotVersion(a).next(e=>u.fs.setTargetsMetadata(a,a.currentSequenceNumber,h));c.push(l)}return P1.waitFor(c).next(()=>e.apply(a)).next(()=>u.ci.Gs(a,t)).next(()=>t)}).then(e=>(u.ii=d,e))}function yM(e,s,t){let n=ID();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=vD;return t.forEach((e,t)=>{const n=r.get(e);t.isNoDocument()&&t.version.isEqual(ZR.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):RR("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),i})}function _M(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.fs.getTargetData(t,r).next(e=>e?(n=e,P1.resolve(n)):i.fs.allocateTargetId(t).next(e=>(n=new G1(r,e,0,t.currentSequenceNumber),i.fs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.ii.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.ii=i.ii.insert(e.targetId,e),i.ri.set(r,e.targetId)),e})}async function wM(e,t,n){const r=e,i=r.ii.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!F1(e))throw e;RR("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ii=r.ii.remove(t),r.ri.delete(i.target)}function bM(e,n,r){const i=e;let s=ZR.min(),o=ID();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.ri.get(n);return void 0!==i?P1.resolve(r.ii.get(i)):r.fs.getTargetData(t,n)}(i,t,EP(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.fs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>i.si.Qs(t,n,r?s:ZR.min(),r?o:ID())).next(e=>(EM(i,RP(n),e),{documents:e,li:o})))}function IM(e,t){const n=e,r=n.fs,i=n.ii.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.Et(e,t).next(e=>e?e.target:null))}function TM(e,t){const n=e,r=n.oi.get(t)||ZR.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.ui.getAllFromCollectionGroup(e,t,zx(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(EM(n,t,e),e))}function EM(e,t,n){let r=ZR.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.oi.set(t,r)}class SM{constructor(e){this.M=e,this.wi=new Map,this.mi=new Map}getBundleMetadata(e,t){return P1.resolve(this.wi.get(t))}saveBundleMetadata(e,t){return this.wi.set(t.id,{id:t.id,version:t.version,createTime:UD(t.createTime)}),P1.resolve()}getNamedQuery(e,t){return P1.resolve(this.mi.get(t))}saveNamedQuery(e,t){return this.mi.set(t.name,{name:(t=t).name,query:nO(t.bundledQuery),readTime:UD(t.readTime)}),P1.resolve()}}class kM{constructor(){this.overlays=new hD(wx.comparator),this.gi=new Map}getOverlay(e,t){return P1.resolve(this.overlays.get(t))}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.Xt(n,r,t)}),P1.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.gi.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.gi.delete(n)),P1.resolve()}getOverlaysForCollection(e,t,n){const r=_D(),i=t.length+1,s=new wx(t.child("")),o=this.overlays.getIteratorFrom(s);for(;o.hasNext();){const e=o.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return P1.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new hD((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=_D(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const o=_D(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach((e,t)=>o.set(e,t)),!(o.size()>=r)););return P1.resolve(o)}Xt(t,n,r){if(null!==r){var i=this.overlays.get(r.key);if(null!==i){const t=this.gi.get(i.largestBatchId).delete(r.key);this.gi.set(i.largestBatchId,t)}this.overlays=this.overlays.insert(r.key,new z1(n,r));let e=this.gi.get(n);void 0===e&&(e=ID(),this.gi.set(n,e)),this.gi.set(n,e.add(r.key))}}}class CM{constructor(){this.yi=new pD(AM.pi),this.Ii=new pD(AM.Ti)}isEmpty(){return this.yi.isEmpty()}addReference(e,t){var n=new AM(e,t);this.yi=this.yi.add(n),this.Ii=this.Ii.add(n)}Ei(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ai(new AM(e,t))}Ri(e,t){e.forEach(e=>this.removeReference(e,t))}Pi(e){const t=new wx(new ix([])),n=new AM(t,e),r=new AM(t,e+1),i=[];return this.Ii.forEachInRange([n,r],e=>{this.Ai(e),i.push(e.key)}),i}bi(){this.yi.forEach(e=>this.Ai(e))}Ai(e){this.yi=this.yi.delete(e),this.Ii=this.Ii.delete(e)}Vi(e){var t=new wx(new ix([])),n=new AM(t,e),t=new AM(t,e+1);let r=ID();return this.Ii.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new AM(e,0),t=this.yi.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class AM{constructor(e,t){this.key=e,this.vi=t}static pi(e,t){return wx.comparator(e.key,t.key)||QR(e.vi,t.vi)}static Ti(e,t){return QR(e.vi,t.vi)||wx.comparator(e.key,t.key)}}class NM{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.Bs=[],this.Si=1,this.Di=new pD(AM.pi)}checkEmpty(e){return P1.resolve(0===this.Bs.length)}addMutationBatch(e,t,n,r){var i=this.Si;this.Si++,0<this.Bs.length&&this.Bs[this.Bs.length-1];var s=new $1(i,t,n,r);this.Bs.push(s);for(const t of r)this.Di=this.Di.add(new AM(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return P1.resolve(s)}lookupMutationBatch(e,t){return P1.resolve(this.Ci(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.xi(t+1),n=n<0?0:n;return P1.resolve(this.Bs.length>n?this.Bs[n]:null)}getHighestUnacknowledgedBatchId(){return P1.resolve(0===this.Bs.length?-1:this.Si-1)}getAllMutationBatches(e){return P1.resolve(this.Bs.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new AM(t,0),r=new AM(t,Number.POSITIVE_INFINITY),i=[];return this.Di.forEachInRange([n,r],e=>{var t=this.Ci(e.vi);i.push(t)}),P1.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new pD(QR);return t.forEach(e=>{var t=new AM(e,0),n=new AM(e,Number.POSITIVE_INFINITY);this.Di.forEachInRange([t,n],e=>{r=r.add(e.vi)})}),P1.resolve(this.Ni(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;wx.isDocumentKey(i)||(i=i.child(""));var s=new AM(new wx(i),0);let o=new pD(QR);return this.Di.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.vi)),!0)},s),P1.resolve(this.Ni(o))}Ni(e){const n=[];return e.forEach(e=>{var t=this.Ci(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){MR(0===this.ki(r.batchId,"removed")),this.Bs.shift();let i=this.Di;return P1.forEach(r.mutations,e=>{var t=new AM(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Di=i})}_n(e){}containsKey(e,t){var n=new AM(t,0),n=this.Di.firstAfterOrEqual(n);return P1.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.Bs.length,P1.resolve()}ki(e,t){return this.xi(e)}xi(e){return 0===this.Bs.length?0:e-this.Bs[0].batchId}Ci(e){var t=this.xi(e);return t<0||t>=this.Bs.length?null:this.Bs[t]}}class RM{constructor(e){this.Mi=e,this.docs=new hD(wx.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Mi(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return P1.resolve(n?n.document.mutableCopy():jx.newInvalidDocument(t))}getEntries(e,t){let n=vD;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():jx.newInvalidDocument(e))}),P1.resolve(n)}getAllFromCollection(e,t,n){let r=vD;const i=new wx(t.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i}}=s.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||function(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=wx.comparator(e.documentKey,t.documentKey),0!==n?n:QR(e.largestBatchId,t.largestBatchId))}((o=i,new Gx(o.readTime,o.key,-1)),n)<=0||(r=r.insert(i.key,i.mutableCopy()))}var o;return P1.resolve(r)}getAllFromCollectionGroup(e,t,n,r){OR()}Oi(e,t){return P1.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new xM(this)}getSize(e){return P1.resolve(this.size)}}class xM extends QO{constructor(e){super(),this.Kn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Kn.addEntry(n,t)):this.Kn.removeEntry(e)}),P1.waitFor(r)}getFromCache(e,t){return this.Kn.getEntry(e,t)}getAllFromCache(e,t){return this.Kn.getEntries(e,t)}}class PM{constructor(e){this.persistence=e,this.Fi=new uD(e=>Yx(e),Jx),this.lastRemoteSnapshotVersion=ZR.min(),this.highestTargetId=0,this.$i=0,this.Bi=new CM,this.targetCount=0,this.Li=FO.gn()}forEachTarget(e,n){return this.Fi.forEach((e,t)=>n(t)),P1.resolve()}getLastRemoteSnapshotVersion(e){return P1.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return P1.resolve(this.$i)}allocateTargetId(e){return this.highestTargetId=this.Li.next(),P1.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.$i&&(this.$i=t),P1.resolve()}Tn(e){this.Fi.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Li=new FO(t),this.highestTargetId=t),e.sequenceNumber>this.$i&&(this.$i=e.sequenceNumber)}addTargetData(e,t){return this.Tn(t),this.targetCount+=1,P1.resolve()}updateTargetData(e,t){return this.Tn(t),P1.resolve()}removeTargetData(e,t){return this.Fi.delete(t.target),this.Bi.Pi(t.targetId),--this.targetCount,P1.resolve()}removeTargets(n,r,i){let s=0;const o=[];return this.Fi.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Fi.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),P1.waitFor(o).next(()=>s)}getTargetCount(e){return P1.resolve(this.targetCount)}getTargetData(e,t){var n=this.Fi.get(t)||null;return P1.resolve(n)}addMatchingKeys(e,t,n){return this.Bi.Ei(t,n),P1.resolve()}removeMatchingKeys(t,e,n){this.Bi.Ri(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),P1.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Bi.Pi(t),P1.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Bi.Vi(t);return P1.resolve(n)}containsKey(e,t){return P1.resolve(this.Bi.containsKey(t))}}class DM{constructor(e,t){this.Ui={},this.overlays={},this.es=new GR(0),this.ns=!1,this.ns=!0,this.referenceDelegate=e(this),this.fs=new PM(this),this.indexManager=new wO,this.ds=(e=e=>this.referenceDelegate.qi(e),new RM(e)),this.M=new H1(t),this._s=new SM(this.M)}start(){return Promise.resolve()}shutdown(){return this.ns=!1,Promise.resolve()}get started(){return this.ns}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new kM,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Ui[e.toKey()];return n||(n=new NM(t,this.referenceDelegate),this.Ui[e.toKey()]=n),n}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getBundleCache(){return this._s}runTransaction(e,t,n){RR("MemoryPersistence","Starting transaction:",e);const r=new OM(this.es.next());return this.referenceDelegate.Ki(),n(r).next(e=>this.referenceDelegate.Gi(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Qi(t,n){return P1.or(Object.values(this.Ui).map(e=>()=>e.containsKey(t,n)))}}class OM extends x1{constructor(e){super(),this.currentSequenceNumber=e}}class MM{constructor(e){this.persistence=e,this.ji=new CM,this.Wi=null}static zi(e){return new MM(e)}get Hi(){if(this.Wi)return this.Wi;throw OR()}addReference(e,t,n){return this.ji.addReference(n,t),this.Hi.delete(n.toString()),P1.resolve()}removeReference(e,t,n){return this.ji.removeReference(n,t),this.Hi.add(n.toString()),P1.resolve()}markPotentiallyOrphaned(e,t){return this.Hi.add(t.toString()),P1.resolve()}removeTarget(e,t){this.ji.Pi(t.targetId).forEach(e=>this.Hi.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Hi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ki(){this.Wi=new Set}Gi(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return P1.forEach(this.Hi,e=>{const t=wx.fromPath(e);return this.Ji(n,t).next(e=>{e||r.removeEntry(t,ZR.min())})}).next(()=>(this.Wi=null,r.apply(n)))}updateLimboDocument(e,t){return this.Ji(e,t).next(e=>{e?this.Hi.delete(t.toString()):this.Hi.add(t.toString())})}qi(e){return 0}Ji(e,t){return P1.or([()=>P1.resolve(this.ji.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Qi(e,t)])}}function LM(e,t){return`firestore_clients_${e}_${t}`}function FM(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function UM(e,t){return`firestore_targets_${e}_${t}`}class qM{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Yi(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new FR(r.error.code,r.error.message))),s?new qM(e,t,r.state,i):(xR("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Xi(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class jM{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Yi(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new FR(n.error.code,n.error.message))),i?new jM(e,n.state,r):(xR("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Xi(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class VM{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Yi(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=TD;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=_x(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new VM(e,i):(xR("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class BM{constructor(e,t){this.clientId=e,this.onlineState=t}static Yi(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new BM(t.clientId,t.onlineState):(xR("SharedClientState",`Failed to parse online state: ${e}`),null)}}class KM{constructor(){this.activeTargetIds=TD}Zi(e){this.activeTargetIds=this.activeTargetIds.add(e)}tr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Xi(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class $M{constructor(e,t,n,r,i){this.window=e,this.Yn=t,this.persistenceKey=n,this.er=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.nr=this.sr.bind(this),this.ir=new hD(QR),this.started=!1,this.rr=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.ur=LM(this.persistenceKey,this.er),this.ar=`firestore_sequence_number_${this.persistenceKey}`,this.ir=this.ir.insert(this.er,new KM),this.cr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.hr=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.lr=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.dr=`firestore_online_state_${this.persistenceKey}`,this._r=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.nr)}static vt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Fs();for(const n of e)if(n!==this.er){const e=this.getItem(LM(this.persistenceKey,n));var t;!e||(t=VM.Yi(n,e))&&(this.ir=this.ir.insert(t.clientId,t))}this.wr();const n=this.storage.getItem(this.dr);if(n){const e=this.mr(n);e&&this.gr(e)}for(const e of this.rr)this.sr(e);this.rr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.ar,JSON.stringify(e))}getAllActiveQueryTargets(){return this.yr(this.ir)}isActiveQueryTarget(n){let r=!1;return this.ir.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.pr(e,"pending")}updateMutationState(e,t,n){this.pr(e,t,n),this.Ir(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(UM(this.persistenceKey,e)))||(n=jM.Yi(e,n))&&(t=n.state)),this.Tr.Zi(e),this.wr(),t}removeLocalQueryTarget(e){this.Tr.tr(e),this.wr()}isLocalQueryTarget(e){return this.Tr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(UM(this.persistenceKey,e))}updateQueryState(e,t,n){this.Er(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Ir(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ar(e)}notifyBundleLoaded(e){this.Rr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.nr),this.removeItem(this.ur),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return RR("SharedClientState","READ",e,t),t}setItem(e,t){RR("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){RR("SharedClientState","REMOVE",e),this.storage.removeItem(e)}sr(e){const i=e;i.storageArea===this.storage&&(RR("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.ur?this.Yn.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.cr.test(i.key)){if(null==i.newValue){var e=this.Pr(i.key);return this.br(e,null)}e=this.Vr(i.key,i.newValue);if(e)return this.br(e.clientId,e)}else if(this.hr.test(i.key)){if(null!==i.newValue){var t=this.vr(i.key,i.newValue);if(t)return this.Sr(t)}}else if(this.lr.test(i.key)){if(null!==i.newValue){t=this.Dr(i.key,i.newValue);if(t)return this.Cr(t)}}else if(i.key===this.dr){if(null!==i.newValue){var n=this.mr(i.newValue);if(n)return this.gr(n)}}else if(i.key===this.ar){n=function(e){let t=GR.A;if(null!=e)try{var n=JSON.parse(e);MR("number"==typeof n),t=n}catch(e){xR("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==GR.A&&this.sequenceNumberHandler(n)}else if(i.key===this._r){const r=this.Nr(i.newValue);await Promise.all(r.map(e=>this.syncEngine.kr(e)))}}else this.rr.push(i)}):xR("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Tr(){return this.ir.get(this.er)}wr(){this.setItem(this.ur,this.Tr.Xi())}pr(e,t,n){const r=new qM(this.currentUser,e,t,n),i=FM(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Xi())}Ir(e){var t=FM(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ar(e){var t={clientId:this.er,onlineState:e};this.storage.setItem(this.dr,JSON.stringify(t))}Er(e,t,n){const r=UM(this.persistenceKey,e),i=new jM(e,t,n);this.setItem(r,i.Xi())}Rr(e){var t=JSON.stringify(Array.from(e));this.setItem(this._r,t)}Pr(e){var t=this.cr.exec(e);return t?t[1]:null}Vr(e,t){var n=this.Pr(e);return VM.Yi(n,t)}vr(e,t){var n=this.hr.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return qM.Yi(new kR(n),r,t)}Dr(e,t){var n=this.lr.exec(e),n=Number(n[1]);return jM.Yi(n,t)}mr(e){return BM.Yi(e)}Nr(e){return JSON.parse(e)}async Sr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Mr(e.batchId,e.state,e.error);RR("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Cr(e){return this.syncEngine.Or(e.targetId,e.state,e.error)}br(e,t){const n=t?this.ir.insert(e,t):this.ir.remove(e),r=this.yr(this.ir),i=this.yr(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.Fr(s,o).then(()=>{this.ir=n})}gr(e){this.ir.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}yr(e){let n=TD;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class WM{constructor(){this.$r=new KM,this.Br={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.$r.Zi(e),this.Br[e]||"not-current"}updateQueryState(e,t,n){this.Br[e]=t}removeLocalQueryTarget(e){this.$r.tr(e)}isLocalQueryTarget(e){return this.$r.activeTargetIds.has(e)}clearQueryState(e){delete this.Br[e]}getAllActiveQueryTargets(){return this.$r.activeTargetIds}isActiveQueryTarget(e){return this.$r.activeTargetIds.has(e)}start(){return this.$r=new KM,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class zM{Lr(e){}shutdown(){}}class GM{constructor(){this.Ur=()=>this.qr(),this.Kr=()=>this.Gr(),this.Qr=[],this.jr()}Lr(e){this.Qr.push(e)}shutdown(){window.removeEventListener("online",this.Ur),window.removeEventListener("offline",this.Kr)}jr(){window.addEventListener("online",this.Ur),window.addEventListener("offline",this.Kr)}qr(){RR("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Qr)e(0)}Gr(){RR("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Qr)e(1)}static vt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const HM={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class QM{constructor(e){this.Wr=e.Wr,this.zr=e.zr}Hr(e){this.Jr=e}Yr(e){this.Xr=e}onMessage(e){this.Zr=e}close(){this.zr()}send(e){this.Wr(e)}eo(){this.Jr()}no(e){this.Xr(e)}so(e){this.Zr(e)}}class YM extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.io=t+"://"+e.host,this.ro="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}oo(t,e,n,r,i){const s=this.uo(t,e);RR("RestConnection","Sending: ",s,n);var o={};return this.ao(o,r,i),this.co(t,s,o,n).then(e=>(RR("RestConnection","Received: ",e),e),e=>{throw PR("RestConnection",`${t} failed with error: `,e,"url: ",s,"request:",n),e})}ho(e,t,n,r,i){return this.oo(e,t,n,r,i)}ao(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+CR,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}uo(e,t){var n=HM[e];return`${this.io}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}co(a,t,n,r){return new Promise((i,s)=>{const o=new ER;o.listenOnce(yR.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case vR.NO_ERROR:var e=o.getResponseJson();RR("Connection","XHR received:",JSON.stringify(e)),i(e);break;case vR.TIMEOUT:RR("Connection",'RPC "'+a+'" timed out'),s(new FR(LR.DEADLINE_EXCEEDED,"Request time out"));break;case vR.HTTP_ERROR:var t,n=o.getStatus();if(RR("Connection",'RPC "'+a+'" failed with status:',n,"response text:",o.getResponseText()),0<n){const a=o.getResponseJson().error;a&&a.status&&a.message?(r=a.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(LR).indexOf(r)?r:LR.UNKNOWN,s(new FR(t,a.message))):s(new FR(LR.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new FR(LR.UNAVAILABLE,"Connection failed."));break;default:OR()}}finally{RR("Connection",'RPC "'+a+'" completed.')}var r});var e=JSON.stringify(r);o.send(t,"POST",e,n,15)})}lo(e,t,n){const r=[this.io,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=new uR,s=mR(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(o.xmlHttpFactory=new IR({})),this.ao(o.initMessageHeaders,t,n),od()||ld()||0<=sd().indexOf("Electron/")||ud()||0<=sd().indexOf("MSAppHost/")||cd()||(o.httpHeadersOverwriteParam="$httpHeaders");var a=r.join("");RR("Connection","Creating WebChannel: "+a,o);const c=i.createWebChannel(a,o);let l=!1,u=!1;const h=new QM({Wr:e=>{u?RR("Connection","Not sending because WebChannel is closed:",e):(l||(RR("Connection","Opening WebChannel transport."),c.open(),l=!0),RR("Connection","WebChannel sending:",e),c.send(e))},zr:()=>c.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(c,TR.EventType.OPEN,()=>{u||RR("Connection","WebChannel transport opened.")}),d(c,TR.EventType.CLOSE,()=>{u||(u=!0,RR("Connection","WebChannel transport closed"),h.no())}),d(c,TR.EventType.ERROR,e=>{u||(u=!0,PR("Connection","WebChannel transport errored:",e),h.no(new FR(LR.UNAVAILABLE,"The operation could not be completed")))}),d(c,TR.EventType.MESSAGE,n=>{if(!u){var e=n.data[0];MR(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){RR("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=gR[e];if(void 0!==t)return lD(t)}(n),t=r.message;void 0===e&&(e=LR.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),u=!0,h.no(new FR(e,t)),c.close()}else RR("Connection","WebChannel received:",e),h.so(e)}}),d(s,_R.STAT_EVENT,e=>{e.stat===wR?RR("Connection","Detected buffering proxy"):e.stat===bR&&RR("Connection","Detected no buffering proxy")}),setTimeout(()=>{h.eo()},0),h}}function JM(){return"undefined"!=typeof window?window:null}function XM(){return"undefined"!=typeof document?document:null}function ZM(e){return new MD(e,!0)}class eL{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Yn=e,this.timerId=t,this.fo=n,this._o=r,this.wo=i,this.mo=0,this.yo=null,this.po=Date.now(),this.reset()}reset(){this.mo=0}Io(){this.mo=this.wo}To(e){this.cancel();var t=Math.floor(this.mo+this.Eo()),n=Math.max(0,Date.now()-this.po),r=Math.max(0,t-n);0<r&&RR("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.mo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.yo=this.Yn.enqueueAfterDelay(this.timerId,r,()=>(this.po=Date.now(),e())),this.mo*=this._o,this.mo<this.fo&&(this.mo=this.fo),this.mo>this.wo&&(this.mo=this.wo)}Ao(){null!==this.yo&&(this.yo.skipDelay(),this.yo=null)}cancel(){null!==this.yo&&(this.yo.cancel(),this.yo=null)}Eo(){return(Math.random()-.5)*this.mo}}class tL{constructor(e,t,n,r,i,s,o,a){this.Yn=e,this.Ro=n,this.Po=r,this.bo=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Vo=0,this.vo=null,this.So=null,this.stream=null,this.Do=new eL(e,t)}Co(){return 1===this.state||5===this.state||this.xo()}xo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.No()}async stop(){this.Co()&&await this.close(0)}ko(){this.state=0,this.Do.reset()}Mo(){this.xo()&&null===this.vo&&(this.vo=this.Yn.enqueueAfterDelay(this.Ro,6e4,()=>this.Oo()))}Fo(e){this.$o(),this.stream.send(e)}async Oo(){if(this.xo())return this.close(0)}$o(){this.vo&&(this.vo.cancel(),this.vo=null)}Bo(){this.So&&(this.So.cancel(),this.So=null)}async close(e,t){this.$o(),this.Bo(),this.Do.cancel(),this.Vo++,4!==e?this.Do.reset():t&&t.code===LR.RESOURCE_EXHAUSTED?(xR(t.toString()),xR("Using maximum backoff delay to prevent overloading the backend."),this.Do.Io()):t&&t.code===LR.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Lo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Yr(t)}Lo(){}auth(){this.state=1;const e=this.Uo(this.Vo),n=this.Vo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Vo===n&&this.qo(e,t)},t=>{e(()=>{var e=new FR(LR.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ko(e)})})}qo(e,t){const n=this.Uo(this.Vo);this.stream=this.Go(e,t),this.stream.Hr(()=>{n(()=>(this.state=2,this.So=this.Yn.enqueueAfterDelay(this.Po,1e4,()=>(this.xo()&&(this.state=3),Promise.resolve())),this.listener.Hr()))}),this.stream.Yr(e=>{n(()=>this.Ko(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}No(){this.state=5,this.Do.To(async()=>{this.state=0,this.start()})}Ko(e){return RR("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Uo(t){return e=>{this.Yn.enqueueAndForget(()=>this.Vo===t?e():(RR("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class nL extends tL{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.M=i}Go(e,t){return this.bo.lo("Listen",e,t)}onMessage(e){this.Do.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:OR(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.N?(MR(void 0===f||"string"==typeof f),cx.fromBase64String(f||"")):(MR(void 0===f||f instanceof Uint8Array),cx.fromUint8Array(f||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(f=o).code?LR.UNKNOWN:lD(f.code),new FR(a,f.message||""));n=new AD(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var a=BD(e,c.document.name),l=UD(c.document.updateTime),u=new qx({mapValue:{fields:c.document.fields}}),l=jx.newFoundDocument(a,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new kD(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=BD(e,u.document),l=u.readTime?UD(u.readTime):ZR.min(),l=jx.newNoDocument(c,l),u=u.removedTargetIds||[];n=new kD([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=BD(e,h.document),h=h.removedTargetIds||[];n=new kD([],h,d,null)}else{if(!("filter"in t))return OR();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new aD(h),h=e.targetId;n=new CD(h,d)}}var a,f;return n}(this.M,e),n=function(e){if(!("targetChange"in e))return ZR.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?UD(t.readTime):ZR.min()}(e);return this.listener.Qo(t,n)}jo(e){const t={};t.database=WD(this.M),t.addTarget=function(e,t){let n;var r=t.target;return n=Xx(r)?{documents:JD(e,r)}:{query:XD(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=FD(e,t.resumeToken):0<t.snapshotVersion.compareTo(ZR.min())&&(n.readTime=LD(e,t.snapshotVersion.toTimestamp())),n}(this.M,e);var n,r,r=(this.M,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return OR()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Fo(t)}Wo(e){const t={};t.database=WD(this.M),t.removeTarget=e,this.Fo(t)}}class rL extends tL{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.M=i,this.zo=!1}get Ho(){return this.zo}start(){this.zo=!1,this.lastStreamToken=void 0,super.start()}Lo(){this.zo&&this.Jo([])}Go(e,t){return this.bo.lo("Write",e,t)}onMessage(e){if(MR(!!e.streamToken),this.lastStreamToken=e.streamToken,this.zo){this.Do.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(MR(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?UD(e.updateTime):UD(t);return n.isEqual(ZR.min())&&(n=UD(t)),new zP(n,e.transformResults||[])}(e,i))):[]),n=UD(e.commitTime);return this.listener.Yo(n,t)}var r,i;return MR(!e.writeResults||0===e.writeResults.length),this.zo=!0,this.listener.Xo()}Zo(){const e={};e.database=WD(this.M),this.Fo(e)}Jo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>QD(this.M,e))};this.Fo(t)}}class iL extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.bo=n,this.M=r,this.tu=!1}eu(){if(this.tu)throw new FR(LR.FAILED_PRECONDITION,"The client has already been terminated.")}oo(n,r,i){return this.eu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.bo.oo(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===LR.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FR(LR.UNKNOWN,e.toString())})}ho(n,r,i){return this.eu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.bo.ho(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===LR.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FR(LR.UNKNOWN,e.toString())})}terminate(){this.tu=!0}}class sL{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.nu=0,this.su=null,this.iu=!0}ru(){0===this.nu&&(this.ou("Unknown"),this.su=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.su=null,this.uu("Backend didn't respond within 10 seconds."),this.ou("Offline"),Promise.resolve())))}au(e){"Online"===this.state?this.ou("Unknown"):(this.nu++,1<=this.nu&&(this.cu(),this.uu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ou("Offline")))}set(e){this.cu(),this.nu=0,"Online"===e&&(this.iu=!1),this.ou(e)}ou(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}uu(e){var t=`Could not reach Cloud Firestore backend. ${e}\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.iu?(xR(t),this.iu=!1):RR("OnlineStateTracker",t)}cu(){null!==this.su&&(this.su.cancel(),this.su=null)}}class oL{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.hu=[],this.lu=new Map,this.fu=new Set,this.du=[],this._u=i,this._u.Lr(e=>{n.enqueueAndForget(async()=>{gL(this)&&(RR("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.fu.add(4),await cL(t),t.wu.set("Unknown"),t.fu.delete(4),await aL(t)}(this))})}),this.wu=new sL(n,r)}}async function aL(e){if(gL(e))for(const t of e.du)await t(!0)}async function cL(e){for(const t of e.du)await t(!1)}function lL(e,t){const n=e;n.lu.has(t.targetId)||(n.lu.set(t.targetId,t),pL(n)?fL(n):EL(n).xo()&&hL(n,t))}function uL(e,t){const n=e,r=EL(n);n.lu.delete(t),r.xo()&&dL(n,t),0===n.lu.size&&(r.xo()?r.Mo():gL(n)&&n.wu.set("Unknown"))}function hL(e,t){e.mu.Z(t.targetId),EL(e).jo(t)}function dL(e,t){e.mu.Z(t),EL(e).Wo(t)}function fL(t){t.mu=new RD({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t.lu.get(e)||null}),EL(t).start(),t.wu.ru()}function pL(e){return gL(e)&&!EL(e).Co()&&0<e.lu.size}function gL(e){return 0===e.fu.size}function mL(e){e.mu=void 0}async function vL(e,t,n){if(!F1(t))throw t;e.fu.add(1),await cL(e),e.wu.set("Offline"),n=n||(()=>mM(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{RR("RemoteStore","Retrying IndexedDB access"),await n(),e.fu.delete(1),await aL(e)})}function yL(t,n){return n().catch(e=>vL(t,e,n))}async function _L(e){const t=e,n=SL(t);let r=0<t.hu.length?t.hu[t.hu.length-1].batchId:-1;for(;gL(i=t)&&i.hu.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.Bs.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.hu.length&&n.Mo();break}r=e.batchId,function(e,t){e.hu.push(t);const n=SL(e);n.xo()&&n.Ho&&n.Jo(t.mutations)}(t,e)}catch(e){await vL(t,e)}var i;wL(t)&&bL(t)}function wL(e){return gL(e)&&!SL(e).Co()&&0<e.hu.length}function bL(e){SL(e).start()}async function IL(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),RR("RemoteStore","RemoteStore received new credentials");var r=gL(n);n.fu.add(3),await cL(n),r&&n.wu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.fu.delete(3),await aL(n)}async function TL(e,t){const n=e;t?(n.fu.delete(2),await aL(n)):(n.fu.add(2),await cL(n),n.wu.set("Unknown"))}function EL(t){return t.gu||(t.gu=function(e,t,n){const r=e;return r.eu(),new nL(t,r.bo,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Hr:(async function(n){n.lu.forEach((e,t)=>{hL(n,e)})}).bind(null,t),Yr:(async function(e,t){mL(e),pL(e)?(e.wu.au(t),fL(e)):e.wu.set("Unknown")}).bind(null,t),Qo:(async function(e,r,t){if(e.wu.set("Online"),r instanceof AD&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.lu.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.lu.delete(n),e.mu.removeTarget(n))}(e)}catch(t){RR("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await vL(e,t)}else if(r instanceof kD?e.mu.ut(r):r instanceof CD?e.mu._t(r):e.mu.ht(r),!t.isEqual(ZR.min()))try{const r=await mM(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.mu.yt(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.lu.get(t);n&&r.lu.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r.lu.get(e);var n;t&&(r.lu.set(e,t.withResumeToken(cx.EMPTY_BYTE_STRING,t.snapshotVersion)),dL(r,e),n=new G1(t.target,e,1,t.sequenceNumber),hL(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){RR("RemoteStore","Failed to raise snapshot:",r),await vL(e,r)}}).bind(null,t)}),t.du.push(async e=>{e?(t.gu.ko(),pL(t)?fL(t):t.wu.set("Unknown")):(await t.gu.stop(),mL(t))})),t.gu}function SL(t){return t.yu||(t.yu=function(e,t,n){const r=e;return r.eu(),new rL(t,r.bo,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Hr:(async function(e){SL(e).Zo()}).bind(null,t),Yr:(async function(e,t){t&&SL(e).Ho&&await async function(e,t){if(cD(n=t.code)&&n!==LR.ABORTED){const n=e.hu.shift();SL(e).ko(),await yL(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await _L(e)}var n}(e,t),wL(e)&&bL(e)}).bind(null,t),Xo:(async function(e){const t=SL(e);for(const n of e.hu)t.Jo(n.mutations)}).bind(null,t),Yo:(async function(e,t,n){const r=e.hu.shift(),i=W1.from(r,t,n);await yL(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await _L(e)}).bind(null,t)}),t.du.push(async e=>{e?(t.yu.ko(),await _L(t)):(await t.yu.stop(),0<t.hu.length&&(RR("RemoteStore",`Stopping write stream with ${t.hu.length} pending writes`),t.hu=[]))})),t.yu}class kL{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new UR,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new kL(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FR(LR.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function CL(e,t){if(xR("AsyncQueue",`${t}: ${e}`),F1(e))return new FR(LR.UNAVAILABLE,`${t}: ${e}`);throw e}class AL{constructor(n){this.comparator=n?(e,t)=>n(e,t)||wx.comparator(e.key,t.key):(e,t)=>wx.comparator(e.key,t.key),this.keyedMap=yD,this.sortedSet=new hD(this.comparator)}static emptySet(e){return new AL(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof AL))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new AL;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class NL{constructor(){this.pu=new hD(wx.comparator)}track(e){var t=e.doc.key,n=this.pu.get(t);!n||0!==e.type&&3===n.type?this.pu=this.pu.insert(t,e):3===e.type&&1!==n.type?this.pu=this.pu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.pu=this.pu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.pu=this.pu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.pu=this.pu.remove(t):1===e.type&&2===n.type?this.pu=this.pu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.pu=this.pu.insert(t,{type:2,doc:e.doc}):OR()}Iu(){const n=[];return this.pu.inorderTraversal((e,t)=>{n.push(t)}),n}}class RL{constructor(e,t,n,r,i,s,o,a){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(e,t,n,r){const i=[];return t.forEach(e=>{i.push({type:0,doc:e})}),new RL(e,t,AL.emptySet(t),i,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&kP(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class xL{constructor(){this.Tu=void 0,this.listeners=[]}}class PL{constructor(){this.queries=new uD(e=>CP(e),kP),this.onlineState="Unknown",this.Eu=new Set}}async function DL(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new xL),i)try{s.Tu=await n.onListen(r)}catch(e){const n=CL(e,`Initialization of query '${AP(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Au(n.onlineState),!s.Tu||t.Ru(s.Tu)&&ML(n)}async function OL(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function ML(e){e.Eu.forEach(e=>{e.next()})}class LL{constructor(e,t,n){this.query=e,this.Pu=t,this.bu=!1,this.Vu=null,this.onlineState="Unknown",this.options=n||{}}Ru(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new RL(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.bu?this.vu(e)&&(this.Pu.next(e),t=!0):this.Su(e,this.onlineState)&&(this.Du(e),t=!0),this.Vu=e,t}onError(e){this.Pu.error(e)}Au(e){this.onlineState=e;let t=!1;return this.Vu&&!this.bu&&this.Su(this.Vu,e)&&(this.Du(this.Vu),t=!0),t}Su(e,t){return!e.fromCache||!(this.options.Cu&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}vu(e){if(0<e.docChanges.length)return!0;var t=this.Vu&&this.Vu.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Du(e){e=RL.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.bu=!0,this.Pu.next(e)}}class FL{constructor(e,t){this.payload=e,this.byteLength=t}xu(){return"metadata"in this.payload}}class UL{constructor(e){this.M=e}fi(e){return BD(this.M,e)}di(e){return e.metadata.exists?HD(this.M,e.document,!1):jx.newNoDocument(this.fi(e.metadata.name),this._i(e.metadata.readTime))}_i(e){return UD(e)}}class qL{constructor(e,t,n){this.Nu=e,this.localStore=t,this.M=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=jL(e)}ku(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.payload.namedQuery)this.queries.push(e.payload.namedQuery);else if(e.payload.documentMetadata){this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t;const n=ix.fromString(e.payload.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Mu(e){const t=new Map,n=new UL(this.M);for(const i of e)if(i.metadata.queries){const e=n.fi(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||ID()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=ID(),o=vD;for(const e of n){const n=t.fi(e.metadata.name);e.document&&(s=s.add(n));const l=t.di(e);l.setReadTime(t._i(e.metadata.readTime)),o=o.insert(n,l)}const a=i.ui.newChangeBuffer({trackRemovals:!0}),c=await _M(i,(r=r,EP(vP(ix.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>yM(t,a,o).next(e=>(a.apply(t),e)).next(e=>i.fs.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.fs.addMatchingKeys(t,s,c.targetId)).next(()=>i.ci.Gs(t,e)).next(()=>e)))}(this.localStore,new UL(this.M),this.documents,this.Nu.id),t=this.Mu(this.documents);for(const e of this.queries)await async function(e,n,r=ID()){const i=await _M(e,EP(nO(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=UD(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s._s.saveNamedQuery(e,n);t=i.withResumeToken(cx.EMPTY_BYTE_STRING,t);return s.ii=s.ii.insert(t.targetId,t),s.fs.updateTargetData(e,t).next(()=>s.fs.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.fs.addMatchingKeys(e,r,i.targetId)).next(()=>s._s.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Ou:this.collectionGroups,Fu:e}}}function jL(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class VL{constructor(e){this.key=e}}class BL{constructor(e){this.key=e}}class KL{constructor(e,t){this.query=e,this.$u=t,this.Bu=null,this.current=!1,this.Lu=ID(),this.mutatedKeys=ID(),this.Uu=xP(e),this.qu=new AL(this.Uu)}get Ku(){return this.$u}Gu(e,t){const a=t?t.Qu:new NL,c=(t||this).qu;let l=(t||this).mutatedKeys,u=c,h=!1;const d=yP(this.query)&&c.size===this.query.limit?c.last():null,f=_P(this.query)&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=NP(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let o=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(a.track({type:3,doc:r}),o=!0):this.ju(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.Uu(r,d)||f&&this.Uu(r,f)<0)&&(h=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||f)&&(h=!0)),o&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),yP(this.query)||_P(this.query))for(;u.size>this.query.limit;){const e=yP(this.query)?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),a.track({type:1,doc:e})}return{qu:u,Qu:a,ni:h,mutatedKeys:l}}ju(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.qu;this.qu=e.qu,this.mutatedKeys=e.mutatedKeys;const i=e.Qu.Iu();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return OR()}};return n(e)-n(t)}(e.type,t.type)||this.Uu(e.doc,t.doc)),this.Wu(n);var s=t?this.zu():[],o=0===this.Lu.size&&this.current?1:0,a=o!==this.Bu;return this.Bu=o,0!==i.length||a?{snapshot:new RL(this.query,e.qu,r,i,e.mutatedKeys,0==o,a,!1),Hu:s}:{Hu:s}}Au(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({qu:this.qu,Qu:new NL,mutatedKeys:this.mutatedKeys,ni:!1},!1)):{Hu:[]}}Ju(e){return!this.$u.has(e)&&!!this.qu.has(e)&&!this.qu.get(e).hasLocalMutations}Wu(e){e&&(e.addedDocuments.forEach(e=>this.$u=this.$u.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.$u=this.$u.delete(e)),this.current=e.current)}zu(){if(!this.current)return[];const t=this.Lu;this.Lu=ID(),this.qu.forEach(e=>{this.Ju(e.key)&&(this.Lu=this.Lu.add(e.key))});const n=[];return t.forEach(e=>{this.Lu.has(e)||n.push(new BL(e))}),this.Lu.forEach(e=>{t.has(e)||n.push(new VL(e))}),n}Yu(e){this.$u=e.li,this.Lu=ID();var t=this.Gu(e.documents);return this.applyChanges(t,!0)}Xu(){return RL.fromInitialDocuments(this.query,this.qu,this.mutatedKeys,0===this.Bu)}}class $L{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class WL{constructor(e){this.key=e,this.Zu=!1}}class zL{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.ta={},this.ea=new uD(e=>CP(e),kP),this.na=new Map,this.sa=new Set,this.ia=new hD(wx.comparator),this.ra=new Map,this.oa=new CM,this.ua={},this.aa=new Map,this.ca=FO.yn(),this.onlineState="Unknown",this.ha=void 0}get isPrimaryClient(){return!0===this.ha}}async function GL(n,e,t,r){n.la=(e,s,t)=>async function(e,t,n){let r=t.view.Gu(s);r.ni&&(r=await bM(e.localStore,t.query,!1).then(({documents:e})=>t.view.Gu(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return nF(e,t.targetId,i.Hu),i.snapshot}(n,e,t);const i=await bM(n.localStore,e,!0),s=new KL(e,i.li),o=s.Gu(i.documents),a=SD.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),c=s.applyChanges(o,n.isPrimaryClient,a);nF(n,t,c.Hu);var l=new $L(e,t,s);return n.ea.set(e,l),n.na.has(t)?n.na.get(t).push(e):n.na.set(t,[e]),c.snapshot}async function HL(e,t,n){const r=lF(e);try{const e=await function(e,r){const i=e,s=XR.now(),t=r.reduce((e,t)=>e.add(t.key),ID());let o;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>i.ci.Ks(n,t).next(e=>{o=e;const t=[];for(const n of r){const r=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=LP(r.transform,e||null);null!=i&&(null==n&&(n=qx.empty()),n.set(r.field,i))}return n||null}(n,o.get(n.key));null!=r&&t.push(new tD(n.key,r,function r(e){const i=[];return tx(e.fields,(e,t)=>{const n=new ox([e]);if(Ox(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new ax(i)}(r.value.mapValue),GP.exists(!0)))}return i.Bs.addMutationBatch(n,s,t,r)})).then(e=>(e.applyToLocalDocumentSet(o),{batchId:e.batchId,changes:o}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.ua[e.currentUser.toKey()];r=r||new hD(QR),r=r.insert(t,n),e.ua[e.currentUser.toKey()]=r}(r,e.batchId,n),await iF(r,e.changes),await _L(r.remoteStore)}catch(e){const t=CL(e,"Failed to persist write");n.reject(t)}}async function QL(e,t){const r=e;try{const e=await vM(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.ra.get(t);n&&(MR(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.Zu=!0:0<e.modifiedDocuments.size?MR(n.Zu):0<e.removedDocuments.size&&(MR(n.Zu),n.Zu=!1))}),await iF(r,e,t)}catch(e){await BO(e)}}function YL(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ea.forEach((e,t)=>{var n=t.view.Au(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.Au(n)&&(r=!0)}),r&&ML(t)}(t.eventManager,i),r.length&&t.ta.Qo(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function JL(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.ui.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let o=P1.resolve();return n.forEach(n=>{o=o.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);MR(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),o.next(()=>e.Bs.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.Bs.performConsistencyCheck(e)).next(()=>i.ci.Ks(e,t))})}(n.localStore,t);ZL(n,r,null),XL(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await iF(n,e)}catch(e){await BO(e)}}function XL(e,t){(e.aa.get(t)||[]).forEach(e=>{e.resolve()}),e.aa.delete(t)}function ZL(e,t,n){const r=e;let i=r.ua[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.ua[r.currentUser.toKey()]=i}}function eF(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.na.get(e))t.ea.delete(r),n&&t.ta.fa(r,n);t.na.delete(e),t.isPrimaryClient&&t.oa.Pi(e).forEach(e=>{t.oa.containsKey(e)||tF(t,e)})}function tF(e,t){e.sa.delete(t.path.canonicalString());var n=e.ia.get(t);null!==n&&(uL(e.remoteStore,n),e.ia=e.ia.remove(t),e.ra.delete(n),rF(e))}function nF(e,t,n){for(const r of n)r instanceof VL?(e.oa.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.ia.get(n)||e.sa.has(r)||(RR("SyncEngine","New document in limbo: "+n),e.sa.add(r),rF(e))}(e,r)):r instanceof BL?(RR("SyncEngine","Document no longer in limbo: "+r.key),e.oa.removeReference(r.key,t),e.oa.containsKey(r.key)||tF(e,r.key)):OR()}function rF(e){for(;0<e.sa.size&&e.ia.size<e.maxConcurrentLimboResolutions;){var t=e.sa.values().next().value;e.sa.delete(t);var n=new wx(ix.fromString(t)),t=e.ca.next();e.ra.set(t,new WL(n)),e.ia=e.ia.insert(n,t),lL(e.remoteStore,new G1(EP(vP(n.path)),t,2,GR.A))}}async function iF(e,t,r){const i=e,s=[],o=[],a=[];i.ea.isEmpty()||(i.ea.forEach((e,n)=>{a.push(i.la(n,t,r).then(e=>{var t;e&&(i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),s.push(e),t=hM.Ys(n.targetId,e),o.push(t))}))}),await Promise.all(a),i.ta.Qo(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>P1.forEach(t,t=>P1.forEach(t.Hs,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>P1.forEach(t.Js,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!F1(e))throw e;RR("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ii.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.ii=r.ii.insert(t,i)}}}(i.localStore,o))}async function sF(r,e){const i=r;if(cF(i),lF(i),!0===e&&!0!==i.ha){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await oF(i,r.toArray());i.ha=!0,await TL(i.remoteStore,!0);for(const r of e)lL(i.remoteStore,r)}else if(!1===e&&!1!==i.ha){const r=[];let n=Promise.resolve();i.na.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(eF(i,t),wM(i.localStore,t,!0))),uL(i.remoteStore,t)}),await n,await oF(i,r),function(){const n=i;n.ra.forEach((e,t)=>{uL(n.remoteStore,t)}),n.oa.bi(),n.ra=new Map,n.ia=new hD(wx.comparator)}(),i.ha=!1,await TL(i.remoteStore,!1)}}async function oF(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.na.get(t);if(u&&0!==u.length){e=await _M(r.localStore,EP(u[0]));for(const t of u){const n=r.ea.get(t),u=(o=r,a=n,l=c=void 0,l=await bM((c=o).localStore,a.query,!0),l=a.view.Yu(l),c.isPrimaryClient&&nF(c,a.targetId,l.Hu),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await IM(r.localStore,t);e=await _M(r.localStore,u),await GL(r,aF(u),t,!1)}i.push(e)}var o,a,c,l;return r.ta.Qo(s),i}function aF(e){return mP(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function cF(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=QL.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.ra.get(t);if(r&&r.Zu)return ID().add(r.key);{let e=ID();const r=n.na.get(t);if(!r)return e;for(const t of r){const r=n.ea.get(t);e=e.unionWith(r.view.Ku)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.ra.get(t),s=i&&i.key;if(s){let e=new hD(wx.comparator);e=e.insert(s,jx.newNoDocument(s,ZR.min()));const n=ID().add(s),i=new ED(ZR.min(),new Map,new pD(QR),e,n);await QL(r,i),r.ia=r.ia.remove(s),r.ra.delete(t),rF(r)}else await wM(r.localStore,t,!1).then(()=>eF(r,t,n)).catch(BO)}).bind(null,t),t.ta.Qo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.Ru(e)&&(r=!0);i.Tu=e}}r&&ML(n)}).bind(null,t.eventManager),t.ta.fa=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function lF(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=JL.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.Bs.lookupMutationBatch(t,r).next(e=>(MR(null!==e),n=e.keys(),i.Bs.removeMutationBatch(t,e))).next(()=>i.Bs.performConsistencyCheck(t)).next(()=>i.ci.Ks(t,n))})}(r.localStore,t);ZL(r,t,n),XL(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await iF(r,e)}catch(n){await BO(n)}}).bind(null,t),t}class uF{constructor(){this.synchronizeTabs=!1}async initialize(e){this.M=ZM(e.databaseInfo.databaseId),this.sharedClientState=this._a(e),this.persistence=this.wa(e),await this.persistence.start(),this.gcScheduler=this.ma(e),this.localStore=this.ga(e)}ma(e){return null}ga(e){return pM(this.persistence,new dM,e.initialUser,this.M)}wa(e){return new DM(MM.zi,this.M)}_a(e){return new WM}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class hF extends uF{constructor(e,t,n){super(),this.ya=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.ya.initialize(this,e),await lF(this.ya.syncEngine),await _L(this.ya.remoteStore),await this.persistence.Ts(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}ga(e){return pM(this.persistence,new dM,e.initialUser,this.M)}ma(e){var t=this.persistence.referenceDelegate.garbageCollector;return new WO(t,e.asyncQueue)}wa(e){var t=lM(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?NO.withCacheSize(this.cacheSizeBytes):NO.DEFAULT;return new oM(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,JM(),XM(),this.M,this.sharedClientState,!!this.forceOwnership)}_a(e){return new WM}}class dF extends hF{constructor(e,t){super(e,t,!1),this.ya=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.ya.syncEngine;this.sharedClientState instanceof $M&&(this.sharedClientState.syncEngine={Mr:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.Bs;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.fn(t,n).next(e=>e?r.ci.Ks(t,e):P1.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await _L(i.remoteStore):"acknowledged"===n||"rejected"===n?(ZL(i,t,r||null),XL(i,t),i.localStore.Bs._n(t)):OR(),await iF(i,s)):RR("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Or:(async function(e,t,n,r){const i=e;if(i.ha)RR("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.na.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await TM(i.localStore,RP(s[0])),r=ED.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await iF(i,e,r);break}case"rejected":await wM(i.localStore,t,!0),eF(i,t,r);break;default:OR()}}}).bind(null,t),Fr:(async function(e,t,n){const r=cF(e);if(r.ha){for(const e of t)if(r.na.has(e))RR("SyncEngine","Adding an already active target "+e);else{const t=await IM(r.localStore,e),n=await _M(r.localStore,t);await GL(r,aF(t),n.targetId,!1),lL(r.remoteStore,n)}for(const e of n)r.na.has(e)&&await wM(r.localStore,e,!1).then(()=>{uL(r.remoteStore,e),eF(r,e)}).catch(BO)}}).bind(null,t),Fs:(function(e){return e.localStore.persistence.Fs()}).bind(null,t),kr:(async function(e,t){const n=e;return TM(n.localStore,t).then(e=>iF(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ts(async e=>{await sF(this.ya.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}_a(e){var t=JM();if(!$M.vt(t))throw new FR(LR.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=lM(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new $M(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class fF{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>YL(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){RR("SyncEngine","User change. New user:",t.toKey());const r=await gM(n.localStore,t);n.currentUser=t,(e=n).aa.forEach(e=>{e.forEach(e=>{e.reject(new FR(LR.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.aa.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await iF(n,r.hi)}}).bind(null,this.syncEngine),await TL(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new PL}createDatastore(e){var t,n,r,i,s=ZM(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new YM(t));return n=e.authCredentials,r=e.appCheckCredentials,i=t,e=s,new iL(n,r,i,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>YL(this.syncEngine,e,0),s=new(GM.vt()?GM:zM),new oL(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new zL(e,t,n,r,i,s);return o&&(a.ha=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;RR("RemoteStore","RemoteStore shutting down."),t.fu.add(5),await cL(t),t._u.shutdown(),t.wu.set("Unknown")}(this.remoteStore)}}function pF(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class gF{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.pa(this.observer.next,e)}error(e){this.observer.error?this.pa(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}Ia(){this.muted=!0}pa(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class mF{constructor(e,t){this.Ta=e,this.M=t,this.metadata=new UR,this.buffer=new Uint8Array,this.Ea=new TextDecoder("utf-8"),this.Aa().then(e=>{e&&e.xu()?this.metadata.resolve(e.payload.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.payload)}`))},e=>this.metadata.reject(e))}close(){return this.Ta.cancel()}async getMetadata(){return this.metadata.promise}async da(){return await this.getMetadata(),this.Aa()}async Aa(){var e=await this.Ra();if(null===e)return null;var t=this.Ea.decode(e),n=Number(t);isNaN(n)&&this.Pa(`length string (${t}) is not valid number`);t=await this.ba(n);return new FL(JSON.parse(t),e.length+n)}Va(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ra(){for(;this.Va()<0&&!await this.va(););if(0===this.buffer.length)return null;var e=this.Va();e<0&&this.Pa("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async ba(e){for(;this.buffer.length<e;)await this.va()&&this.Pa("Reached the end of bundle when more is expected.");var t=this.Ea.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Pa(e){throw this.Ta.cancel(),new Error(`Invalid bundle format: ${e}`)}async va(){var e=await this.Ta.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class vF{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new FR(LR.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=WD(r.M)+"/documents",i={documents:t.map(e=>VD(r.M,e))},s=await r.ho("BatchGetDocuments",n,i),o=new Map;s.forEach(e=>{const t=(n=r.M,"found"in(e=e)?function(e,t){MR(!!t.found),t.found.name,t.found.updateTime;var n=BD(e,t.found.name),r=UD(t.found.updateTime),i=new qx({mapValue:{fields:t.found.fields}});return jx.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){MR(!!t.missing),MR(!!t.readTime);var n=BD(e,t.missing),r=UD(t.readTime);return jx.newNoDocument(n,r)}(n,e):OR());var n;o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=o.get(e.toString());MR(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new sD(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=wx.fromPath(t);this.mutations.push(new oD(n,this.precondition(n)))}),await async function(e,t){const n=e,r=WD(n.M)+"/documents",i={writes:t.map(e=>QD(n.M,e))};await n.oo("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw OR();t=ZR.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new FR(LR.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?GP.updateTime(t):GP.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return GP.exists(!0);if(t.isEqual(ZR.min()))throw new FR(LR.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return GP.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class yF{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.Sa=5,this.Do=new eL(this.asyncQueue,"transaction_retry")}run(){--this.Sa,this.Da()}Da(){this.Do.To(async()=>{const t=new vF(this.datastore),e=this.Ca(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.xa(e)}))}).catch(e=>{this.xa(e)})})}Ca(e){try{var t=this.updateFunction(e);return!vx(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}xa(e){0<this.Sa&&this.Na(e)?(--this.Sa,this.asyncQueue.enqueueAndForget(()=>(this.Da(),Promise.resolve()))):this.deferred.reject(e)}Na(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!cD(t)}}class _F{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=kR.UNAUTHENTICATED,this.clientId=HR.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{RR("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(RR("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new FR(LR.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new UR;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=CL(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function wF(e,t){e.asyncQueue.verifyOperationInProgress(),RR("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await gM(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function bF(e,n){e.asyncQueue.verifyOperationInProgress();var t=await IF(e);RR("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>IL(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>IL(n.remoteStore,t)),e.onlineComponents=n}async function IF(e){return e.offlineComponents||(RR("FirestoreClient","Using default OfflineComponentProvider"),await wF(e,new uF)),e.offlineComponents}async function TF(e){return e.onlineComponents||(RR("FirestoreClient","Using default OnlineComponentProvider"),await bF(e,new fF)),e.onlineComponents}function EF(e){return IF(e).then(e=>e.persistence)}function SF(e){return IF(e).then(e=>e.localStore)}function kF(e){return TF(e).then(e=>e.remoteStore)}function CF(e){return TF(e).then(e=>e.syncEngine)}async function AF(e){const t=await TF(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=cF(e);let r,i;const s=n.ea.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Xu();else{const e=await _M(n.localStore,EP(t));n.isPrimaryClient&&lL(n.remoteStore,e);const s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await GL(n,t,r,"current"===s)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ea.get(t),i=n.na.get(r.targetId);if(1<i.length)return n.na.set(r.targetId,i.filter(e=>!kP(e,t))),void n.ea.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await wM(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),uL(n.remoteStore,r.targetId),eF(n,r.targetId)}).catch(BO)):(eF(n,r.targetId),await wM(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function NF(e,t,n={}){const r=new UR;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,o){const e=new gF({next:e=>{r.enqueueAndForget(()=>OL(n,a));var t=e.docs.has(i);!t&&e.fromCache?o.reject(new FR(LR.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?o.reject(new FR(LR.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):o.resolve(e)},error:e=>o.reject(e)}),a=new LL(vP(i.path),e,{includeMetadataChanges:!0,Cu:!0});return DL(n,a)}(await AF(e),e.asyncQueue,t,n,r)),r.promise}function RF(e,t,n={}){const r=new UR;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new gF({next:e=>{n.enqueueAndForget(()=>OL(t,o)),e.fromCache&&"server"===r.source?i.reject(new FR(LR.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),o=new LL(e,s,{includeMetadataChanges:!0,Cu:!0});return DL(t,o)}(await AF(e),e.asyncQueue,t,n,r)),r.promise}function xF(e,t,n,r){const i=(n=n,t=ZM(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return pF(e,void 0);if(e instanceof ArrayBuffer)return pF(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new mF(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=UD(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n._s.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(jL(i));const o=new qL(i,t.localStore,n.M);let e=await n.da();for(;e;){const t=await o.ku(e);t&&r._updateProgress(t),e=await n.da()}var s=await o.complete();return await iF(t,s.Fu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n._s.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.Ou)}catch(t){return PR("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await CF(e),i,r)})}const PF=new Map;function DF(e,t,n){if(!n)throw new FR(LR.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function OF(e,t,n,r){if(!0===t&&!0===r)throw new FR(LR.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function MF(e){if(!wx.isDocumentKey(e))throw new FR(LR.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function LF(e){if(wx.isDocumentKey(e))throw new FR(LR.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function FF(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":OR();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function UF(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new FR(LR.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=FF(e);throw new FR(LR.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function qF(e,t){if(t<=0)throw new FR(LR.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class jF{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new FR(LR.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new FR(LR.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,OF("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class VF{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new jF({}),this._settingsFrozen=!1,e instanceof mx?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new FR(LR.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new mx(e.options.projectId)}(e))}get app(){if(!this._app)throw new FR(LR.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new FR(LR.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new jF(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new jR;switch(e.type){case"gapi":var t=e.client;return MR(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new $R(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new FR(LR.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=PF.get(e);t&&(RR("ComponentProvider","Removing Datastore"),PF.delete(e),t.terminate())}(this),Promise.resolve()}}class BF{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new $F(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new BF(this.firestore,e,this._key)}}class KF{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new KF(this.firestore,e,this._query)}}class $F extends KF{constructor(e,t,n){super(e,t,vP(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new BF(this.firestore,null,new wx(e))}withConverter(e){return new $F(this.firestore,e,this._path)}}function WF(e,t,...n){if(e=$d(e),DF("collection","path",t),e instanceof VF){var r=ix.fromString(t,...n);return LF(r),new $F(e,null,r)}if(!(e instanceof BF||e instanceof $F))throw new FR(LR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ix.fromString(t,...n));return LF(r),new $F(e.firestore,null,r)}function zF(e,t,...n){if(e=$d(e),DF("doc","path",t=1===arguments.length?HR.R():t),e instanceof VF){var r=ix.fromString(t,...n);return MF(r),new BF(e,null,new wx(r))}if(!(e instanceof BF||e instanceof $F))throw new FR(LR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ix.fromString(t,...n));return MF(r),new BF(e.firestore,e instanceof $F?e.converter:null,new wx(r))}function GF(e,t){return e=$d(e),t=$d(t),(e instanceof BF||e instanceof $F)&&(t instanceof BF||t instanceof $F)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function HF(e,t){return e=$d(e),t=$d(t),e instanceof KF&&t instanceof KF&&e.firestore===t.firestore&&kP(e._query,t._query)&&e.converter===t.converter}class QF{constructor(){this.ka=Promise.resolve(),this.Ma=[],this.Oa=!1,this.Fa=[],this.$a=null,this.Ba=!1,this.La=!1,this.Ua=[],this.Do=new eL(this,"async_queue_retry"),this.qa=()=>{var e=XM();e&&RR("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Do.Ao()};const e=XM();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.qa)}get isShuttingDown(){return this.Oa}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Ka(),this.Ga(e)}enterRestrictedMode(e){if(!this.Oa){this.Oa=!0,this.La=e||!1;const t=XM();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.qa)}}enqueue(e){if(this.Ka(),this.Oa)return new Promise(()=>{});const t=new UR;return this.Ga(()=>this.Oa&&this.La?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Ma.push(e),this.Qa()))}async Qa(){if(0!==this.Ma.length){try{await this.Ma[0](),this.Ma.shift(),this.Do.reset()}catch(e){if(!F1(e))throw e;RR("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Ma.length&&this.Do.To(()=>this.Qa())}}Ga(e){var t=this.ka.then(()=>(this.Ba=!0,e().catch(e=>{throw this.$a=e,this.Ba=!1,xR("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Ba=!1,e))));return this.ka=t}enqueueAfterDelay(e,t,n){this.Ka(),-1<this.Ua.indexOf(e)&&(t=0);var r=kL.createAndSchedule(this,e,t,n,e=>this.ja(e));return this.Fa.push(r),r}Ka(){this.$a&&OR()}verifyOperationInProgress(){}async Wa(){for(var e;await(e=this.ka),e!==this.ka;);}za(e){for(const t of this.Fa)if(t.timerId===e)return!0;return!1}Ha(t){return this.Wa().then(()=>{this.Fa.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Fa)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Wa()})}Ja(e){this.Ua.push(e)}ja(e){var t=this.Fa.indexOf(e);this.Fa.splice(t,1)}}function YF(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class JF{constructor(){this._progressObserver={},this._taskCompletionResolver=new UR,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var XF,ZF,eU,tU;class nU extends VF{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new QF,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||iU(this),this._firestoreClient.terminate()}}function rU(e){return e._firestoreClient||iU(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function iU(e){var t,n,r,i,s,o=e._freezeSettings(),o=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",i=e._persistenceKey,s=o,new gx(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new _F(e._authCredentials,e._appCheckCredentials,e._queue,o)}function sU(e,n,r){const i=new UR;return e.asyncQueue.enqueue(async()=>{try{await wF(e,r),await bF(e,n),i.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===LR.FAILED_PRECONDITION||t.code===LR.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw e;console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+e),i.reject(e)}var t}).then(()=>i.promise)}function oU(e){return function(e){const t=new UR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;gL(n.remoteStore)||RR("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.Bs.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.aa.get(e)||[];r.push(t),n.aa.set(e,r)}catch(e){const n=CL(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await CF(e),t)),t.promise}(rU(e=UF(e,nU)))}function aU(e){return(n=rU(e=UF(e,nU))).asyncQueue.enqueue(async()=>{const e=await EF(n),t=await kF(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.fu.delete(0),aL(e)}()});var n}function cU(e){return(n=rU(e=UF(e,nU))).asyncQueue.enqueue(async()=>{const e=await EF(n),t=await kF(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.fu.add(0),await cL(e),e.wu.set("Offline")}()});var n}function lU(t,e){return n=rU(t=UF(t,nU)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n._s.getNamedQuery(e,t))}(await SF(n),r)).then(e=>e?new KF(t,null,e.query):null);var n,r}function uU(e){if(e._initialized||e._terminated)throw new FR(LR.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class hU{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new FR(LR.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new ox(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class dU{constructor(e){this._byteString=e}static fromBase64String(e){try{return new dU(cx.fromBase64String(e))}catch(e){throw new FR(LR.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new dU(cx.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class fU{constructor(e){this._methodName=e}}class pU{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new FR(LR.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new FR(LR.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return QR(this._lat,e._lat)||QR(this._long,e._long)}}const gU=/^__.*__$/;class mU{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new tD(e,this.data,this.fieldMask,t,this.fieldTransforms):new eD(e,this.data,t,this.fieldTransforms)}}class vU{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new tD(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function yU(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw OR()}}class _U{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.M=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Ya(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Xa(){return this.settings.Xa}Za(e){return new _U(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.M,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}tc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Za({path:n,ec:!1});return r.nc(e),r}sc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Za({path:n,ec:!1});return r.Ya(),r}ic(e){return this.Za({path:void 0,ec:!0})}rc(e){return qU(e,this.settings.methodName,this.settings.oc||!1,this.path,this.settings.uc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}Ya(){if(this.path)for(let e=0;e<this.path.length;e++)this.nc(this.path.get(e))}nc(e){if(0===e.length)throw this.rc("Document fields must not be empty");if(yU(this.Xa)&&gU.test(e))throw this.rc('Document fields cannot begin and end with "__"')}}class wU{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.M=n||ZM(e)}ac(e,t,n,r=!1){return new _U({Xa:e,methodName:t,uc:n,path:ox.emptyPath(),ec:!1,oc:r},this.databaseId,this.M,this.ignoreUndefinedProperties)}}function bU(e){var t=e._freezeSettings(),n=ZM(e._databaseId);return new wU(e._databaseId,!!t.ignoreUndefinedProperties,n)}function IU(e,t,n,r,i,s={}){const o=e.ac(s.merge||s.mergeFields?2:0,t,n,i);MU("Data must be an object, but it was:",o,r);var a=DU(r,o);let c,l;if(s.merge)c=new ax(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=LU(t,r,n);if(!o.contains(i))throw new FR(LR.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);jU(e,i)||e.push(i)}c=new ax(e),l=o.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=o.fieldTransforms;return new mU(new qx(a),c,l)}class TU extends fU{_toFieldTransform(e){if(2!==e.Xa)throw 1===e.Xa?e.rc(`${this._methodName}() can only appear at the top level of your update data`):e.rc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof TU}}function EU(e,t,n){return new _U({Xa:3,uc:t.settings.uc,methodName:e._methodName,ec:n},t.databaseId,t.M,t.ignoreUndefinedProperties)}class SU extends fU{_toFieldTransform(e){return new WP(e.path,new FP)}isEqual(e){return e instanceof SU}}class kU extends fU{constructor(e,t){super(e),this.cc=t}_toFieldTransform(e){const t=EU(this,e,!0),n=this.cc.map(e=>PU(e,t)),r=new UP(n);return new WP(e.path,r)}isEqual(e){return this===e}}class CU extends fU{constructor(e,t){super(e),this.cc=t}_toFieldTransform(e){const t=EU(this,e,!0),n=this.cc.map(e=>PU(e,t)),r=new jP(n);return new WP(e.path,r)}isEqual(e){return this===e}}class AU extends fU{constructor(e,t){super(e),this.hc=t}_toFieldTransform(e){var t=new BP(e.M,OP(e.M,this.hc));return new WP(e.path,t)}isEqual(e){return this===e}}function NU(e,i,s,t){const o=e.ac(1,i,s);MU("Data must be an object, but it was:",o,t);const a=[],c=qx.empty();tx(t,(e,t)=>{var n=UU(i,e,s);t=$d(t);var r=o.sc(n);if(t instanceof TU)a.push(n);else{const e=PU(t,r);null!=e&&(a.push(n),c.set(n,e))}});var n=new ax(a);return new vU(c,n,o.fieldTransforms)}function RU(e,t,n,r,i,s){const o=e.ac(1,t,n),a=[LU(t,r,n)],c=[i];if(s.length%2!=0)throw new FR(LR.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)a.push(LU(t,s[f])),c.push(s[f+1]);const l=[],u=qx.empty();for(let p=a.length-1;0<=p;--p)if(!jU(l,a[p])){const t=a[p];var h=$d(h=c[p]);const r=o.sc(t);if(h instanceof TU)l.push(t);else{const e=PU(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new ax(l);return new vU(u,d,o.fieldTransforms)}function xU(e,t,n,r=!1){return PU(n,e.ac(r?4:3,t))}function PU(s,e){if(OU(s=$d(s)))return MU("Unsupported field value:",e,s),DU(s,e);if(s instanceof fU)return function(e,t){if(!yU(t.Xa))throw t.rc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.rc(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(s,e),null;if(void 0===s&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),s instanceof Array){if(e.settings.ec&&4!==e.Xa)throw e.rc("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=PU(i,t.ic(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=$d(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return OP(t.M,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=XR.fromDate(e);return{timestampValue:LD(t.M,n)}}if(e instanceof XR){n=new XR(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:LD(t.M,n)}}if(e instanceof pU)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof dU)return{bytesValue:FD(t.M,e._byteString)};if(e instanceof BF){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.rc(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:qD(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.rc(`Unsupported field value: ${FF(e)}`)}(0,e)}function DU(e,r){const i={};return nx(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):tx(e,(e,t)=>{var n=PU(t,r.tc(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function OU(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof XR||e instanceof pU||e instanceof dU||e instanceof BF||e instanceof fU)}function MU(e,t,n){if(!OU(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=FF(n);throw"an object"===r?t.rc(e+" a custom object"):t.rc(e+" "+r)}var i}function LU(e,t,n){if((t=$d(t))instanceof hU)return t._internalPath;if("string"==typeof t)return UU(e,t);throw qU("Field path arguments must be of type string or ",e,!1,void 0,n)}const FU=new RegExp("[~\\*/\\[\\]]");function UU(t,n,r){if(0<=n.search(FU))throw qU(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new hU(...n.split("."))._internalPath}catch(e){throw qU(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function qU(e,t,n,r,i){var s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new FR(LR.INVALID_ARGUMENT,a+e+c)}function jU(e,t){return e.some(e=>e.isEqual(t))}class VU{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new BF(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new BU(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(KU("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class BU extends VU{data(){return super.data()}}function KU(e,t){return"string"==typeof t?UU(e,t):(t instanceof hU?t:t._delegate)._internalPath}class $U{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class WU extends VU{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new zU(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(KU("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class zU extends WU{data(e={}){return super.data(e)}}class GU{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new $U(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new zU(this._firestore,this._userDataWriter,e.key,e,new $U(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new FR(LR.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let t=0;return s._snapshot.docChanges.map(e=>({type:"added",doc:new zU(s._firestore,s._userDataWriter,e.doc.key,e.doc,new $U(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter),oldIndex:-1,newIndex:t++}))}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new zU(s._firestore,s._userDataWriter,e.doc.key,e.doc,new $U(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return OR()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function HU(e,t){return e instanceof WU&&t instanceof WU?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof GU&&t instanceof GU&&e._firestore===t._firestore&&HF(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function QU(e){if(_P(e)&&0===e.explicitOrderBy.length)throw new FR(LR.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class YU{}function JU(e,...t){for(const n of t)e=n._apply(e);return e}class XU extends YU{constructor(e,t,n){super(),this.lc=e,this.fc=t,this.dc=n,this.type="where"}_apply(e){var t=bU(e.firestore),t=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new FR(LR.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){sq(o,s);const t=[];for(const n of o)t.push(iq(r,e,n));a={arrayValue:{values:t}}}else a=iq(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||sq(o,s),a=xU(n,t,o,"in"===s||"not-in"===s);var c=nP.create(i,s,a);return function(e,t){if(t.S()){const r=bP(e);if(null!==r&&!r.isEqual(t.field))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${t.field.toString()}'`);var n=wP(e);null!==n&&oq(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new FR(LR.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new FR(LR.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,c),c}(e._query,"where",t,e.firestore._databaseId,this.lc,this.fc,this.dc);return new KF(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new gP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class ZU extends YU{constructor(e,t){super(),this.lc=e,this._c=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new FR(LR.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new FR(LR.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new dP(t,n);return n=i,null!==wP(e=e)||null!==(r=bP(e))&&oq(0,r,n.field),i}(e._query,this.lc,this._c);return new KF(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new gP(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class eq extends YU{constructor(e,t,n){super(),this.type=e,this.wc=t,this.mc=n}_apply(e){return new KF(e.firestore,e.converter,SP(e._query,this.wc,this.mc))}}class tq extends YU{constructor(e,t,n){super(),this.type=e,this.gc=t,this.yc=n}_apply(e){var t,n=rq(e,this.type,this.gc,this.yc);return new KF(e.firestore,e.converter,(t=e._query,e=n,new gP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class nq extends YU{constructor(e,t,n){super(),this.type=e,this.gc=t,this.yc=n}_apply(e){var t,n=rq(e,this.type,this.gc,this.yc);return new KF(e.firestore,e.converter,(t=e._query,e=n,new gP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function rq(e,t,n,r){if(n[0]=$d(n[0]),n[0]instanceof VU)return function(e,t,n,r,i){if(!r)throw new FR(LR.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of TP(e))if(n.field.isKeyField())s.push(Nx(t,r.key));else{const e=r.data.field(n.field);if(fx(e))throw new FR(LR.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new FR(LR.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new hP(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=bU(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new FR(LR.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let c=0;c<i.length;c++){const l=i[c];if(o[c].field.isKeyField()){if("string"!=typeof l)throw new FR(LR.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!IP(e)&&-1!==l.indexOf("/"))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(ix.fromString(l));if(!wx.isDocumentKey(n))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new wx(n);a.push(Nx(t,i))}else{const e=xU(n,r,l);a.push(e)}}return new hP(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function iq(e,t,n){if("string"==typeof(n=$d(n))){if(""===n)throw new FR(LR.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!IP(t)&&-1!==n.indexOf("/"))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(ix.fromString(n));if(!wx.isDocumentKey(r))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Nx(e,new wx(r))}if(n instanceof BF)return Nx(e,n._key);throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${FF(n)}.`)}function sq(e,t){if(!Array.isArray(e)||0===e.length)throw new FR(LR.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new FR(LR.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function oq(e,t,n){if(!n.isEqual(t))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class aq{convertValue(e,t="none"){switch(Tx(e)){case 0:return null;case 1:return e.booleanValue;case 2:return hx(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(dx(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw OR()}}convertObject(e,n){const r={};return tx(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new pU(hx(e.latitude),hx(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return fx(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(px(e));default:return null}}convertTimestamp(e){var t=ux(e);return new XR(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=ix.fromString(e);MR(i1(n));const r=new mx(n.get(1),n.get(3)),i=new wx(n.popFirst(5));return r.isEqual(t)||xR(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function cq(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class lq extends aq{constructor(e){super(),this.firestore=e}convertBytes(e){return new dU(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new BF(this.firestore,null,t)}}class uq{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=bU(e)}set(e,t,n){this._verifyNotCommitted();const r=hq(e,this._firestore),i=cq(r.converter,t,n),s=IU(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,GP.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=hq(e,this._firestore);let s;return s="string"==typeof(t=$d(t))||t instanceof hU?RU(this._dataReader,"WriteBatch.update",i._key,t,n,r):NU(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,GP.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=hq(e,this._firestore);return this._mutations=this._mutations.concat(new sD(t._key,GP.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FR(LR.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function hq(e,t){if((e=$d(e)).firestore!==t)throw new FR(LR.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class dq extends aq{constructor(e){super(),this.firestore=e}convertBytes(e){return new dU(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new BF(this.firestore,null,t)}}function fq(t){t=UF(t,BF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return function(e,t){const n=new UR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.ci.Ls(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new FR(LR.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=CL(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await SF(e),t,n)),n.promise}(e,t._key).then(e=>new WU(n,r,t._key,e,new $U(null!==e&&e.hasLocalMutations,!0),t.converter))}function pq(t){t=UF(t,KF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return function(e,t){const n=new UR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await bM(e,t,!0),s=new KL(t,i.li),o=s.Gu(i.documents),a=s.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=CL(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await SF(e),t,n)),n.promise}(e,t._query).then(e=>new GU(n,r,t,e))}function gq(e,t,n){e=UF(e,BF);var r=UF(e.firestore,nU),i=cq(e.converter,t,n);return _q(r,[IU(bU(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,GP.none())])}function mq(e,t,n,...r){e=UF(e,BF);var i=UF(e.firestore,nU),s=bU(i);let o;return o="string"==typeof(t=$d(t))||t instanceof hU?RU(s,"updateDoc",e._key,t,n,r):NU(s,"updateDoc",e._key,t),_q(i,[o.toMutation(e._key,GP.exists(!0))])}function vq(t,...n){var e;t=$d(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||YF(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(YF(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let o,a,c;if(t instanceof BF)a=UF(t.firestore,nU),c=vP(t._key.path),o={next:e=>{n[i]&&n[i](wq(a,t,e))},error:n[i+1],complete:n[i+2]};else{const l=UF(t,KF);a=UF(l.firestore,nU),c=l._query;const u=new dq(a);o={next:e=>{n[i]&&n[i](new GU(a,u,l,e))},error:n[i+1],complete:n[i+2]},QU(t._query)}return function(e,t,n,r){const i=new gF(r),s=new LL(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>DL(await AF(e),s)),()=>{i.Ia(),e.asyncQueue.enqueueAndForget(async()=>OL(await AF(e),s))}}(rU(a),c,s,o)}function yq(e,t){return function(e,t){const n=new gF(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Eu.add(t),t.next()}(await AF(e),n)),()=>{n.Ia(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Eu.delete(t)}(await AF(e),n))}}(rU(e=UF(e,nU)),YF(t)?t:{next:t})}function _q(e,t){return function(e,t){const n=new UR;return e.asyncQueue.enqueueAndForget(async()=>HL(await CF(e),t,n)),n.promise}(rU(e),t)}function wq(e,t,n){var r=n.docs.get(t._key),i=new dq(e);return new WU(e,i,t._key,r,new $U(n.hasPendingWrites,n.fromCache),t.converter)}class bq extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=bU(e)}get(e){const n=hq(e,this._firestore),r=new lq(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return OR();const t=e[0];if(t.isFoundDocument())return new VU(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new VU(this._firestore,r,n._key,null,n.converter);throw OR()})}set(e,t,n){var r=hq(e,this._firestore),i=cq(r.converter,t,n),i=IU(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=hq(e,this._firestore),s="string"==typeof(t=$d(t))||t instanceof hU?RU(this._dataReader,"Transaction.update",i._key,t,n,r):NU(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=hq(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=hq(e,this._firestore),n=new dq(this._firestore);return super.get(e).then(e=>new WU(this._firestore,n,t._key,e._document,new $U(!1,!1),t.converter))}}function Iq(t,n){return function(t,n){const r=new UR;return t.asyncQueue.enqueueAndForget(async()=>{var e=await TF(t).then(e=>e.datastore);new yF(t.asyncQueue,e,n,r).run()}),r.promise}(rU(t=UF(t,nU)),e=>n(new bq(t,e)))}z=Tf,CR=z,_f(new Xd("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new nU(n,new BR(e.getProvider("auth-internal")),new zR(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),Cf(SR,"3.4.8",void 0),Cf(SR,"3.4.8","esm2017");function Tq(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new FR("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Eq(){if("undefined"==typeof Uint8Array)throw new FR("unimplemented","Uint8Arrays are not available in this environment.")}function Sq(){if("undefined"==typeof atob)throw new FR("unimplemented","Blobs are unavailable in Firestore in this environment.")}class kq{constructor(e){this._delegate=e}static fromBase64String(e){return Sq(),new kq(dU.fromBase64String(e))}static fromUint8Array(e){return Eq(),new kq(dU.fromUint8Array(e))}toBase64(){return Sq(),this._delegate.toBase64()}toUint8Array(){return Eq(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Cq(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class Aq{enableIndexedDbPersistence(e,t){return function(e,t){uU(e=UF(e,nU));var n=rU(e),r=e._freezeSettings(),i=new fF;return sU(n,i,new hF(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){uU(e=UF(e,nU));var t=rU(e),n=e._freezeSettings(),r=new fF;return sU(t,r,new dF(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new FR(LR.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new UR;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!O1.vt())return Promise.resolve();var t=e+"main";await O1.delete(t)}(lM(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Nq{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof mx||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||PR("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=UF(n,VF))._getSettings();if("firestore.googleapis.com"!==s.host&&s.host!==e&&PR("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},s),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=kR.MOCK_USER;else{e=id(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new FR(LR.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new kR(s)}n._authCredentials=new VR(new qR(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return aU(this._delegate)}disableNetwork(){return cU(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,OF("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return oU(this._delegate)}onSnapshotsInSync(e){return yq(this._delegate,e)}get app(){if(!this._appCompat)throw new FR("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Kq(this,WF(this._delegate,e))}catch(e){throw Mq(e,"collection()","Firestore.collection()")}}doc(e){try{return new Oq(this,zF(this._delegate,e))}catch(e){throw Mq(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new jq(this,function(e,t){if(e=UF(e,VF),DF("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new FR(LR.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new KF(e,null,(t=t,new gP(ix.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Mq(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Iq(this._delegate,e=>t(new xq(this,e)))}batch(){return rU(this._delegate),new Pq(new uq(this._delegate,e=>_q(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=rU(t=UF(t,nU)),r=new JF,xF(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return lU(this._delegate,e).then(e=>e?new jq(this,e):null)}}class Rq extends aq{constructor(e){super(),this.firestore=e}convertBytes(e){return new kq(new dU(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Oq.forKey(t,this.firestore,null)}}class xq{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Rq(e)}get(e){const t=$q(e);return this._delegate.get(t).then(e=>new Uq(this._firestore,new WU(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=$q(e);return n?(Tq("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=$q(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=$q(e);return this._delegate.delete(t),this}}class Pq{constructor(e){this._delegate=e}set(e,t,n){var r=$q(e);return n?(Tq("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=$q(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=$q(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Dq{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new zU(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new qq(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=Dq.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Dq(e,new Rq(e),t),r.set(t,i)),i}}Dq.INSTANCES=new WeakMap;class Oq{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Rq(e)}static forPath(e,t,n){if(e.length%2!=0)throw new FR("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Oq(t,new BF(t._delegate,n,new wx(e)))}static forKey(e,t,n){return new Oq(t,new BF(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Kq(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Kq(this.firestore,WF(this._delegate,e))}catch(e){throw Mq(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=$d(e))instanceof BF&&GF(this._delegate,e)}set(e,t){t=Tq("DocumentReference.set",t);try{return t?gq(this._delegate,e,t):gq(this._delegate,e)}catch(e){throw Mq(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?mq(this._delegate,e):mq(this._delegate,e,t,...n)}catch(e){throw Mq(e,"updateDoc()","DocumentReference.update()")}}delete(){return _q(UF((e=this._delegate).firestore,nU),[new sD(e._key,GP.none())]);var e}onSnapshot(...e){var t=Lq(e),n=Fq(e,e=>new Uq(this.firestore,new WU(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return vq(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?fq:"server"===(null==e?void 0:e.source)?function(t){t=UF(t,BF);const n=UF(t.firestore,nU);return NF(rU(n),t._key,{source:"server"}).then(e=>wq(n,t,e))}:function(t){t=UF(t,BF);const n=UF(t.firestore,nU);return NF(rU(n),t._key).then(e=>wq(n,t,e))})(this._delegate),t.then(e=>new Uq(this.firestore,new WU(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Oq(this.firestore,e?this._delegate.withConverter(Dq.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Mq(e,t,n){return e.message=e.message.replace(t,n),e}function Lq(e){for(const t of e)if("object"==typeof t&&!Cq(t))return t;return{}}function Fq(e,t){var n;let r;return r=Cq(e[0])?e[0]:Cq(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class Uq{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Oq(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return HU(this._delegate,e._delegate)}}class qq extends Uq{data(e){var t=this._delegate.data(e);return void 0!==t||OR(),t}}class jq{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Rq(e)}where(e,t,n){try{return new jq(this.firestore,JU(this._delegate,(r=n,i=t,s=KU("where",e),new XU(s,i,r))))}catch(e){throw Mq(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new jq(this.firestore,JU(this._delegate,([n,r="asc"]=[e,t],i=r,s=KU("orderBy",n),new ZU(s,i))))}catch(e){throw Mq(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new jq(this.firestore,JU(this._delegate,(qF("limit",t=e),new eq("limit",t,"F"))))}catch(e){throw Mq(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new jq(this.firestore,JU(this._delegate,(qF("limitToLast",t=e),new eq("limitToLast",t,"L"))))}catch(e){throw Mq(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new tq("startAt",e,!0)}(...e)))}catch(e){throw Mq(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new tq("startAfter",e,!1)}(...e)))}catch(e){throw Mq(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new nq("endBefore",e,!1)}(...e)))}catch(e){throw Mq(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new nq("endAt",e,!0)}(...e)))}catch(e){throw Mq(e,"endAt()","Query.endAt()")}}isEqual(e){return HF(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?pq:"server"===(null==e?void 0:e.source)?function(t){t=UF(t,KF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return RF(e,t._query,{source:"server"}).then(e=>new GU(n,r,t,e))}:function(t){t=UF(t,KF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return QU(t._query),RF(e,t._query).then(e=>new GU(n,r,t,e))})(this._delegate),t.then(e=>new Bq(this.firestore,new GU(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Lq(e),n=Fq(e,e=>new Bq(this.firestore,new GU(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return vq(this._delegate,t,n)}withConverter(e){return new jq(this.firestore,e?this._delegate.withConverter(Dq.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Vq{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new qq(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Bq{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new jq(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new qq(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Vq(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new qq(this._firestore,e))})}isEqual(e){return HU(this._delegate,e._delegate)}}class Kq extends jq{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new Oq(this.firestore,e):null}doc(e){try{return void 0===e?new Oq(this.firestore,zF(this._delegate)):new Oq(this.firestore,zF(this._delegate,e))}catch(e){throw Mq(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=UF(e.firestore,nU),r=zF(e),i=cq(e.converter,t);return _q(n,[IU(bU(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,GP.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Oq(this.firestore,e))}isEqual(e){return GF(this._delegate,e._delegate)}withConverter(e){return new Kq(this.firestore,e?this._delegate.withConverter(Dq.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function $q(e){return UF(e,BF)}const Wq={Firestore:Nq,GeoPoint:pU,Timestamp:XR,Blob:kq,Transaction:xq,WriteBatch:Pq,DocumentReference:Oq,DocumentSnapshot:Uq,Query:jq,QueryDocumentSnapshot:qq,QuerySnapshot:Bq,CollectionReference:Kq,FieldPath:class KK{constructor(...e){this._delegate=new hU(...e)}static documentId(){return new KK(ox.keyField().canonicalString())}isEqual(e){return(e=$d(e))instanceof hU&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class $K{constructor(e){this._delegate=e}static serverTimestamp(){const e=new SU("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new $K(e)}static delete(){const e=new TU("deleteField");return e._methodName="FieldValue.delete",new $K(e)}static arrayUnion(...e){const t=function(...e){return new kU("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new $K(t)}static arrayRemove(...e){const t=function(...e){return new CU("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new $K(t)}static increment(e){const t=new AU("increment",e);return t._methodName="FieldValue.increment",new $K(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,AR.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};XF=zf,ZF=(e,t)=>new Nq(e,t,new Aq),XF.INTERNAL.registerComponent(new Xd("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return ZF(t,n)},"PUBLIC").setServiceProps(Object.assign({},Wq))),XF.registerVersion("@firebase/firestore-compat","0.1.17");function zq(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function Gq(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>Gq(e)):"function"==typeof e||"object"==typeof e?zq(e,e=>Gq(e)):e}const Hq="functions",Qq={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class Yq extends gd{constructor(e,t,n){super(`${Hq}/${e}`,t||""),this.details=n}}function Jq(e,t){let n=function(e){if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!Qq[e])return new Yq("internal","internal");n=Qq[e],r=e}var o=s.message;"string"==typeof o&&(r=o),i=s.details,void 0!==i&&(i=Gq(i))}}catch(e){}return"ok"===n?null:new Yq(n,r,i)}class Xq{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){var e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const Zq="us-central1";class ej{constructor(e,t,n,r,i=Zq,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new Xq(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var o=new URL(i);this.customDomain=o.origin,this.region=Zq}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function tj(t,n,r){return e=>async function(e,t,n,r){const i=e._url(t),s={data:n=function t(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>t(e));if("function"==typeof e||"object"==typeof e)return zq(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)},o={},a=await e.contextProvider.getContext();a.authToken&&(o.Authorization="Bearer "+a.authToken);a.messagingToken&&(o["Firebase-Instance-ID-Token"]=a.messagingToken);null!==a.appCheckToken&&(o["X-Firebase-AppCheck"]=a.appCheckToken);const c=r.timeout||7e4,l=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new Yq("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(c),u=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}(i,s,o,e.fetchImpl),l.promise,e.cancelAllRequests]);if(l.cancel(),!u)throw new Yq("cancelled","Firebase Functions instance was deleted.");var h=Jq(u.status,u.json);if(h)throw h;if(!u.json)throw new Yq("internal","Response is not valid JSON object.");let d=u.json.data;void 0===d&&(d=u.json.result);if(void 0===d)throw new Yq("internal","Response is missing data field.");h=Gq(d);return{data:h}}(t,n,e,r||{})}const nj="@firebase/functions";function rj(e,t,n){$d(e).emulatorOrigin=`http://${t}:${n}`}eU=fetch.bind(self),_f(new Xd(Hq,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new ej(n,r,i,s,t,eU)},"PUBLIC").setMultipleInstances(!0)),Cf(nj,"0.7.11",tU),Cf(nj,"0.7.11","esm2017");var ij,sj,oj,aj;class cj{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return tj($d(this._delegate),e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new gd("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new gd("functions","Port missing in origin provided to useFunctionsEmulator()");return rj(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return rj(this._delegate,e,t)}}const lj="us-central1",uj=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:lj});return new cj(n,r)};ij={Functions:cj},zf.INTERNAL.registerComponent(new Xd("functions-compat",uj,"PUBLIC").setServiceProps(ij).setMultipleInstances(!0)),zf.registerVersion("@firebase/functions-compat","0.1.12");const hj="/firebase-messaging-sw.js",dj="/firebase-cloud-messaging-push-scope",fj="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",pj="https://fcmregistrations.googleapis.com/v1",gj="google.c.a.c_id",mj="google.c.a.e";function vj(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=S2=S2||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(yt=sj=sj||{}).PUSH_RECEIVED="push-received",yt.NOTIFICATION_CLICKED="notification-clicked";const yj="fcm_token_details_db",_j="fcm_token_object_Store";async function wj(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(yj))return null}let l=null;const e=await Yd(yj,5,async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(_j)){const a=r.objectStore(_j);var s,o=await a.index("fcmSenderId").get(c);await a.clear(),o&&(2===t?(s=o).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:vj(s.vapidKey)}}):3===t?(s=o,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:vj(s.auth),p256dh:vj(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:vj(s.vapidKey)}}):4===t&&(o=o,l={token:o.fcmToken,createTime:o.createTime,subscriptionOptions:{auth:vj(o.auth),p256dh:vj(o.p256dh),endpoint:o.endpoint,swScope:o.swScope,vapidKey:vj(o.vapidKey)}}))}});return e.close(),await Jd(yj),await Jd("fcm_vapid_details_db"),await Jd("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const bj="firebase-messaging-database",Ij=1,Tj="firebase-messaging-store";let Ej=null;function Sj(){return Ej=Ej||Yd(bj,Ij,(e,t)=>{0===t&&e.createObjectStore(Tj)}),Ej}async function kj(e){var t=Aj(e);const n=await Sj();t=await n.transaction(Tj).objectStore(Tj).get(t);if(t)return t;t=await wj(e.appConfig.senderId);return t?(await Cj(e,t),t):void 0}async function Cj(e,t){var n=Aj(e);const r=await Sj(),i=r.transaction(Tj,"readwrite");return await i.objectStore(Tj).put(t,n),await i.complete,t}function Aj({appConfig:e}){return e.appId}const Nj=new md("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function Rj(e,t){var n={method:"DELETE",headers:await Pj(e)};try{const s=await fetch(`${xj(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw Nj.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw Nj.create("token-unsubscribe-failed",{errorInfo:e})}}function xj({projectId:e}){return`${pj}/projects/${e}/registrations`}async function Pj({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function Dj({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==fj&&(i.web.applicationPubKey=r),i}const Oj=6048e5;async function Mj(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,o,a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:vj(t.getKey("auth")),p256dh:vj(t.getKey("p256dh"))},c=await kj(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=a.vapidKey===n.vapidKey,i=a.endpoint===n.endpoint,s=a.auth===n.auth,o=a.p256dh===n.p256dh,r&&i&&s&&o)return Date.now()>=c.createTime+Oj?async function(t,e){try{var n=await async function(e,t){var n=await Pj(e),r=Dj(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${xj(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw Nj.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Nj.create("token-update-failed",{errorInfo:r})}if(!i.token)throw Nj.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await Cj(t.firebaseDependencies,r),n}catch(e){throw await Lj(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Rj(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Fj(e.firebaseDependencies,a)}return Fj(e.firebaseDependencies,a)}async function Lj(e){var t=await kj(e.firebaseDependencies);t&&(await Rj(e.firebaseDependencies,t.token),await async function(e){var t=Aj(e);const n=await Sj(),r=n.transaction(Tj,"readwrite");await r.objectStore(Tj).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Fj(e,t){var n={token:await async function(e,t){var n=await Pj(e),r=Dj(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(xj(e.appConfig),r);i=await s.json()}catch(e){throw Nj.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Nj.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw Nj.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await Cj(e,n),n.token}function Uj(e){var t,n,r,i={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return n=i,(t=e).notification&&(n.notification={},(r=t.notification.title)&&(n.notification.title=r),(r=t.notification.body)&&(n.notification.body=r),(r=t.notification.image)&&(n.notification.image=r)),t=i,(n=e).data&&(t.data=n.data),n=i,(e=e).fcmOptions&&(n.fcmOptions={},(r=e.fcmOptions.link)&&(n.fcmOptions.link=r),(r=e.fcmOptions.analytics_label)&&(n.fcmOptions.analyticsLabel=r)),i}function qj(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function jj(e){return Nj.create("missing-app-config-values",{valueName:e})}qj("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),qj("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Vj{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw jj("App Configuration Object");if(!e.name)throw jj("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw jj(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function Bj(e){try{e.swRegistration=await navigator.serviceWorker.register(hj,{scope:dj}),e.swRegistration.update().catch(()=>{})}catch(e){throw Nj.create("failed-service-worker-registration",{browserErrorMessage:e.message})}}async function Kj(e,t){if(!navigator)throw Nj.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw Nj.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=fj)),await async function(e,t){if(t||e.swRegistration||await Bj(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw Nj.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),Mj(e)}async function $j(e,t,n){var r=function(e){switch(e){case sj.NOTIFICATION_CLICKED:return"notification_open";case sj.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[gj],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function Wj(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===sj.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Uj(r)):e.onMessageHandler.next(Uj(r))),n=r.data,"object"==typeof(t=n)&&t&&gj in t&&"1"===n[mj]&&await $j(e,r.messageType,n))}const zj="@firebase/messaging",Gj=e=>{const t=new Vj(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>Wj(t,e)),t},Hj=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>Kj(t,e)}};function Qj(e){return async function(e){if(!navigator)throw Nj.create("only-available-in-window");return e.swRegistration||await Bj(e),Lj(e)}(e=$d(e))}function Yj(e,t){return function(e,t){if(!navigator)throw Nj.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=$d(e),t)}_f(new Xd("messaging",Gj,"PUBLIC")),_f(new Xd("messaging-internal",Hj,"PRIVATE")),Cf(zj,"0.9.12"),Cf(zj,"0.9.12","esm2017");const Jj="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Xj="https://fcmregistrations.googleapis.com/v1",Zj="FCM_MSG",eV="google.c.a.c_id",tV=3,nV=1;function rV(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=oj=oj||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(c=aj=aj||{}).PUSH_RECEIVED="push-received",c.NOTIFICATION_CLICKED="notification-clicked";const iV="fcm_token_details_db",sV="fcm_token_object_Store";async function oV(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(iV))return null}let l=null;const e=await Yd(iV,5,async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(sV)){const a=r.objectStore(sV);var s,o=await a.index("fcmSenderId").get(c);await a.clear(),o&&(2===t?(s=o).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:rV(s.vapidKey)}}):3===t?(s=o,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:rV(s.auth),p256dh:rV(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:rV(s.vapidKey)}}):4===t&&(o=o,l={token:o.fcmToken,createTime:o.createTime,subscriptionOptions:{auth:rV(o.auth),p256dh:rV(o.p256dh),endpoint:o.endpoint,swScope:o.swScope,vapidKey:rV(o.vapidKey)}}))}});return e.close(),await Jd(iV),await Jd("fcm_vapid_details_db"),await Jd("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const aV="firebase-messaging-database",cV=1,lV="firebase-messaging-store";let uV=null;function hV(){return uV=uV||Yd(aV,cV,(e,t)=>{0===t&&e.createObjectStore(lV)}),uV}async function dV(e){var t=pV(e);const n=await hV();t=await n.transaction(lV).objectStore(lV).get(t);if(t)return t;t=await oV(e.appConfig.senderId);return t?(await fV(e,t),t):void 0}async function fV(e,t){var n=pV(e);const r=await hV(),i=r.transaction(lV,"readwrite");return await i.objectStore(lV).put(t,n),await i.complete,t}function pV({appConfig:e}){return e.appId}const gV=new md("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function mV(e,t){var n={method:"DELETE",headers:await yV(e)};try{const s=await fetch(`${vV(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw gV.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw gV.create("token-unsubscribe-failed",{errorInfo:e})}}function vV({projectId:e}){return`${Xj}/projects/${e}/registrations`}async function yV({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function _V({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==Jj&&(i.web.applicationPubKey=r),i}async function wV(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,o,a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:rV(t.getKey("auth")),p256dh:rV(t.getKey("p256dh"))},c=await dV(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=a.vapidKey===n.vapidKey,i=a.endpoint===n.endpoint,s=a.auth===n.auth,o=a.p256dh===n.p256dh,r&&i&&s&&o)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await yV(e),r=_V(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${vV(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw gV.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw gV.create("token-update-failed",{errorInfo:r})}if(!i.token)throw gV.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await fV(t.firebaseDependencies,r),n}catch(e){throw await bV(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await mV(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return IV(e.firebaseDependencies,a)}return IV(e.firebaseDependencies,a)}async function bV(e){var t=await dV(e.firebaseDependencies);t&&(await mV(e.firebaseDependencies,t.token),await async function(e){var t=pV(e);const n=await hV(),r=n.transaction(lV,"readwrite");await r.objectStore(lV).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function IV(e,t){var n={token:await async function(e,t){var n=await yV(e),r=_V(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(vV(e.appConfig),r);i=await s.json()}catch(e){throw gV.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw gV.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw gV.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await fV(e,n),n.token}async function TV(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=oj.DISPLAY_NOTIFICATION.toString():r.message_type=oj.DATA_MESSAGE.toString();r.sdk_platform=tV.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=nV.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function EV(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function SV(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await TV(t,n);var r,i,s=await CV();if(s.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=aj.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(s,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[Zj]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(s={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},n=s,(e=r).notification&&(n.notification={},(i=e.notification.title)&&(n.notification.title=i),(i=e.notification.body)&&(n.notification.body=i),(i=e.notification.image)&&(n.notification.image=i)),e=s,(n=r).data&&(e.data=n.data),n=s,(r=r).fcmOptions&&(n.fcmOptions={},(i=r.fcmOptions.link)&&(n.fcmOptions.link=i),(i=r.fcmOptions.analytics_label)&&(n.fcmOptions.analyticsLabel=i)),s=s,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(s):t.onBackgroundMessageHandler.next(s))}}async function kV(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[Zj];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&eV in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await CV();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=aj.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function CV(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function AV(e){return gV.create("missing-app-config-values",{valueName:e})}EV("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),EV("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class NV{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw AV("App Configuration Object");if(!e.name)throw AV("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw AV(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const RV=e=>{const t=new NV(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(SV(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await dV(t.firebaseDependencies),await bV(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:Jj,await wV(t)):await bV(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(kV(e))}),t};function xV(e,t){return function(e,t){if(void 0!==self.document)throw gV.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=$d(e),t)}_f(new Xd("messaging-sw",RV,"PUBLIC"));var PV,DV,OV;class MV{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return Kj(e=$d(e),t)}(this._delegate,e)}async deleteToken(){return Qj(this._delegate)}onMessage(e){return Yj(this._delegate,e)}onBackgroundMessage(e){return xV(this._delegate,e)}}const LV=e=>self&&"ServiceWorkerGlobalScope"in self?new MV(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new MV(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),FV={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?dd()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&dd()&&pd()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};zf.INTERNAL.registerComponent(new Xd("messaging-compat",LV,"PUBLIC").setServiceProps(FV)),zf.registerVersion("@firebase/messaging-compat","0.1.12");const UV="firebasestorage.googleapis.com",qV="storageBucket";class jV extends gd{constructor(e,t){super(VV(e),`Firebase Storage: ${t} (${VV(e)})`),this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,jV.prototype)}_codeEquals(e){return VV(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function VV(e){return"storage/"+e}function BV(){return new jV("unknown","An unknown error occurred, please check the error payload for server response.")}function KV(){return new jV("canceled","User canceled the upload/download.")}function $V(){return new jV("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function WV(e){return new jV("invalid-argument",e)}function zV(){return new jV("app-deleted","The Firebase app was deleted.")}function GV(e){return new jV("invalid-root-operation","The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function HV(e,t){return new jV("invalid-format","String does not match format '"+e+"': "+t)}function QV(e){throw new jV("internal-error","Internal error: "+e)}class YV{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=YV.makeFromUrl(t,e)}catch(e){return new YV(t,"")}if(""===n.path)return n;throw t=t,new jV("invalid-default-bucket","Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var o=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${o}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),o=t===UV?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${o}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new YV(u,e),d.postModify(n);break}}if(null==n)throw t=e,new jV("invalid-url","Invalid URL '"+t+"'.");return n}}class JV{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function XV(e){return"string"==typeof e||e instanceof String}function ZV(e){return eB()&&e instanceof Blob}function eB(){return"undefined"!=typeof Blob}function tB(e,t,n,r){if(r<t)throw WV(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw WV(`Invalid value for '${e}'. Expected ${n} or less.`)}function nB(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function rB(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}(c=PV=PV||{})[c.NO_ERROR=0]="NO_ERROR",c[c.NETWORK_ERROR=1]="NETWORK_ERROR",c[c.ABORT=2]="ABORT";class iB{constructor(e,t,n,r,i,s,o,a,c,l,u){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=o,this.errorCallback_=a,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(r,e)=>{if(e)r(!1,new sB(!1,null,!0));else{const i=this.connectionFactory_();this.pendingConnection_=i;const s=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&i.addUploadProgressListener(s),i.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&i.removeUploadProgressListener(s),this.pendingConnection_=null;var e,t=i.getErrorCode()===PV.NO_ERROR,n=i.getStatus();t&&!this.isRetryStatusCode_(n)?(e=-1!==this.successCodes_.indexOf(n),r(!0,new sB(e,i))):(e=i.getErrorCode()===PV.ABORT,r(!1,new sB(!1,null,e)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const a=BV();a.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,a)):r(a)}else{var o;t.canceled?(o=(this.appDelete_?zV:KV)(),r(o)):(o=new jV("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),r(o))}};this.canceled_?t(0,new sB(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,o=!1,a=0;function c(){return 2===a}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(f,c())},e)}function d(){s&&clearTimeout(s)}function f(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||o)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===a?(a=2,0):1e3*(r+Math.random()),h(e)}}let p=!1;function g(e){p||(p=!0,d(),l||(null!==i?(e||(a=2),clearTimeout(i),h(0)):e||(a=1)))}return h(0),s=setTimeout(()=>{g(o=!0)},e),g}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}isRetryStatusCode_(e){var t=500<=e&&e<600,n=-1!==[408,429].indexOf(e),r=-1!==this.additionalRetryCodes_.indexOf(e);return t||n||r}}class sB{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function oB(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(eB())return new Blob(t);throw new jV("unsupported-environment","This browser doesn't seem to support creating Blobs")}const aB={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class cB{constructor(e,t){this.data=e,this.contentType=t||null}}function lB(e,t){switch(e){case aB.RAW:return new cB(uB(t));case aB.BASE64:case aB.BASE64URL:return new cB(hB(e,t));case aB.DATA_URL:return new cB((n=t,(r=new dB(n)).base64?hB(aB.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw HV(aB.DATA_URL,"Malformed data URL.")}return uB(t)}(r.rest)),(n=t,new dB(n).contentType))}var n,r;throw BV()}function uB(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function hB(t,e){switch(t){case aB.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw HV(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case aB.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw HV(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw HV(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let o=0;o<i.length;o++)s[o]=i.charCodeAt(o);return s}class dB{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw HV(aB.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class fB{constructor(e,t){let n=0,r="";ZV(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(ZV(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new fB(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new fB(n,!0)}static getBlob(...e){if(eB()){var t=e.map(e=>e instanceof fB?e.data_:e);return new fB(oB.apply(null,t))}{const r=e.map(e=>XV(e)?lB(aB.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new fB(i,!0)}}uploadData(){return this.data_}}function pB(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function gB(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function mB(e,t){return t}class vB{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||mB}}let yB=null;function _B(){if(yB)return yB;const e=[];e.push(new vB("bucket")),e.push(new vB("generation")),e.push(new vB("metageneration")),e.push(new vB("name","fullPath",!0));const t=new vB("name");t.xform=function(e,t){return!XV(t=t)||t.length<2?t:gB(t)},e.push(t);const n=new vB("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new vB("timeCreated")),e.push(new vB("updated")),e.push(new vB("md5Hash",null,!0)),e.push(new vB("cacheControl",null,!0)),e.push(new vB("contentDisposition",null,!0)),e.push(new vB("contentEncoding",null,!0)),e.push(new vB("contentLanguage",null,!0)),e.push(new vB("contentType",null,!0)),e.push(new vB("metadata","customMetadata",!0)),yB=e,yB}function wB(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new YV(e,t);return r._makeStorageReference(t)}})}function bB(e,t,n){var r=pB(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const o=n[s];r[o.local]=o.xform(r,t[o.server])}return wB(r,e),r}(e,r,n)}function IB(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}function TB(e,t,n){var r=pB(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n.prefixes)for(const o of n.prefixes){var i=o.replace(/\/$/,""),i=e._makeStorageReference(new YV(t,i));r.prefixes.push(i)}if(n.items)for(const a of n.items){var s=e._makeStorageReference(new YV(t,a.name));r.items.push(s)}return r}(e,t,r)}class EB{constructor(e,t,n,r){this.url=e,this.method=t,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 SB(e){if(!e)throw BV()}function kB(r,i){return function(e,t){var n=bB(r,t,i);return SB(null!==n),n}}function CB(r,i){return function(e,t){var n=TB(r,i,t);return SB(null!==n),n}}function AB(r,i){return function(e,t){var n=bB(r,t,i);return SB(null!==n),function(r,e,i,s){var t=pB(e);if(null===t)return null;if(!XV(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const o=encodeURIComponent,a=n.split(",");return a.map(e=>{var t=r.bucket,n=r.fullPath;return nB("/b/"+o(t)+"/o/"+o(n),i,s)+rB({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function NB(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new jV("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new jV("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new jV("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(e=i.path,new jV("unauthorized","User does not have permission to access '"+e+"'.")):t,n.serverResponse=t.serverResponse,n}}function RB(r){const i=NB(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new jV("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function xB(e,t,n){var r=nB(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new EB(r,"GET",kB(e,n),i);return s.errorHandler=RB(t),s}function PB(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function DB(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const o={"X-Goog-Upload-Protocol":"multipart"};var a=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();o["Content-Type"]="multipart/related; boundary="+a;var c=PB(t,r,i),l="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+IB(c,n)+"\r\n--"+a+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",a="\r\n--"+a+"--";const u=fB.getBlob(l,r,a);if(null===u)throw $V();a={name:c.fullPath},c=nB(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new EB(c,"POST",kB(e,n),s);return h.urlParams=a,h.headers=o,h.body=u.uploadData(),h.errorHandler=NB(t),h}class OB{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function MB(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){SB(!1)}const r=t||["active"];return SB(!!n&&-1!==r.indexOf(n)),n}function LB(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),o=PB(t,r,i),a={name:o.fullPath},c=nB(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":o.contentType,"Content-Type":"application/json; charset=utf-8"},s=IB(o,n),o=e.maxUploadRetryTime;const u=new EB(c,"POST",function(e){MB(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){SB(!1)}return SB(XV(t)),t},o);return u.urlParams=a,u.headers=l,u.body=s,u.errorHandler=NB(t),u}function FB(e,t,n,i){var r=e.maxUploadRetryTime;const s=new EB(n,"POST",function(e){var t=MB(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){SB(!1)}n||SB(!1);var r=Number(n);return SB(!isNaN(r)),new OB(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=NB(t),s}function UB(e,o,t,a,n,c,r,i){const l=new OB(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=a.size()),a.size()!==l.total)throw new jV("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u,s={"X-Goog-Upload-Command":u===s?"upload, finalize":"upload","X-Goog-Upload-Offset":`${l.current}`};const f=a.slice(h,d);if(null===f)throw $V();d=o.maxUploadRetryTime;const p=new EB(t,"POST",function(e,t){var n=MB(e,["active","final"]),r=l.current+u,i=a.size();let s;return s="final"===n?kB(o,c)(e,t):null,new OB(r,i,"final"===n,s)},d);return p.headers=s,p.body=f.uploadData(),p.progressCallback=i||null,p.errorHandler=NB(e),p}const qB={STATE_CHANGED:"state_changed"},jB={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function VB(e){switch(e){case"running":case"pausing":case"canceling":return jB.RUNNING;case"paused":return jB.PAUSED;case"success":return jB.SUCCESS;case"canceled":return jB.CANCELED;default:return jB.ERROR}}class BB{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function KB(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class $B extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=PV.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=PV.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=PV.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw QV("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw QV("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw QV("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw QV("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw QV("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function WB(){return new $B}class zB{constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=_B(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{this._request=void 0,this._chunkMultiplier=1,e._codeEquals("canceled")?(this._needToFetchStatus=!0,this.completeTransitions_()):(this._error=e,this._transition("error"))},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals("canceled")?this.completeTransitions_():(this._error=e,this._transition("error"))},this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){const t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this._continueUpload():this._oneShotUpload())}_resolveToken(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=LB(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,WB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=FB(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,WB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const i=262144*this._chunkMultiplier,s=new OB(this._transferred,this._blob.size()),o=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=UB(this._ref._location,this._ref.storage,o,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const r=this._ref.storage._makeRequest(n,WB,e,t);this._request=r,r.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){262144*this._chunkMultiplier<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var n=xB(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,WB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=DB(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,WB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request&&this._request.cancel();break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=KV(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=VB(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new BB(t||void 0,n||void 0,r||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(VB(this._state)){case jB.SUCCESS:KB(this._resolve.bind(null,this.snapshot))();break;case jB.CANCELED:case jB.ERROR:const t=this._reject;KB(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(VB(this._state)){case jB.RUNNING:case jB.PAUSED:e.next&&KB(e.next.bind(e,this.snapshot))();break;case jB.SUCCESS:e.complete&&KB(e.complete.bind(e))();break;case jB.CANCELED:case jB.ERROR:default:e.error&&KB(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class GB{constructor(e,t){this._service=e,t instanceof YV?this._location=t:this._location=YV.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new GB(e,t)}get root(){var e=new YV(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return gB(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new YV(this._location.bucket,e);return new GB(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw GV(e)}}function HB(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await QB(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function QB(e,t){null!=t&&"number"==typeof t.maxResults&&tB("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var o=nB(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime;const c=new EB(o,"GET",CB(e,t.bucket),a);return c.urlParams=s,c.errorHandler=NB(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,WB)}function YB(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=nB(t.fullServerUrl(),e.host,e._protocol),s=IB(n,r),o=e.maxOperationRetryTime;const a=new EB(i,"PATCH",kB(e,r),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=RB(t),a}(e.storage,e._location,t,_B());return e.storage.makeRequestWithTokens(n,WB)}function JB(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=nB(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new EB(r,"GET",AB(e,n),i);return s.errorHandler=RB(t),s}(e.storage,e._location,_B());return e.storage.makeRequestWithTokens(t,WB).then(e=>{if(null===e)throw new jV("no-download-url","The given file does not have any download URLs.");return e})}function XB(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=nB(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new EB(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=RB(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,WB)}function ZB(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new YV(e._location.bucket,r);return new GB(e.storage,r)}function e2(e,t){if(e instanceof r2){var n=e;if(null==n._bucket)throw new jV("no-default-bucket","No default bucket found. Did you set the '"+qV+"' property when initializing the app?");n=new GB(n,n._bucket);return null!=t?e2(n,t):n}return void 0!==t?ZB(e,t):e}function t2(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof r2)return n=e,r=t,new GB(n,r);throw WV("To use ref(service, url), the first argument must be a Storage instance.")}return e2(e,t);var n,r}function n2(e,t){var n=null==t?void 0:t[qV];return null==n?null:YV.makeFromBucketSpec(n,e)}class r2{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=UV,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?YV.makeFromBucketSpec(r,this._host):n2(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=YV.makeFromBucketSpec(this._url,e):this._bucket=n2(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){tB("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){tB("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new GB(this,e)}_makeRequest(e,t,n,r){if(this._deleted)return new JV(zV());{const l=(i=e,s=this._appId,o=n,e=r,n=t,r=this._firebaseVersion,a=rB(i.urlParams),c=i.url+a,a=Object.assign({},i.headers),t=a,(s=s)&&(t["X-Firebase-GMPID"]=s),s=a,null!==(o=o)&&0<o.length&&(s.Authorization="Firebase "+o),r=r,a["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=a,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new iB(c,i.method,a,i.body,i.successCodes,i.additionalRetryCodes,i.handler,i.errorHandler,i.timeout,i.progressCallback,n));return this._requests.add(l),l.getPromise().then(()=>this._requests.delete(l),()=>this._requests.delete(l)),l}var i,s,o,a,c}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const i2="@firebase/storage";function s2(e,t,n){return e=$d(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new zB(e,new fB(t),n)}function o2(e){return function(e){e._throwIfRoot("getMetadata");var t=xB(e.storage,e._location,_B());return e.storage.makeRequestWithTokens(t,WB)}(e=$d(e))}function a2(e,t){return t2(e=$d(e),t)}function c2(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:id(i,e.app.options.projectId))}(e,t,n,r)}function l2(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new r2(n,r,i,t,Tf)}_f(new Xd("storage",l2,"PUBLIC").setMultipleInstances(!0)),Cf(i2,"0.9.5",""),Cf(i2,"0.9.5","esm2017");class u2{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class h2{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new u2(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new u2(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new u2(e,this,this._ref)):{next:t.next?e=>t.next(new u2(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class d2{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new f2(e,this._service))}get items(){return this._delegate.items.map(e=>new f2(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class f2{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=ZB(this._delegate,e);return new f2(t,this.storage)}get root(){return new f2(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new f2(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new h2(s2(this._delegate,e,t),this)}putString(e,t=aB.RAW,n){this._throwIfRoot("putString");var r=lB(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new h2(new zB(this._delegate,new fB(r.data,!0),i),this)}listAll(){return HB($d(this._delegate)).then(e=>new d2(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,QB(t=$d(t),e).then(e=>new d2(e,this.storage));var t}getMetadata(){return o2(this._delegate)}updateMetadata(e){return YB($d(this._delegate),e)}getDownloadURL(){return JB($d(this._delegate))}delete(){return this._throwIfRoot("delete"),XB($d(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw GV(e)}}class p2{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(g2(e))throw WV("ref() expected a child path but got a URL, use refFromURL instead.");return new f2(a2(this._delegate,e),this)}refFromURL(e){if(!g2(e))throw WV("refFromURL() expected a full URL but got a child path, use ref() instead.");try{YV.makeFromUrl(e,this._delegate.host)}catch(e){throw WV("refFromUrl() expected a valid full URL but got an invalid one.")}return new f2(a2(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){c2(this._delegate,e,t,n)}}function g2(e){return/^[A-Za-z]+:\/\//.test(e)}function m2(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new p2(n,r)}DV=zf,OV={TaskState:jB,TaskEvent:qB,StringFormat:aB,Storage:p2,Reference:f2},DV.INTERNAL.registerComponent(new Xd("storage-compat",m2,"PUBLIC").setServiceProps(OV).setMultipleInstances(!0)),DV.registerVersion("@firebase/storage-compat","0.1.13");const v2="@firebase/performance",y2="0.5.8",_2="FB-PERF-TRACE-MEASURE",w2="@firebase/performance/config",b2="@firebase/performance/configexpire";var I2,T2,E2,S2="Performance";const k2=new md("performance",S2,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),C2=new cf(S2);C2.logLevel=$h.INFO;let A2,N2;class R2{constructor(e){if(!(this.window=e))throw k2.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&pd()?!!dd()||(C2.info("IndexedDB is not supported by current browswer"),!1):(C2.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===A2&&(A2=new R2(N2)),A2}}let x2;function P2(e,t){var n=e.length-t.length;if(n<0||1<n)throw k2.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let D2;class O2{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=P2("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=P2("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===D2&&(D2=new O2),D2}}(c=I2=I2||{})[c.UNKNOWN=0]="UNKNOWN",c[c.VISIBLE=1]="VISIBLE",c[c.HIDDEN=2]="HIDDEN";const M2=["firebase_","google_","ga_"],L2=new RegExp("^[a-zA-Z]\\w*$");function F2(){switch(R2.getInstance().document.visibilityState){case"visible":return I2.VISIBLE;case"hidden":return I2.HIDDEN;default:return I2.UNKNOWN}}function U2(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw k2.create("no app id");return t}const q2="0.0.1",j2={loggingEnabled:!0},V2="FIREBASE_INSTALLATIONS_AUTH";function B2(e,t){var r,i,n=function(){const e=R2.getInstance().localStorage;if(e){var t=e.getItem(b2);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(w2);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?($2(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw k2.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw k2.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${V2} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:U2(r.app),app_version:y2,sdk_version:q2})});return fetch(n).then(e=>{if(e.ok)return e.json();throw k2.create("RC response not ok")})}).catch(()=>{C2.info(K2)}).then($2).then(e=>function(e){const t=R2.getInstance().localStorage;e&&t&&(t.setItem(w2,JSON.stringify(e)),t.setItem(b2,String(Date.now()+60*O2.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const K2="Could not fetch config, will use default configs";function $2(e){if(!e)return e;const t=O2.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=j2.loggingEnabled,n.fpr_log_source&&(t.logSource=Number(n.fpr_log_source)),n.fpr_log_endpoint_url&&(t.logEndPointUrl=n.fpr_log_endpoint_url),n.fpr_log_transport_key&&(t.transportKey=n.fpr_log_transport_key),void 0!==n.fpr_vc_network_request_sampling_rate&&(t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate)),void 0!==n.fpr_vc_trace_sampling_rate&&(t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate)),t.logTraceAfterSampling=W2(t.tracesSamplingRate),t.logNetworkAfterSampling=W2(t.networkRequestsSamplingRate),e}function W2(e){return Math.random()<=e}let z2=1,G2;function H2(e){var t;return z2=2,G2=G2||(t=e,function(){const n=R2.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{x2=e}),t}(t.installations)).then(e=>B2(t,e)).then(()=>Q2(),()=>Q2())),G2}function Q2(){z2=3}const Y2=1e4,J2=3,X2=1e3;let Z2=J2,eK=[],tK=!1;function nK(e){setTimeout(()=>{if(0!==Z2)return eK.length?void function(){const e=eK.splice(0,X2),t=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:O2.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=O2.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||C2.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=Y2;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(eK=[...r,...eK],C2.info("Retry transport request later.")),Z2=J2,nK(n)})}(n,e).catch(()=>{eK=[...e,...eK],Z2--,C2.info(`Tries left: ${Z2}.`),nK(Y2)})}():nK(Y2)},e)}function rK(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw k2.create("invalid cc log");eK=[...eK,e]}({message:t(...e),eventTime:Date.now()})}}let iK;function sK(e,t){iK=iK||rK(cK),iK(e,t)}function oK(e){var t=O2.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&R2.getInstance().requiredApisAvailable()&&(e.isAuto&&F2()!==I2.VISIBLE||(3===z2?aK(e):H2(e.performanceController).then(()=>aK(e),()=>aK(e))))}function aK(e){var t;!x2||(t=O2.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>sK(e,1),0)}function cK(e,t){return 0===t?(n={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},n={application_info:lK(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:lK(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function lK(e){return{google_app_id:U2(e),app_instance_id:x2,web_app_info:{sdk_version:y2,page_url:R2.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=R2.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:F2(),effective_connection_type:function(){var e=R2.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}()},application_process_state:0};var t}const uK=["_fp","_fcp","_fid"];class hK{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=R2.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`${_2}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw k2.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw k2.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),oK(this)}record(e,t,n){if(e<=0)throw k2.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw k2.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));oK(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<uK.indexOf(r))&&r.startsWith("_"))throw k2.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&C2.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!M2.some(e=>n.startsWith(e))&&!!n.match(L2)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw k2.create("invalid attribute name",{attributeName:e});if(!s)throw k2.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,n,r){var i=R2.getInstance().getUrl();if(i){const s=new hK(e,"_wt_"+i,!0);i=Math.floor(1e3*R2.getInstance().getTimeOrigin());s.setStartTime(i),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),oK(s)}}static createUserTimingTrace(e,t){oK(new hK(e,t,!1,t))}}function dK(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=R2.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=O2.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>sK(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const fK=5e3;function pK(e){x2&&(setTimeout(()=>function(n){const e=R2.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{hK.createOobTrace(n,r,i),t=void 0},fK);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),hK.createOobTrace(n,r,i,e))})}else hK.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=R2.getInstance(),n=e.getEntriesByType("resource");for(const r of n)dK(t,r);e.setupObserver("resource",e=>dK(t,e))}(e),0),setTimeout(()=>function(t){const e=R2.getInstance(),n=e.getEntriesByType("measure");for(const r of n)gK(t,r);e.setupObserver("measure",e=>gK(t,e))}(e),0))}function gK(e,t){const n=t.name;n.substring(0,_2.length)!==_2&&hK.createUserTimingTrace(e,n)}class mK{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),R2.getInstance().requiredApisAvailable()?fd().then(e=>{e&&(tK||(nK(5500),tK=!0),H2(this).then(()=>pK(this),()=>pK(this)),this.initialized=!0)}).catch(e=>{C2.info(`Environment doesn't support IndexedDB: ${e}`)}):C2.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){O2.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return O2.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){O2.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return O2.getInstance().dataCollectionEnabled}}const vK="[DEFAULT]";const yK=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==vK)throw k2.create("FB not default");if("undefined"==typeof window)throw k2.create("no window");e=window,N2=e;const i=new mK(n,r);return i._init(t),i};_f(new Xd("performance",yK,"PUBLIC")),Cf(v2,"0.5.8"),Cf(v2,"0.5.8","esm2017");class _K{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=$d(t),new hK(t,e);var t}}function wK(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new _K(t,n)}(T2=zf).INTERNAL.registerComponent(new Xd("performance-compat",wK,"PUBLIC")),T2.registerVersion("@firebase/performance-compat","0.1.8");const bK="@firebase/remote-config";class IK{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const TK=new md("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser"});const EK=["1","true","t","yes","y","on"];class SK{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=EK.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function kK(e){const t=$d(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function CK(e){const t=$d(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function AK(t){const n=$d(t),e=new IK;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof gd&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function NK(n){const e=$d(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=RK(n,t),e),{});var t,r}function RK(e,t){const n=$d(e);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new SK("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new SK("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new SK("static"))}class xK{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class PK{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let o;try{await Promise.race([i,r]),o=await i}catch(e){let t="fetch-client-network";throw"AbortError"===e.name&&(t="fetch-timeout"),TK.create(t,{originalErrorMessage:e.message})}let a=o.status;i=o.headers.get("ETag")||void 0;let c,l;if(200===o.status){let e;try{e=await o.json()}catch(e){throw TK.create("fetch-client-parse",{originalErrorMessage:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?a=500:"NO_CHANGE"===l?a=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==a&&200!==a)throw TK.create("fetch-status",{httpStatus:a});return{status:a,eTag:i,config:c}}}class DK{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(TK.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof gd&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+Kd(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class OK{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function MK(e,t){var n=e.target.error||void 0;return TK.create(t,{originalErrorMessage:n&&n.message})}const LK="app_namespace_store";class FK{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(MK(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(LK,{keyPath:"compositeKey"})}}catch(e){n(TK.create("storage-open",{originalErrorMessage:e}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(o){const a=await this.openDbPromise;return new Promise((n,t)=>{const e=a.transaction([LK],"readonly"),r=e.objectStore(LK);var i=this.createCompositeKey(o);try{const s=r.get(i);s.onerror=e=>{t(MK(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(TK.create("storage-get",{originalErrorMessage:e&&e.message}))}})}async set(o,a){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([LK],"readwrite"),r=n.objectStore(LK);var i=this.createCompositeKey(o);try{const s=r.put({compositeKey:i,value:a});s.onerror=e=>{t(MK(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(TK.create("storage-set",{originalErrorMessage:e&&e.message}))}})}async delete(o){const a=await this.openDbPromise;return new Promise((e,t)=>{const n=a.transaction([LK],"readwrite"),r=n.objectStore(LK);var i=this.createCompositeKey(o);try{const s=r.delete(i);s.onerror=e=>{t(MK(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(TK.create("storage-delete",{originalErrorMessage:e&&e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class UK{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}}async function qK(){if(!dd())return!1;try{return await fd()}catch(e){return!1}}_f(new Xd("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw TK.create("registration-window");if(!dd())throw TK.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:o}=n.options;if(!i)throw TK.create("registration-project-id");if(!s)throw TK.create("registration-api-key");if(!o)throw TK.create("registration-app-id");t=t||"firebase";const a=new FK(o,n.name,t),c=new UK(a),l=new cf(bK);l.logLevel=$h.ERROR;o=new PK(r,Tf,t,i,s,o),o=new DK(o,a),o=new xK(o,a,c,l),o=new OK(n,o,c,a,l);return CK(o),o},"PUBLIC").setMultipleInstances(!0)),Cf(bK,"0.3.7"),Cf(bK,"0.3.7","esm2017");class jK{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return kK(this._delegate)}ensureInitialized(){return CK(this._delegate)}fetch(){return AK(this._delegate)}fetchAndActivate(){return async function(e){return await AK(e=$d(e)),kK(e)}(this._delegate)}getAll(){return NK(this._delegate)}getBoolean(e){return RK($d(this._delegate),e).asBoolean()}getNumber(e){return RK($d(this._delegate),e).asNumber()}getString(e){return RK($d(this._delegate),e).asString()}getValue(e){return RK(this._delegate,e)}setLogLevel(e){!function(e,t){const n=$d(e);switch(t){case"debug":n._logger.logLevel=$h.DEBUG;break;case"silent":n._logger.logLevel=$h.SILENT;break;default:n._logger.logLevel=$h.ERROR}}(this._delegate,e)}}function VK(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new jK(n,r)}return(E2=zf).INTERNAL.registerComponent(new Xd("remoteConfig-compat",VK,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:qK})),E2.registerVersion("@firebase/remote-config-compat","0.1.8"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),zf.registerVersion("firebase","9.6.11","compat-cdn"),zf});
9
+ `)}function Hg(){var e=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}();const t=wg;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new rd;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Wg())}}const Qg={error:"UNKNOWN_ERROR"};async function Yg(e,t=!1){var n=e.app;Ng(n);const r=bg(n);let i=r.token,s=void 0;if(i||(a=await r.cachedTokenPromise)&&tm(a)&&(i=a),!t&&i&&tm(i))return{token:i.token};let o=!1;if(zg()){r.exchangeTokenPromise||(r.exchangeTokenPromise=Pg(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${Tg}/projects/${n}/apps/${r}:${Eg}?key=${i}`,body:{debug_token:t}}}(n,await Gg()),e.heartbeatServiceProvider).then(e=>(r.exchangeTokenPromise=void 0,e)),o=!0);var a=await r.exchangeTokenPromise;return await $g(n,a),Ig(n,Object.assign(Object.assign({},r),{token:a})),{token:a.token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().then(e=>(r.exchangeTokenPromise=void 0,e)),o=!0),i=await r.exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?Bg.warn(e.message):Bg.error(e),s=e}let c;return i?(c={token:i.token},Ig(n,Object.assign(Object.assign({},r),{token:i})),await $g(n,i)):c=(e=s,{token:function(e){return Zh.encodeString(JSON.stringify(e),!1)}(Qg),error:e}),o&&em(n,c),c}function Jg(e,t,n,r){var i=e["app"];const s=bg(i);var o={next:n,error:r,type:t};if(Ig(i,Object.assign(Object.assign({},s),{tokenObservers:[...s.tokenObservers,o]})),s.token&&tm(s.token)){const a=s.token;Promise.resolve().then(()=>{n({token:a.token}),Zg(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Zg(e))}function Xg(e,t){const n=bg(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),Ig(e,Object.assign(Object.assign({},n),{tokenObservers:r}))}function Zg(e){var t=e["app"],n=bg(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new kg(async()=>{var e=bg(r);let t;if(t=e.token?await Yg(n,!0):await Yg(n),t.error)throw t.error},()=>!0,()=>{var e=bg(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},Sg.RETRIAL_MIN_WAIT,Sg.RETRIAL_MAX_WAIT)}(e),Ig(t,Object.assign(Object.assign({},n),{tokenRefresher:r}))),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function em(e,t){for(const n of bg(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function tm(e){return 0<e.expireTimeMillis-Date.now()}class nm{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=bg(this.app)["tokenObservers"];for(const t of e)Xg(this.app,t.next);return Promise.resolve()}}const rm="https://www.google.com/recaptcha/api.js",im="https://www.google.com/recaptcha/enterprise.js";function sm(t,n){var e=bg(t);const r=new rd;Ig(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=cm(t);e=Ag(!1);return e?am(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=rm,t.onload=e,document.head.appendChild(t)}(()=>{var e=Ag(!1);if(!e)throw new Error("no recaptcha");am(t,n,e,i,r)}),r.promise}function om(t,n){var e=bg(t);const r=new rd;Ig(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=cm(t);e=Ag(!0);return e?am(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=im,t.onload=e,document.head.appendChild(t)}(()=>{var e=Ag(!0);if(!e)throw new Error("no recaptcha");am(t,n,e,i,r)}),r.promise}function am(r,i,s,o,a){s.ready(()=>{var e,t,n;e=r,t=s.render(o,{sitekey:i,size:"invisible"}),n=bg(e),Ig(e,Object.assign(Object.assign({},n),{reCAPTCHAState:Object.assign(Object.assign({},n.reCAPTCHAState),{widgetId:t})})),a.resolve(s)})}function cm(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function lm(r){Ng(r);const i=await bg(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=bg(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class um{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){pm(this._throttleData);var t=await lm(this._app).catch(e=>{throw Cg.create("recaptcha-error")});let e;try{e=await Pg(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${Tg}/projects/${n}/apps/${r}:exchangeRecaptchaV3Token?key=${i}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw"fetch-status-error"===e.code?(this._throttleData=fm(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),Cg.create("throttled",{time:Rg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=wf(e,"heartbeat"),sm(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof um&&this._siteKey===e._siteKey}}class hm{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){pm(this._throttleData);var t=await lm(this._app).catch(e=>{throw Cg.create("recaptcha-error")});let e;try{e=await Pg(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${Tg}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw"fetch-status-error"===e.code?(this._throttleData=fm(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),Cg.create("throttled",{time:Rg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=wf(e,"heartbeat"),om(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof hm&&this._siteKey===e._siteKey}}class dm{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=wd(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof dm&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function fm(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=Kd(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function pm(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw Cg.create("throttled",{time:Rg(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function gm(e=Sf(),t){const n=wf(e=$d(e),"app-check");if(wg.initialized||Hg(),zg()&&Gg().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw Cg.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=bg(t),i=Object.assign(Object.assign({},r),{activated:!0});i.provider=e,i.cachedTokenPromise=Kg(t).then(e=>(e&&tm(e)&&(Ig(t,Object.assign(Object.assign({},bg(t)),{token:e})),em(t,{token:e.token})),e)),i.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,Ig(t,i),i.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),bg(e).isTokenAutoRefreshEnabled&&Jg(r,"INTERNAL",()=>{}),r}const mm="app-check-internal";_f(new Xd("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new nm(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(mm).initialize()})),_f(new Xd(mm,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>Yg(t,e),addTokenListener:e=>Jg(t,"INTERNAL",e),removeTokenListener:e=>Xg(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),Cf("@firebase/app-check","0.5.7");const vm=new md("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class ym{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new um(e):e instanceof hm||e instanceof um||e instanceof dm?e:new dm({getToken:e.getToken}),this._delegate=gm(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw vm.create("use-before-activation",{appName:this.app.name});!function(e,t){var n=e.app;const r=bg(n);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),Ig(n,Object.assign(Object.assign({},r),{isTokenAutoRefreshEnabled:t}))}(this._delegate,e)}getToken(e){if(!this._delegate)throw vm.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Yg(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw vm.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Jg(e,"EXTERNAL",r,i),()=>Xg(e.app,r)}(this._delegate,e,t)}}const _m=e=>{var t=e.getProvider("app-compat").getImmediate();return new ym(t)};function wm(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}zf.INTERNAL.registerComponent(new Xd("appCheck-compat",_m,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:hm,ReCaptchaV3Provider:um,CustomProvider:dm})),zf.registerVersion("@firebase/app-check-compat","0.2.7");const bm={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},Im={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function Tm(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}function Em(){return{"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.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"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 AuthError 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 AuthError 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 to 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-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","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-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","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 AuthError 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 request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","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.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","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 AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError 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.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","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-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","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.","unverified-email":"The operation requires a verified email.","user-cancelled":"The 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.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance."}}const Sm=Tm,km=new md("auth","Firebase",Tm()),Cm=new cf("@firebase/auth");function Am(e,...t){Cm.logLevel<=$h.ERROR&&Cm.error(`Auth (${Tf}): ${e}`,...t)}function Nm(e,...t){throw Dm(e,...t)}function Rm(e,...t){return Dm(e,...t)}function xm(e,t,n){var r=Object.assign(Object.assign({},Sm()),{[t]:n});const i=new md("auth","Firebase",r);return i.create(t,{appName:e.name})}function Pm(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&Nm(e,"argument-error"),xm(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Dm(e,...t){if("string"==typeof e)return km.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function Om(e,t,...n){if(!e)throw Dm(t,...n)}function Mm(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Am(t),new Error(t)}function Lm(e,t){e||Mm(t)}const Fm=new Map;function Um(e){Lm(e instanceof Function,"Expected a class definition");let t=Fm.get(e);return t?Lm(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Fm.set(e,t)),t}function qm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function jm(){return"http:"===Vm()||"https:"===Vm()}function Vm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Bm{constructor(e,t){Lm((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=od()||ld()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(jm()||cd()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Km(e,t){Lm(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class $m{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void Mm("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:void Mm("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:void Mm("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Wm={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error"},zm=new Bm(3e4,6e4);function Gm(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Hm(i,s,o,a,e={}){return Qm(i,e,async()=>{let e={},t={};a&&("GET"===s?t=a:e={body:JSON.stringify(a)});var n=Cd(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),$m.fetch()(Jm(i,i.config.apiHost,o,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Qm(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Wm),e);try{const o=new Xm(t),a=await Promise.race([n(),o.promise]);o.clearNetworkTimeout();var i=await a.json();if("needConfirmation"in i)throw Zm(t,"account-exists-with-different-credential",i);if(a.ok&&!("errorMessage"in i))return i;{const c=a.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Zm(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Zm(t,"email-already-in-use",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw xm(t,s,u);Nm(t,s)}}catch(e){if(e instanceof gd)throw e;Nm(t,"network-request-failed")}}async function Ym(e,t,n,r,i={}){var s=await Hm(e,t,n,r,i);return"mfaPendingCredential"in s&&Nm(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Jm(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?Km(e.config,i):`${e.config.apiScheme}://${i}`}class Xm{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Rm(this.auth,"network-request-failed")),zm.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Zm(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Rm(e,t,r);return i.customData._tokenResponse=n,i}function ev(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function tv(e){return 1e3*Number(e)}function nv(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return Am("JWT malformed, contained fewer than 3 sections"),null;try{var i=td(n);return i?JSON.parse(i):(Am("Failed to decode base64 JWT payload"),null)}catch(e){return Am("Caught error parsing JWT payload as JSON",e),null}}async function rv(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof gd&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class iv{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,t)}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e.code&&this.schedule(!0))}this.schedule()}}class sv{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=ev(this.lastLoginAt),this.creationTime=ev(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function ov(e){var t=e.auth,n=await e.getIdToken(),r=await rv(e,async function(e,t){return Hm(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));Om(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,o,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=wm(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,o=t,[...s.filter(t=>!o.some(e=>e.providerId===t.providerId)),...o]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new sv(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class av{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Om(e.idToken,"internal-error"),Om(void 0!==e.idToken,"internal-error"),Om(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,Om(n=nv(t),"internal-error"),Om(void 0!==n.exp,"internal-error"),Om(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return Om(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:o}=(s=t,await{accessToken:(o=await Qm(i=e,{},async()=>{var e=Cd({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=Jm(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",$m.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:o.expires_in,refreshToken:o.refresh_token});this.updateTokensAndExpiration(n,r,Number(o))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new av;return n&&(Om("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(Om("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(Om("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new av,this.toJSON())}_performRefresh(){return Mm("not implemented")}}function cv(e,t){Om("string"==typeof e||void 0===e,"internal-error",{appName:t})}class lv{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=wm(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new iv(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new sv(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await rv(this,this.stsTokenManager.getToken(this.auth,e));return Om(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=$d(e);var r=await n.getIdToken(t),i=nv(r);Om(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:ev(tv(i.auth_time)),issuedAtTime:ev(tv(i.iat)),expirationTime:ev(tv(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=$d(e);await ov(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Om(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){return new lv(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){Om(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await ov(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await rv(this,async function(e,t){return Hm(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n=null!==(o=t.displayName)&&void 0!==o?o:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(a=t.phoneNumber)&&void 0!==a?a:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,o=null!==(c=t.tenantId)&&void 0!==c?c:void 0,a=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:f,stsTokenManager:p}=t;Om(u&&p,e,"internal-error");var g=av.fromJSON(this.name,p);Om("string"==typeof u,e,"internal-error"),cv(n,e.name),cv(r,e.name),Om("boolean"==typeof h,e,"internal-error"),Om("boolean"==typeof d,e,"internal-error"),cv(i,e.name),cv(s,e.name),cv(o,e.name),cv(a,e.name),cv(c,e.name),cv(l,e.name);const m=new lv({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:g,createdAt:c,lastLoginAt:l});return f&&Array.isArray(f)&&(m.providerData=f.map(e=>Object.assign({},e))),a&&(m._redirectEventId=a),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new av;r.updateFromServerResponse(t);var i=new lv({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await ov(i),i}}class uv{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}uv.type="NONE";const hv=uv;function dv(e,t,n){return`firebase:${e}:${t}:${n}`}class fv{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=dv(this.userKey,r.apiKey,i),this.fullPersistenceKey=dv("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){var e=await this.persistence._get(this.fullUserKey);return e?lv._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence!==e){var t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new fv(Um(hv),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||Um(hv);const s=dv(n,e.config.apiKey,e.name);let o=null;for(const u of t)try{var a=await u._get(s);if(a){var c=lv._fromJSON(e,a);u!==i&&(o=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new fv(i,e,n)}}function pv(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(yv(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(gv(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(wv(t))return"Blackberry";if(bv(t))return"Webos";if(mv(t))return"Safari";if((t.includes("chrome/")||vv(t))&&!t.includes("edge/"))return"Chrome";if(_v(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function gv(e=sd()){return/firefox\//i.test(e)}function mv(e=sd()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function vv(e=sd()){return/crios\//i.test(e)}function yv(e=sd()){return/iemobile/i.test(e)}function _v(e=sd()){return/android/i.test(e)}function wv(e=sd()){return/blackberry/i.test(e)}function bv(e=sd()){return/webos/i.test(e)}function Iv(e=sd()){return/iphone|ipad|ipod/i.test(e)}function Tv(e=sd()){return Iv(e)||_v(e)||bv(e)||wv(e)||/windows phone/i.test(e)||yv(e)}function Ev(e,t=[]){let n;switch(e){case"Browser":n=pv(sd());break;case"Worker":n=`${pv(sd())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Tf}/${r}`}class Sv{constructor(e,t,n){this.app=e,this.heartbeatServiceProvider=t,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Cv(this),this.idTokenSubscription=new Cv(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=km,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion}_initializeWithPersistence(t,n){return n&&(this._popupRedirectResolver=Um(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await fv.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e)}}async initializeCurrentUser(e){var t,n,r;let i=await this.assertedPersistence.getCurrentUser();return e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===i||void 0===i?void 0:i._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(i=r.user)),i?i._redirectEventId?(Om(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)):this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await ov(e)}catch(e){if("auth/network-request-failed"!==e.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?$d(e):null;return t&&Om(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){if(!this._deleted)return e&&Om(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(Um(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new md("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(Om(t=e&&Um(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await fv.create(this,[Um(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=null!==(e=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return Om(s,this,"internal-error"),s.then(()=>i(this.currentUser)),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&(this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh()),(this.currentUser=e)?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return Om(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Ev(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);var t=await(null===(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getHeartbeatsHeader());return t&&(e["X-Firebase-Client"]=t),e}}function kv(e){return $d(e)}class Cv{constructor(e){this.auth=e,this.observer=null,this.addObserver=xd(e=>this.observer=e)}get next(){return Om(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function Av(e,t,n){const r=kv(e);Om(r._canInitEmulator,r,"emulator-config-failed"),Om(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=Nv(t);var{host:o,port:a}=function(e){const t=Nv(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:Rv(r.substr(s.length+1))}}var[o,s]=r.split(":");return{host:o,port:Rv(s)}}}(t);r.config.emulator={url:`${s}//${o}${null===a?"":`:${a}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function Nv(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Rv(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class xv{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Mm("not implemented")}_getIdTokenResponse(e){return Mm("not implemented")}_linkToIdToken(e,t){return Mm("not implemented")}_getReauthenticationResolver(e){return Mm("not implemented")}}async function Pv(e,t){return Hm(e,"POST","/v1/accounts:resetPassword",Gm(e,t))}async function Dv(e,t){return Hm(e,"POST","/v1/accounts:update",t)}async function Ov(e,t){return Hm(e,"POST","/v1/accounts:sendOobCode",Gm(e,t))}class Mv extends xv{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new Mv(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Mv(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithPassword",Gm(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithEmailLink",Gm(e,t))}(e,{email:this._email,oobCode:this._password});default:Nm(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Dv(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithEmailLink",Gm(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:Nm(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Lv(e,t){return Ym(e,"POST","/v1/accounts:signInWithIdp",Gm(e,t))}class Fv extends xv{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Fv(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):Nm("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,t=wm(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Fv(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return Lv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Lv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Lv(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=Cd(t)}return e}}const Uv={USER_NOT_FOUND:"user-not-found"};class qv extends xv{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new qv({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new qv({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithPhoneNumber",Gm(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Ym(e,"POST","/v1/accounts:signInWithPhoneNumber",Gm(e,t));if(n.temporaryProof)throw Zm(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Ym(e,"POST","/v1/accounts:signInWithPhoneNumber",Gm(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Uv)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){var{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new qv({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class jv{constructor(e){var t=Ad(Nd(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);Om(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=Ad(Nd(e=e)).link,n=t?Ad(Nd(t)).deep_link_id:null,((r=Ad(Nd(e)).deep_link_id)?Ad(Nd(r)).link:null)||r||n||t||e);try{return new jv(t)}catch(e){return null}}}class Vv{constructor(){this.providerId=Vv.PROVIDER_ID}static credential(e,t){return Mv._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=jv.parseLink(t);return Om(n,"argument-error"),Mv._fromEmailAndCode(e,n.code,n.tenantId)}}Vv.PROVIDER_ID="password",Vv.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Vv.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Bv{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class Kv extends Bv{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class $v extends Kv{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return Om("providerId"in t&&"signInMethod"in t,"argument-error"),Fv._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return Om(e.idToken||e.accessToken,"argument-error"),Fv._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return $v.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return $v.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:o}=e;if(!(n||r||t||i))return null;if(!o)return null;try{return new $v(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Wv extends Kv{constructor(){super("facebook.com")}static credential(e){return Fv._fromParams({providerId:Wv.PROVIDER_ID,signInMethod:Wv.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Wv.credentialFromTaggedObject(e)}static credentialFromError(e){return Wv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Wv.credential(e.oauthAccessToken)}catch(e){return null}}}Wv.FACEBOOK_SIGN_IN_METHOD="facebook.com",Wv.PROVIDER_ID="facebook.com";class zv extends Kv{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Fv._fromParams({providerId:zv.PROVIDER_ID,signInMethod:zv.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return zv.credentialFromTaggedObject(e)}static credentialFromError(e){return zv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return zv.credential(t,n)}catch(e){return null}}}zv.GOOGLE_SIGN_IN_METHOD="google.com",zv.PROVIDER_ID="google.com";class Gv extends Kv{constructor(){super("github.com")}static credential(e){return Fv._fromParams({providerId:Gv.PROVIDER_ID,signInMethod:Gv.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Gv.credentialFromTaggedObject(e)}static credentialFromError(e){return Gv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Gv.credential(e.oauthAccessToken)}catch(e){return null}}}Gv.GITHUB_SIGN_IN_METHOD="github.com",Gv.PROVIDER_ID="github.com";class Hv extends xv{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return Lv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Lv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Lv(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new Hv(t,r):null}static _create(e,t){return new Hv(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Qv extends Bv{constructor(e){Om(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Qv.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Qv.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Hv.fromJSON(e);return Om(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return Hv._create(n,t)}catch(e){return null}}}class Yv extends Kv{constructor(){super("twitter.com")}static credential(e,t){return Fv._fromParams({providerId:Yv.PROVIDER_ID,signInMethod:Yv.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Yv.credentialFromTaggedObject(e)}static credentialFromError(e){return Yv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return Yv.credential(t,n)}catch(e){return null}}}async function Jv(e,t){return Ym(e,"POST","/v1/accounts:signUp",Gm(e,t))}Yv.TWITTER_SIGN_IN_METHOD="twitter.com",Yv.PROVIDER_ID="twitter.com";class Xv{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await lv._fromIdTokenResponse(e,n,r),s=Zv(n);return new Xv({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=Zv(n);return new Xv({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function Zv(e){return e.providerId||("phoneNumber"in e?"phone":null)}class ey extends gd{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,ey.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new ey(e,t,n,r)}}function ty(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw ey._fromErrorAndOperation(t,e,n,r);throw e})}function ny(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function ry(e,t){const n=$d(e);await sy(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await Hm(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=ny(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function iy(e,t,n=!1){var r=await rv(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Xv._forOperation(e,"link",r)}async function sy(e,t,n){await ov(t);const r=ny(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";Om(r.has(n)===e,t.auth,i)}async function oy(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await rv(e,ty(r,i,t,e),n);Om(s.idToken,r,"internal-error");var o=nv(s.idToken);Om(o,r,"internal-error");var a=o["sub"];return Om(e.uid===a,r,"user-mismatch"),Xv._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&Nm(r,"user-mismatch"),e}}async function ay(e,t,n=!1){var r=await ty(e,"signIn",t),r=await Xv._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function cy(e,t){return ay(kv(e),t)}async function ly(e,t){var n=$d(e);return await sy(!1,n,t.providerId),iy(n,t)}async function uy(e,t){return oy($d(e),t)}async function hy(e,t){const n=kv(e);var r=await Ym(n,"POST","/v1/accounts:signInWithCustomToken",Gm(n,{token:t,returnSecureToken:!0})),r=await Xv._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class dy{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?fy._fromServerResponse(e,t):Nm(e,"internal-error")}}class fy extends dy{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new fy(t)}}function py(e,t,n){var r;Om(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),Om(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(Om(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(Om(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function gy(e,t,n){var r=$d(e),i={requestType:"PASSWORD_RESET",email:t};n&&py(r,i,n),await Ov(r,i)}async function my(e,t){await Hm(e=$d(e),"POST","/v1/accounts:update",Gm(e,{oobCode:t}))}async function vy(e,t){var n=$d(e),r=await Pv(n,{oobCode:t}),i=r.requestType;switch(Om(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":Om(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":Om(r.mfaInfo,n,"internal-error");default:Om(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=dy._fromServerResponse(kv(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function yy(e,t,n){var r=$d(e),i={requestType:"EMAIL_SIGNIN",email:t};Om(n.handleCodeInApp,r,"argument-error"),n&&py(r,i,n),await Ov(r,i)}async function _y(e,t){var n=jm()?qm():"http://localhost",n=(await Hm(e=$d(e),"POST","/v1/accounts:createAuthUri",Gm(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function wy(e,t){var n=$d(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&py(n.auth,r,t);var r=(await Ov(n.auth,r))["email"];r!==e.email&&await e.reload()}async function by(e,t,n){var r=$d(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&py(r.auth,i,n);var i=(await Ov(r.auth,i))["email"];i!==e.email&&await e.reload()}async function Iy(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=$d(e);var r=await i.getIdToken(),r=await rv(i,async function(e,t){return Hm(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function Ty(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await rv(e,Dv(r,i));await e._updateTokensIfNecessary(r,!0)}class Ey{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class Sy extends Ey{constructor(e,t,n,r){super(e,t,n),this.username=r}}class ky extends Ey{constructor(e,t){super(e,"facebook.com",t)}}class Cy extends Sy{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class Ay extends Ey{constructor(e,t){super(e,"google.com",t)}}class Ny extends Sy{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Ry(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=nv(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new Ey(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new ky(r,n);case"github.com":return new Cy(r,n);case"google.com":return new Ay(r,n);case"twitter.com":return new Ny(r,n,e.screenName||null);case"custom":case"anonymous":return new Ey(r,null);default:return new Ey(r,t,n)}}(n)}class xy{constructor(e,t){this.type=e,this.credential=t}static _fromIdtoken(e){return new xy("enroll",e)}static _fromMfaPendingCredential(e){return new xy("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.pendingCredential)return xy._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return xy._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Py{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=kv(e),o=i.customData._serverResponse;var t=(o.mfaInfo||[]).map(e=>dy._fromServerResponse(s,e));Om(o.mfaPendingCredential,s,"internal-error");const a=xy._fromMfaPendingCredential(o.mfaPendingCredential);return new Py(a,t,async e=>{var t=await e._process(s,a);delete o.mfaInfo,delete o.mfaPendingCredential;var n=Object.assign(Object.assign({},o),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Xv._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return Om(i.user,s,"internal-error"),Xv._forOperation(i.user,i.operationType,n);default:Nm(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class Dy{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>dy._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new Dy(e)}async getSession(){return xy._fromIdtoken(await this.user.getIdToken())}async enroll(e,t){const n=e;var r=await this.getSession(),r=await rv(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r=await this.user.getIdToken(),r=await rv(this.user,(n=this.user.auth,e={idToken:r,mfaEnrollmentId:t},Hm(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Gm(n,e))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(r);try{await this.user.reload()}catch(e){if("auth/user-token-expired"!==e.code)throw e}}}const Oy=new WeakMap;const My="__sak";class Ly{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(My,"1"),this.storage.removeItem(My),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){var t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class Fy extends Ly{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(mv(e=sd())||Iv(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Tv(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);ud()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Fy.type="LOCAL";const Uy=Fy;class qy extends Ly{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}qy.type="SESSION";const jy=qy;class Vy{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));if(e)return e;e=new Vy(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:s}))}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function By(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}Vy.receivers=[];class Ky{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,o=50){const a="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!a)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=By("",20);a.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},o);l={messageChannel:a,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),a.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[a.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function $y(){return window}function Wy(){return void 0!==$y().WorkerGlobalScope&&"function"==typeof $y().importScripts}const zy="firebaseLocalStorageDb",Gy="firebaseLocalStorage",Hy="fbase_key";class Qy{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function Yy(e,t){return e.transaction([Gy],t?"readwrite":"readonly").objectStore(Gy)}function Jy(){const r=indexedDB.open(zy,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(Gy,{keyPath:Hy})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(Gy)?n(e):(e.close(),t=indexedDB.deleteDatabase(zy),await new Qy(t).toPromise(),n(await Jy()))})})}async function Xy(e,t,n){var r=Yy(e,!0).put({fbase_key:t,value:n});return new Qy(r).toPromise()}function Zy(e,t){var n=Yy(e,!0).delete(t);return new Qy(n).toPromise()}class e_{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db||(this.db=await Jy(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Wy()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Vy._getInstance(Wy()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new Ky(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;var e=await Jy();return await Xy(e,My,"1"),await Zy(e,My),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Xy(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=Yy(e,!1).get(t);return void 0===(n=await new Qy(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Zy(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=Yy(e,!1).getAll();return new Qy(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}e_.type="LOCAL";const t_=e_;function n_(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=Rm("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function r_(e){return`__${e}${Math.floor(1e6*Math.random())}`}class i_{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new s_(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class s_{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;Om(r,"argument-error",{appName:t}),this.container=r,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const o_=r_("rcb"),a_=new Bm(3e4,6e4);class c_{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!$y().grecaptcha}load(s,o=""){var e;return Om((e=o).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(o)?Promise.resolve($y().grecaptcha):new Promise((t,n)=>{const i=$y().setTimeout(()=>{n(Rm(s,"network-request-failed"))},a_.get());$y()[o_]=()=>{$y().clearTimeout(i),delete $y()[o_];const e=$y().grecaptcha;if(e){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=o,t(e)}else n(Rm(s,"internal-error"))},n_(`https://www.google.com/recaptcha/api.js??${Cd({onload:o_,render:"explicit",hl:o})}`).catch(()=>{clearTimeout(i),n(Rm(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!$y().grecaptcha&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class l_{async load(e){return new i_(e)}clearedOneInstance(){}}const u_="recaptcha",h_={theme:"light",type:"image"};class d_{constructor(e,t=Object.assign({},h_),n){this.parameters=t,this.type=u_,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=kv(n),this.isInvisible="invisible"===this.parameters.size,Om("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof e?document.getElementById(e):e;Om(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?l_:c_),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){Om(!this.parameters.sitekey,this.auth,"argument-error"),Om(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),Om("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=$y()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){Om(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){Om(jm()&&!Wy(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).catch(e=>{throw t&&window.removeEventListener("load",t),e})}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await Hm(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");Om(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return Om(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class f_{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=qv._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function p_(t,n,r){var i,s,o,a,c,l,u=await r.verify();try{Om("string"==typeof u,t,"argument-error"),Om(r.type===u_,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return Om("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await Hm(c,"POST","/v2/accounts/mfaEnrollment:start",Gm(c,l))).phoneSessionInfo.sessionInfo;Om("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return Om(d,t,"missing-multi-factor-info"),(a={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await Hm(t,"POST","/v2/accounts/mfaSignIn:start",Gm(t,a))).phoneResponseInfo.sessionInfo}var f=(s=t,o={phoneNumber:e.phoneNumber,recaptchaToken:u},await Hm(s,"POST","/v1/accounts:sendVerificationCode",Gm(s,o)))["sessionInfo"];return f}finally{r._reset()}}class g_{constructor(e){this.providerId=g_.PROVIDER_ID,this.auth=kv(e)}verifyPhoneNumber(e,t){return p_(this.auth,e,$d(t))}static credential(e,t){return qv._fromVerification(e,t)}static credentialFromResult(e){var t=e;return g_.credentialFromTaggedObject(t)}static credentialFromError(e){return g_.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?qv._fromTokenResponse(t,n):null}}function m_(e,t){return t?Um(t):(Om(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}g_.PROVIDER_ID="phone",g_.PHONE_SIGN_IN_METHOD="phone";class v_ extends xv{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Lv(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Lv(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Lv(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function y_(e){return ay(e.auth,new v_(e),e.bypassAuthState)}function __(e){var{auth:t,user:n}=e;return Om(n,t,"internal-error"),oy(n,new v_(e),e.bypassAuthState)}async function w_(e){var{auth:t,user:n}=e;return Om(n,t,"internal-error"),iy(n,new v_(e),e.bypassAuthState)}class b_{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){var{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return y_;case"linkViaPopup":case"linkViaRedirect":return w_;case"reauthViaPopup":case"reauthViaRedirect":return __;default:Nm(this.auth,"internal-error")}}resolve(e){Lm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Lm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const I_=new Bm(2e3,1e4);class T_ extends b_{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,T_.currentPopupAction&&T_.currentPopupAction.cancel(),T_.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return Om(e,this.auth,"internal-error"),e}async onExecution(){Lm(1===this.filter.length,"Popup operations only handle one event");var e=By();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(Rm(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(Rm(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,T_.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Rm(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(t,I_.get())};t()}}T_.currentPopupAction=null;const E_="pendingRedirect",S_=new Map;class k_ extends b_{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=S_.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=N_(t),r=A_(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}S_.set(this.auth._key(),t)}return this.bypassAuthState||S_.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function C_(e,t){return A_(e)._set(N_(t),"true")}function A_(e){return Um(e._redirectPersistence)}function N_(e){return dv(E_,e.config.apiKey,e.name)}function R_(e,t,n){return async function(e,t,n){var r=kv(e);Pm(e,t,Bv);const i=m_(r,n);return await C_(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function x_(e,t,n){return async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);const i=m_(r.auth,n);await C_(i,r.auth);var s=await O_(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function P_(e,t,n){return async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);const i=m_(r.auth,n);await sy(!1,r,t.providerId),await C_(i,r.auth);var s=await O_(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function D_(e,t,n=!1){const r=kv(e);var i=m_(r,t);const s=new k_(r,i,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,t)),o}async function O_(e){var t=By(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class M_{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(t){if(this.hasEventBeenHandled(t))return!1;let n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return F_(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!F_(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(Rm(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(L_(e))}saveEventToCache(e){this.cachedEventUids.add(L_(e)),this.lastProcessedEventTime=Date.now()}}function L_(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function F_({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function U_(e,t={}){return Hm(e,"GET","/v1/projects",t)}const q_=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,j_=/^https?/;async function V_(e){if(!e.config.emulator){var t=(await U_(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=qm(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!j_.test(n))return!1;if(q_.test(e))return r===e;const s=e.replace(/\./g,"\\."),o=new RegExp("^(.+\\."+s+"|"+s+")$","i");return o.test(r)}(n))return}catch(e){}Nm(e,"unauthorized-domain")}}const B_=new Bm(3e4,6e4);function K_(){const t=$y().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let $_=null;function W_(e){var i;return $_=$_||(i=e,new Promise((e,t)=>{function n(){K_(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{K_(),t(Rm(i,"network-request-failed"))},timeout:B_.get()})}if(null!==(r=null===(r=$y().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=$y().gapi)||void 0===r||!r.load){var r=r_("iframefcb");return $y()[r]=()=>{gapi.load?n():t(Rm(i,"network-request-failed"))},n_(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw $_=null,e})),$_}const z_=new Bm(5e3,15e3),G_="__/auth/iframe",H_="emulator/auth/iframe",Q_={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Y_=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function J_(o){const e=await W_(o);var t=$y().gapi;return Om(t,o,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;Om(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?Km(t,H_):`https://${e.config.authDomain}/${G_}`;const r={apiKey:t.apiKey,appName:e.name,v:Tf};(t=Y_.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${Cd(r).slice(1)}`}(o),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Q_,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=Rm(o,"network-request-failed"),r=$y().setTimeout(()=>{t(n)},z_.get());function i(){$y().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const X_={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Z_{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function ew(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-r)/2,0).toString();let a="";const c=Object.assign(Object.assign({},X_),{width:r.toString(),height:i.toString(),top:s,left:o});s=sd().toLowerCase();n&&(a=vv(s)?"_blank":n),gv(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,o=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=sd()]=[s],Iv(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",a),new Z_(null);const u=window.open(t||"",a,o);Om(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Z_(u)}const tw="__/auth/handler",nw="emulator/auth/handler";function rw(e,t,n,r,i,s){Om(e.config.authDomain,e,"auth-domain-config-required"),Om(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Tf,eventId:i};if(t instanceof Bv){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",Td(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(var[a,c]of Object.entries(s||{}))o[a]=c}if(t instanceof Kv){const u=t.getScopes().filter(e=>""!==e);0<u.length&&(o.scopes=u.join(","))}e.tenantId&&(o.tid=e.tenantId);const l=o;for(const h of Object.keys(l))void 0===l[h]&&delete l[h];return`${e=[e["config"]][0],e.emulator?Km(e,nw):`https://${e.authDomain}/${tw}`}?${Cd(l).slice(1)}`}const iw="webStorageSupport";const sw=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=jy,this._completeRedirectFn=D_}async _openPopup(e,t,n,r){var i;return Lm(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),ew(e,rw(e,t,n,qm(),r),By())}async _openRedirect(e,t,n,r){return await this._originValidation(e),r=rw(e,t,n,qm(),r),$y().location.href=r,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(Lm(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await J_(t),n=new M_(t);return e.register("authEvent",e=>{return Om(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(iw,{type:iw},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[iw];void 0!==t&&r(!!t),Nm(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=V_(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Tv()||mv()||Iv()}};class ow extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return Mm("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ow(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},Hm(e,"POST","/v2/accounts/mfaEnrollment:finalize",Gm(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},Hm(e,"POST","/v2/accounts/mfaSignIn:finalize",Gm(e,t))}}class aw{constructor(){}static assertion(e){return ow._fromCredential(e)}}aw.FACTOR_ID="phone";var cw,lw="@firebase/auth",uw="0.19.12";class hw{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null===e||void 0===e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){Om(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function dw(){return window}cw="Browser",_f(new Xd("auth",(e,{options:r})=>{var t=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");const{apiKey:i,authDomain:s}=t.options;return((e,t)=>{Om(i&&!i.includes(":"),"invalid-api-key",{appName:e.name}),Om(!(null!==s&&void 0!==s&&s.includes(":")),"argument-error",{appName:e.name});var n={apiKey:i,authDomain:s,clientPlatform:cw,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Ev(cw)},n=new Sv(e,t,n);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(Um);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(n,r),n})(t,n)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),_f(new Xd("auth-internal",e=>{var t=kv(e.getProvider("auth").getImmediate());return e=t,new hw(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),Cf(lw,uw,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(cw)),Cf(lw,uw,"esm2017");async function fw(e,t,n){var r=dw()["BuildInfo"];Lm(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(Lm(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return Iv()?s.ibi=r.packageName:_v()?s.apn=r.packageName:Nm(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,rw(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function pw(r){const i=dw()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=sd(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const gw=20;class mw extends M_{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function vw(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<gw;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:Rm(e,"no-auth-event")}}async function yw(e){var t=await ww()._get(bw(e));return t&&await ww()._remove(bw(e)),t}function _w(e,t){var n,r,i;const s=(n=Iw(t=t),o=n.link?decodeURIComponent(n.link):void 0,r=Iw(o).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=Iw(i).link)||i||r||o||t);if(s.includes("/__/auth/callback")){var o=Iw(s),o=o.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(o.firebaseError)):null,o=null===(o=null===(o=null==o?void 0:o.code)||void 0===o?void 0:o.split("auth/"))||void 0===o?void 0:o[1],o=o?Rm(o):null;return o?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:o,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function ww(){return Um(Uy)}function bw(e){return dv("authEvent",e.config.apiKey,e.name)}function Iw(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return Ad(t.join("?"))}const Tw=class{constructor(){this._redirectPersistence=jy,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=D_}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new mw(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){Nm(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,a=dw(),Om("function"==typeof(null===(s=null==a?void 0:a.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),Om(void 0!==(null===(s=null==a?void 0:a.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),Om("function"==typeof(null===(s=null===(s=null===(s=null==a?void 0:a.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),Om("function"==typeof(null===(s=null===(s=null===(s=null==a?void 0:a.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),Om("function"==typeof(null===(a=null===(a=null==a?void 0:a.cordova)||void 0===a?void 0:a.InAppBrowser)||void 0===a?void 0:a.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const o=await this._initialize(e);await o.initialized(),o.resetRedirect(),S_.clear(),await this._originValidation(e);var a=vw(e,n,r);n=e,r=a,await ww()._set(bw(n),r);a=await pw(await fw(e,a,t));return async function(o,a,c){const l=dw()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(Rm(o,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}a.addPassiveListener(r),document.addEventListener("resume",i,!1),_v()&&document.addEventListener("visibilitychange",s,!1),u=()=>{a.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,o,a)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=dw()["BuildInfo"];const n={};Iv()?n.iosBundleId=t.packageName:_v()?n.androidPackageName=t.packageName:Nm(e,"operation-not-supported-in-this-environment"),await U_(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=dw(),s=setTimeout(async()=>{await yw(r),i.onEvent(Ew())},500),o=async e=>{clearTimeout(s);var t=await yw(r);let n=null;t&&null!=e&&e.url&&(n=_w(t,e.url)),i.onEvent(n||Ew())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,o);const a=t,c=`${n.packageName.toLowerCase()}://`;dw().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&o({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}}}};function Ew(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Rm("no-auth-event")}}var Sw;function kw(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function Cw(e=sd()){return!("file:"!==kw()&&"ionic:"!==kw()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Aw(e=sd()){return ud()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=sd()]=[e],/Edge\/\d+/.test(e))}function Nw(){try{const t=self.localStorage;var e=By();if(t)return t.setItem(e,"1"),t.removeItem(e),!Aw()||dd()}catch(e){return Rw()&&dd()}return!1}function Rw(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function xw(){return("http:"===kw()||"https:"===kw()||cd()||Cw())&&!(ld()||ad())&&Nw()&&!Rw()}function Pw(){return Cw()&&"undefined"!=typeof document}const Dw={LOCAL:"local",NONE:"none",SESSION:"session"},Ow=Om,Mw="persistence";async function Lw(e){await e._initializationPromise;const t=Fw();var n=dv(Mw,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function Fw(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const Uw=Om;class qw{constructor(){this.browserResolver=Um(sw),this.cordovaResolver=Um(Tw),this.underlyingResolver=null,this._redirectPersistence=jy,this._completeRedirectFn=D_}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Pw()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Uw(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Pw()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function jw(e){return e.unwrap()}function Vw(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===t.code){const a=t;a.resolver=new Ww(e,(n=t,i=$d(e),Om((o=n).customData.operationType,i,"argument-error"),Om(null===(r=o.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Py._fromError(i,o)))}else if(s){var o=Bw(t);const c=t;o&&(c.credential=o,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Bw(e){var t=(e instanceof gd?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof gd)&&"temporaryProof"in t&&"phoneNumber"in t)return g_.credentialFromResult(e);const n=t.providerId;if(!n||n===bm.PASSWORD)return null;let r;switch(n){case bm.GOOGLE:r=zv;break;case bm.FACEBOOK:r=Wv;break;case bm.GITHUB:r=Gv;break;case bm.TWITTER:r=Yv;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:o,pendingToken:a,nonce:c}=t;return s||o||i||a?a?n.startsWith("saml.")?Hv._create(n,a):Fv._fromParams({providerId:n,signInMethod:n,pendingToken:a,idToken:i,accessToken:s}):new $v(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof gd?r.credentialFromError(e):r.credentialFromResult(e)}function Kw(t,e){return e.catch(e=>{throw e instanceof gd&&Vw(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Bw(e),additionalUserInfo:Ry(e),user:zw.getOrCreate(n)}})}async function $w(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>Kw(t,n.confirm(e))}}class Ww{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Kw(jw(this.auth),this.resolver.resolveSignIn(e))}}class zw{constructor(e){var t;this._delegate=e,this.multiFactor=(t=$d(e),Oy.has(t)||Oy.set(t,Dy._fromUser(t)),Oy.get(t))}static getOrCreate(e){return zw.USER_MAP.has(e)||zw.USER_MAP.set(e,new zw(e)),zw.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Kw(this.auth,ly(this._delegate,e))}async linkWithPhoneNumber(e,t){return $w(this.auth,async function(e,t,n){const r=$d(e);await sy(!1,r,"phone");var i=await p_(r.auth,t,$d(n));return new f_(i,e=>ly(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return Kw(this.auth,async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);var i=m_(r.auth,n);const s=new T_(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,qw))}async linkWithRedirect(e){return await Lw(kv(this.auth)),P_(this._delegate,e,qw)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Kw(this.auth,uy(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return $w(this.auth,async function(e,t,n){const r=$d(e);var i=await p_(r.auth,t,$d(n));return new f_(i,e=>uy(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return Kw(this.auth,async function(e,t,n){var r=$d(e);Pm(r.auth,t,Bv);var i=m_(r.auth,n);const s=new T_(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,qw))}async reauthenticateWithRedirect(e){return await Lw(kv(this.auth)),x_(this._delegate,e,qw)}sendEmailVerification(e){return wy(this._delegate,e)}async unlink(e){return await ry(this._delegate,e),this}updateEmail(e){return Ty($d(this._delegate),e,null)}updatePassword(e){return Ty($d(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await iy($d(e),t)}(this._delegate,e)}updateProfile(e){return Iy(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return by(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}zw.USER_MAP=new WeakMap;const Gw=Om;class Hw{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Gw(n,"invalid-api-key",{appName:e.name}),Gw(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?qw:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=Fw();if(!n)return[];var r=dv(Mw,e,t);switch(n.getItem(r)){case Dw.NONE:return[hv];case Dw.LOCAL:return[t_,jy];case Dw.SESSION:return[jy];default:return[]}}(e,t);"undefined"==typeof self||n.includes(t_)||n.push(t_);if("undefined"!=typeof window)for(const r of[Uy,jy])n.includes(r)||n.push(r);n.includes(hv)||n.push(hv);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(Em),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?zw.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){Av(this._delegate,e,t)}applyActionCode(e){return my(this._delegate,e)}checkActionCode(e){return vy(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await Pv($d(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Kw(this._delegate,async function(e,t,n){const r=kv(e);var i=await Jv(r,{returnSecureToken:!0,email:t,password:n}),i=await Xv._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(i.user),i}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return _y(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=jv.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Gw(xw(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=qw,await kv(e)._initializationPromise,await D_(e,t,!1));return n?Kw(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){kv(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=Qw(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=Qw(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return yy(this._delegate,e,t)}sendPasswordResetEmail(e,t){return gy(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Ow(Object.values(Dw).includes(n),t,"invalid-persistence-type"),ld()?Ow(n!==Dw.SESSION,t,"unsupported-persistence-type"):ad()?Ow(n===Dw.NONE,t,"unsupported-persistence-type"):Rw()?Ow(n===Dw.NONE||n===Dw.LOCAL&&dd(),t,"unsupported-persistence-type"):Ow(n===Dw.NONE||Nw(),t,"unsupported-persistence-type");let r;switch(e){case Dw.SESSION:r=jy;break;case Dw.LOCAL:var i=await Um(t_)._isAvailable();r=i?t_:Uy;break;case Dw.NONE:r=hv;break;default:return Nm("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Kw(this._delegate,async function(e){const t=kv(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Xv({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await Jv(t,{returnSecureToken:!0}),n=await Xv._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return Kw(this._delegate,cy(this._delegate,e))}signInWithCustomToken(e){return Kw(this._delegate,hy(this._delegate,e))}signInWithEmailAndPassword(e,t){return Kw(this._delegate,(n=this._delegate,e=e,t=t,cy($d(n),Vv.credential(e,t))));var n}signInWithEmailLink(e,t){return Kw(this._delegate,async function(e,t,n){var r=$d(e),i=Vv.credentialWithLink(t,n||qm());return Om(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),cy(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return $w(this._delegate,async function(e,t,n){const r=kv(e);var i=await p_(r,t,$d(n));return new f_(i,e=>cy(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Gw(xw(),this._delegate,"operation-not-supported-in-this-environment"),Kw(this._delegate,async function(e,t,n){var r=kv(e);Pm(e,t,Bv);var i=m_(r,n);const s=new T_(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,qw))}async signInWithRedirect(e){return Gw(xw(),this._delegate,"operation-not-supported-in-this-environment"),await Lw(this._delegate),R_(this._delegate,e,qw)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await vy($d(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function Qw(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&zw.getOrCreate(e)),error:t,complete:n}}Hw.Persistence=Dw;class Yw{constructor(){this.providerId="phone",this._delegate=new g_(jw(zf.auth()))}static credential(e,t){return g_.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Yw.PHONE_SIGN_IN_METHOD=g_.PHONE_SIGN_IN_METHOD,Yw.PROVIDER_ID=g_.PROVIDER_ID;const Jw=Om;class Xw{constructor(e,t,n=zf.app()){var r;Jw(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new d_(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(Sw=zf).INTERNAL.registerComponent(new Xd("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new Hw(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:Im.EMAIL_SIGNIN,PASSWORD_RESET:Im.PASSWORD_RESET,RECOVER_EMAIL:Im.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:Im.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:Im.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:Im.VERIFY_EMAIL}},EmailAuthProvider:Vv,FacebookAuthProvider:Wv,GithubAuthProvider:Gv,GoogleAuthProvider:zv,OAuthProvider:$v,SAMLAuthProvider:Qv,PhoneAuthProvider:Yw,PhoneMultiFactorGenerator:aw,RecaptchaVerifier:Xw,TwitterAuthProvider:Yv,Auth:Hw,AuthCredential:xv,Error:gd}).setInstantiationMode("LAZY").setMultipleInstances(!1)),Sw.registerVersion("@firebase/auth-compat","0.2.12");const Zw="@firebase/database";let eb="";function tb(e){eb=e}class nb{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),_d(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:yd(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class rb{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return bd(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var ib,sb,ob,ab,cb,lb,yt=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new nb(t)}}catch(e){}return new rb};function ub(e){var t=function(t){const n=[];let r=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);var i,s;55296<=e&&e<=56319&&(i=e-55296,o++,Yh(o<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(o)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new Rd;return n.update(t),t=n.digest(),Zh.encodeByteArray(t)}const hb=yt("localStorage"),db=yt("sessionStorage"),fb=new cf("@firebase/database"),pb=function(){let e=1;return function(){return e++}}(),gb=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=gb.apply(null,n):t+="object"==typeof n?_d(n):n,t+=" "}return t};let mb=null,vb=!0;function yb(t){return function(...e){Sb(t,...e)}}function _b(...e){var t="FIREBASE INTERNAL ERROR: "+gb(...e);fb.error(t)}function wb(e,t){return e===t?0:e<t?-1:1}function bb(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+_d(t))}function Ib(e){if("object"!=typeof e||null===e)return _d(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=_d(t[i]),n+=":",n+=Ib(e[t[i]]);return n+="}",n}function Tb(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const Eb=function(e,t){Yh(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(fb.logLevel=$h.VERBOSE,mb=fb.log.bind(fb),t&&db.set("logging_enabled",!0)):"function"==typeof e?mb=e:(mb=null,db.remove("logging_enabled"))},Sb=function(...e){var t;!0===vb&&(vb=!1,null===mb&&!0===db.get("logging_enabled")&&Eb(!0)),mb&&(t=gb.apply(null,e),mb(t))},kb=function(...e){var t=`FIREBASE FATAL ERROR: ${gb(...e)}`;throw fb.error(t),new Error(t)},Cb=function(...e){var t="FIREBASE WARNING: "+gb(...e);fb.warn(t)},Ab=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Cb("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Nb=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},Rb="[MIN_NAME]",xb="[MAX_NAME]",Pb=function(e,t){if(e===t)return 0;if(e===Rb||t===xb)return-1;if(t===Rb||e===xb)return 1;var n=qb(e),r=qb(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Db(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Ob(e){Yh(!Nb(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();const a=o.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function Mb(e,t){const n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}const Lb=new RegExp("^-?(0*)\\d{1,10}$"),Fb=-2147483648,Ub=2147483647,qb=function(e){if(Lb.test(e)){var t=Number(e);if(t>=Fb&&t<=Ub)return t}return null},jb=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw Cb("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Vb{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(e=>this.appCheck=e)}getToken(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){Cb(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Bb{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(Sb("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Cb(e)}}class Kb{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Kb.OWNER="owner";const $b=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Wb="websocket",zb="long_polling";class Gb{constructor(e,t,n,r,i=!1,s="",o=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=hb.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&hb.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function Hb(e,t,n){Yh("string"==typeof t,"typeof type must == string"),Yh("object"==typeof n,"typeof params must == object");let r;if(t===Wb)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==zb)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return Db(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class Qb{constructor(){this.counters_={}}incrementCounter(e,t=1){bd(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return nd(void 0,this.counters_)}}const Yb={},Jb={};function Xb(e){var t=e.toString();return Yb[t]||(Yb[t]=new Qb),Yb[t]}class Zb{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&jb(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class eI{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=yb(e),this.stats_=Xb(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Hb(t,zb,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Zb(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new tI((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&$b.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){eI.forceAllow_=!0}static forceDisallow(){eI.forceDisallow_=!0}static isAvailable(){return!!eI.forceAllow_||!(eI.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=_d(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=Hh(t),n=Tb(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=_d(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class tI{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=pb(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=tI.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){Sb("frame writing exception"),e.stack&&Sb(e.stack),Sb(e)}}}static createIFrame_(){const t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||Sb("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{Sb("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let nI=null;"undefined"!=typeof MozWebSocket?nI=MozWebSocket:"undefined"!=typeof WebSocket&&(nI=WebSocket);class rI{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=yb(this.connId),this.stats_=Xb(t),this.connURL=rI.connectionURL_(t,s,o,r),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r){const i={v:"5"};return"undefined"!=typeof location&&location.hostname&&$b.test(location.hostname)&&(i.r="f"),t&&(i.s=t),n&&(i.ls=n),r&&(i.ac=r),Hb(e,Wb,i)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,hb.set("previous_websocket_failure",!0);try{hd()||(n={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}},this.mySock=new nI(this.connURL,[],n))}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){rI.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==nI&&!rI.forceDisallow_}static previouslyFailed(){return hb.isInMemoryStorage||!0===hb.get("previous_websocket_failure")}markConnectionHealthy(){hb.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=yd(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(Yh(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=_d(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=Tb(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}rI.responsesRequiredToBeHealthy=2,rI.healthyTimeout=3e4;class iI{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[eI,rI]}initTransports_(e){var t=rI&&rI.isAvailable();let n=t&&!rI.previouslyFailed();if(e.webSocketOnly&&(t||Cb("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[rI];else{const r=this.transports_=[];for(const i of iI.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i)}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}class sI{constructor(e,t,n,r,i,s,o,a,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=yb("c:"+this.id+":"),this.transportManager_=new iI(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=Mb(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){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)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=bb("t",e),n=bb("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){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:{}}}))}proceedWithUpgrade_(){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()}onPrimaryMessageReceived_(e){var t=bb("t",e),n=bb("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=bb("t",e);if("d"in e){var n=e.d;if("h"===t)this.onHandshake_(n);else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?_b("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):_b("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&Cb("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Mb(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Mb(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(hb.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class oI{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class aI{constructor(e){this.allowedEvents_=e,this.listeners_={},Yh(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){Yh(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class cI extends aI{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||od()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new cI}getInitialEvent(e){return Yh("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class lI{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function uI(){return new lI("")}function hI(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function dI(e){return e.pieces_.length-e.pieceNum_}function fI(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new lI(e.pieces_,t)}function pI(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function gI(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function mI(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new lI(t,0)}function vI(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof lI)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new lI(n,0)}function yI(e){return e.pieceNum_>=e.pieces_.length}function _I(e,t){var n=hI(e),r=hI(t);if(null===n)return t;if(n===r)return _I(fI(e),fI(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function wI(e,t){var n=gI(e,0),r=gI(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Pb(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function bI(e,t){if(dI(e)!==dI(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function II(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(dI(e)>dI(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class TI{constructor(e,t){this.errorPrefix_=t,this.parts_=gI(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=Ud(this.parts_[n]);EI(this)}}function EI(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+SI(e))}function SI(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class kI extends aI{constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}static getInstance(){return new kI}getInitialEvent(e){return Yh("visible"===e,"Unknown event type: "+e),[this.visible_]}}class CI extends oI{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=CI.nextPersistentConnectionId_++,this.log_=yb("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!hd())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");kI.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&cI.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(_d(i)),Yh(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new rd,r={p:e._path.toString(),q:e._queryObject},t={action:"g",request:r,onComplete:e=>{var t=e.d;"ok"===e.s?(this.onDataUpdate_(r.p,t,!1,null),n.resolve(t)):n.reject(t)}};this.outstandingGets_.push(t),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_||setTimeout(()=>{var e=this.outstandingGets_[i];void 0!==e&&t===e&&(delete this.outstandingGets_[i],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),this.log_("get "+i+" timed out on connection"),n.reject(new Error("Client is offline.")))},3e3),this.connected_&&this.sendGet_(i),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),Yh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Yh(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var o={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),o=i._queryIdentifier;this.log_("Listen on "+s+" for "+o);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;CI.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(o))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,o),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&bd(e,"w")){const i=Id(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),Cb("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} to your security rules for better performance.`))}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=wd(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const r=this.authToken_;var e=function(e){const t=wd(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),Yh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+_d(e));var t=e.r;const n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):_b("Unrecognized action received from server: "+_d(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){Yh(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-e),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)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+CI.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var o=function(){n?n.close():(t=!0,u())};this.realtime_={close:o,sendRequest:function(e){Yh(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var a=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(a),this.appCheckTokenProvider_.getToken(a)]);t?Sb("getToken() completed but was canceled"):(Sb("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new sI(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{Cb(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&Cb(e),o())}}}interrupt(e){Sb("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){Sb("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Td(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>Ib(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new lI(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){Sb("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){Sb("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+eb.replace(/\./g,"-")]=1,od()?e["framework.cordova"]=1:ld()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=cI.getInstance().currentlyOnline();return Td(this.interruptReasons_)&&e}}CI.nextPersistentConnectionId_=0,CI.nextConnectionId_=0;class AI{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new AI(e,t)}}class NI{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new AI(Rb,e),r=new AI(Rb,t);return 0!==this.compare(n,r)}minPost(){return AI.MIN}}let RI;class xI extends NI{static get __EMPTY_NODE(){return RI}static set __EMPTY_NODE(e){RI=e}compare(e,t){return Pb(e.name,t.name)}isDefinedOn(e){throw Jh("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return AI.MIN}maxPost(){return new AI(xb,RI)}makePost(e,t){return Yh("string"==typeof e,"KeyIndex indexValue must always be a string."),new AI(e,RI)}toString(){return".key"}}const PI=new xI;class DI{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class OI{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:OI.RED,this.left=null!=r?r:MI.EMPTY_NODE,this.right=null!=i?i:MI.EMPTY_NODE}copy(e,t,n,r,i){return new OI(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return MI.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return MI.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(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,OI.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,OI.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){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");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}OI.RED=!0,OI.BLACK=!1;class MI{constructor(e,t=MI.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new MI(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,OI.BLACK,null,null))}remove(e){return new MI(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,OI.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new DI(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new DI(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new DI(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new DI(this.root_,null,this.comparator_,!0,e)}}function LI(e,t){return Pb(e.name,t.name)}function FI(e,t){return Pb(e,t)}MI.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new OI(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let UI;function qI(e){return"number"==typeof e?"number:"+Ob(e):"string:"+e}function jI(e){var t;e.isLeafNode()?(t=e.val(),Yh("string"==typeof t||"number"==typeof t||"object"==typeof t&&bd(t,".sv"),"Priority must be a string or number.")):Yh(e===UI||e.isEmpty(),"priority of unexpected type."),Yh(e===UI||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let VI;class BI{constructor(e,t=BI.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,Yh(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),jI(this.priorityNode_)}static set __childrenNodeConstructor(e){VI=e}static get __childrenNodeConstructor(){return VI}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new BI(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:BI.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return yI(e)?this:".priority"===hI(e)?this.priorityNode_:BI.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:BI.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=hI(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(Yh(".priority"!==n||1===dI(e),".priority must be the last token in a path"),this.updateImmediateChild(n,BI.__childrenNodeConstructor.EMPTY_NODE.updateChild(fI(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+qI(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Ob(this.value_):this.value_,this.lazyHash_=ub(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===BI.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof BI.__childrenNodeConstructor?-1:(Yh(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=BI.VALUE_TYPE_ORDER.indexOf(t),i=BI.VALUE_TYPE_ORDER.indexOf(n);return Yh(0<=r,"Unknown leaf type: "+t),Yh(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}BI.VALUE_TYPE_ORDER=["object","boolean","number","string"];let KI,$I;const WI=new class extends NI{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Pb(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return AI.MIN}maxPost(){return new AI(xb,new BI("[PRIORITY-POST]",$I))}makePost(e,t){var n=KI(e);return new AI(t,new BI("[PRIORITY-POST]",n))}toString(){return".priority"}},zI=Math.log(2);class GI{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/zI,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function HI(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new OI(i,r.node,OI.BLACK,null,null);var s=parseInt(n/2,10)+e,o=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new OI(i,r.node,OI.BLACK,o,n)};var n=function(e){let s=null,o=null,a=c.length;function t(e,t){var n=a-e,r=a;a-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{o=e;s=e}}(new OI(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,OI.BLACK):(t(r,OI.BLACK),t(r,OI.RED))}return o}(new GI(c.length));return new MI(t||e,n)}let QI;const YI={};class JI{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return Yh((YI,WI),"ChildrenNode.ts has not been loaded"),QI=QI||new JI({".priority":YI},{".priority":WI}),QI}get(e){var t=Id(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof MI?t:null}hasIndex(e){return bd(this.indexSet_,e.toString())}addIndex(e,t){Yh(e!==PI,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(AI.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?HI(n,e.getCompare()):YI;var a=e.toString();const c=Object.assign({},this.indexSet_);c[a]=e;const l=Object.assign({},this.indexes_);return l[a]=o,new JI(l,c)}addToIndexes(o,a){var e=Ed(this.indexes_,(t,e)=>{const n=Id(this.indexSet_,e);if(Yh(n,"Missing index implementation for "+e),t===YI){if(n.isDefinedOn(o.node)){const i=[],s=a.getIterator(AI.Wrap);let e=s.getNext();for(;e;)e.name!==o.name&&i.push(e),e=s.getNext();return i.push(o),HI(i,n.getCompare())}return YI}{var r=a.get(o.name);let e=t;return r&&(e=e.remove(new AI(o.name,r))),e.insert(o,o.node)}});return new JI(e,this.indexSet_)}removeFromIndexes(n,r){var e=Ed(this.indexes_,e=>{if(e===YI)return e;var t=r.get(n.name);return t?e.remove(new AI(n.name,t)):e});return new JI(e,this.indexSet_)}}let XI;class ZI{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&jI(this.priorityNode_),this.children_.isEmpty()&&Yh(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return XI=XI||new ZI(new MI(FI),null,JI.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||XI}updatePriority(e){return this.children_.isEmpty()?this:new ZI(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?XI:t}getChild(e){var t=hI(e);return null===t?this:this.getImmediateChild(t).getChild(fI(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(Yh(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new AI(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?XI:this.priorityNode_;return new ZI(e,i,t)}}updateChild(e,t){var n=hI(e);if(null===n)return t;Yh(".priority"!==hI(e)||1===dI(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(fI(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,o=!0;if(this.forEachChild(WI,(e,t)=>{r[e]=t.val(n),i++,o&&ZI.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):o=!1}),!n&&o&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+qI(this.getPriority().val())+":"),this.forEachChild(WI,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":ub(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new AI(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new AI(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new AI(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,AI.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,AI.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===t0?-1:0}withIndex(e){if(e===PI||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new ZI(this.children_,this.priorityNode_,t)}isIndexed(e){return e===PI||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(WI),i=n.getIterator(WI);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===PI?null:this.indexMap_.get(e.toString())}}ZI.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class e0 extends ZI{constructor(){super(new MI(FI),ZI.EMPTY_NODE,JI.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ZI.EMPTY_NODE}isEmpty(){return!1}}const t0=new e0;Object.defineProperties(AI,{MIN:{value:new AI(Rb,ZI.EMPTY_NODE)},MAX:{value:new AI(xb,t0)}}),xI.__EMPTY_NODE=ZI.EMPTY_NODE,BI.__childrenNodeConstructor=ZI,ib=t0,UI=ib,sb=t0,$I=sb;const n0=!0;function r0(i,e=null){if(null===i)return ZI.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),Yh(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new BI(t,r0(e))}if(i instanceof Array||!n0){let r=ZI.EMPTY_NODE;return Db(i,(e,t)=>{if(bd(i,e)&&"."!==e.substring(0,1)){const n=r0(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(r0(e))}{const s=[];let r=!1;if(Db(i,(e,t)=>{if("."!==e.substring(0,1)){const n=r0(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new AI(e,n)))}}),0===s.length)return ZI.EMPTY_NODE;var n=HI(s,LI,e=>e.name,FI);if(r){t=HI(s,WI.getCompare());return new ZI(n,r0(e),new JI({".priority":t},{".priority":WI}))}return new ZI(n,r0(e),JI.Default)}}KI=r0;class i0 extends NI{constructor(e){super(),this.indexPath_=e,Yh(!yI(e)&&".priority"!==hI(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?Pb(e.name,t.name):r}makePost(e,t){var n=r0(e),n=ZI.EMPTY_NODE.updateChild(this.indexPath_,n);return new AI(t,n)}maxPost(){var e=ZI.EMPTY_NODE.updateChild(this.indexPath_,t0);return new AI(xb,e)}toString(){return gI(this.indexPath_,0).join("/")}}function s0(e){if(e===""+Ub)return l0;var t=qb(e);if(null!=t)return""+(t+1);const n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e.charAt(i);if(n.length<h0)return n.push(l0),n.join("");let r=n.length-1;for(;0<=r&&n[r]===u0;)r--;return-1===r?xb:(t=n[r],t=c0.charAt(c0.indexOf(t)+1),n[r]=t,n.slice(0,r+1).join(""))}function o0(e){if(e===""+Fb)return Rb;var t=qb(e);if(null!=t)return""+(t-1);const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e.charAt(r);return n[n.length-1]===l0?1===n.length?""+Ub:(delete n[n.length-1],n.join("")):(n[n.length-1]=c0.charAt(c0.indexOf(n[n.length-1])-1),n.join("")+u0.repeat(h0-n.length))}const a0=new class extends NI{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Pb(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return AI.MIN}maxPost(){return AI.MAX}makePost(e,t){var n=r0(e);return new AI(t,n)}toString(){return".value"}},c0="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",l0="-",u0="z",h0=786,d0=function(){let s=0;const o=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=c0.charAt(e%64),e=Math.floor(e/64);Yh(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===o[n];n--)o[n]=0;o[n]++}else for(n=0;n<12;n++)o[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=c0.charAt(o[n]);return Yh(20===i.length,"nextPushId: Length should be 20."),i}}();function f0(e){return{type:"value",snapshotNode:e}}function p0(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function g0(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function m0(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class v0{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){Yh(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(g0(t,o)):Yh(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(p0(t,n)):s.trackChildChange(m0(t,n,o))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(WI,(e,t)=>{n.hasChild(e)||i.trackChildChange(g0(e,t))}),n.isLeafNode()||n.forEachChild(WI,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(m0(e,t,n))}else i.trackChildChange(p0(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ZI.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class y0{constructor(e){this.indexedFilter_=new v0(e.getIndex()),this.index_=e.getIndex(),this.startPost_=y0.getStartPost_(e),this.endPost_=y0.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0}updateChild(e,t,n,r,i,s){return this.matches(new AI(t,n))||(n=ZI.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?ZI.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(ZI.EMPTY_NODE);const i=this;return t.forEachChild(WI,(e,t)=>{i.matches(new AI(e,t))||(r=r.updateImmediateChild(e,ZI.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class _0{constructor(e){this.rangedFilter_=new y0(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new AI(t,n))||(n=ZI.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,o,t){let a;if(o.isLeafNode()||o.isEmpty())a=ZI.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<o.numChildren()&&o.isIndexed(this.index_)){a=ZI.EMPTY_NODE.withIndex(this.index_);let t;t=this.reverse_?o.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):o.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;t.hasNext()&&n<this.limit_;){var r=t.getNext();let e;if(e=this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),r)<=0:this.index_.compare(r,this.rangedFilter_.getEndPost())<=0,!e)break;a=a.updateImmediateChild(r.name,r.node),n++}}else{a=o.withIndex(this.index_),a=a.updatePriority(ZI.EMPTY_NODE);let e,t,n,r;if(this.reverse_){r=a.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),t=this.rangedFilter_.getStartPost();const l=this.index_.getCompare();n=(e,t)=>l(t,e)}else r=a.getIterator(this.index_),e=this.rangedFilter_.getStartPost(),t=this.rangedFilter_.getEndPost(),n=this.index_.getCompare();let i=0,s=!1;for(;r.hasNext();){var c=r.getNext();!s&&n(e,c)<=0&&(s=!0),s&&i<this.limit_&&n(c,t)<=0?i++:a=a.updateImmediateChild(c.name,ZI.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,a,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const o=e;Yh(o.numChildren()===this.limit_,"");var a=new AI(t,n),c=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),l=this.rangedFilter_.matches(a);if(o.hasChild(t)){var u=o.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||o.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,a);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(m0(t,n,u)),o.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(g0(t,u));const f=o.updateImmediateChild(t,ZI.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(p0(e.name,e.node)),f.updateImmediateChild(e.name,e.node)):f}}return!n.isEmpty()&&l&&0<=s(c,a)?(null!=i&&(i.trackChildChange(g0(c.name,c.node)),i.trackChildChange(p0(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,ZI.EMPTY_NODE)):e}}class w0{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=WI}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return Yh(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Yh(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Rb}hasEnd(){return this.endSet_}getIndexEndValue(){return Yh(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Yh(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:xb}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return Yh(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===WI}copy(){const e=new w0;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}}function b0(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function I0(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function T0(e,t){const n=e.copy();return n.index_=t,n}function E0(e){const t={};if(e.isDefault())return t;let n;return n=e.index_===WI?"$priority":e.index_===a0?"$value":e.index_===PI?"$key":(Yh(e.index_ instanceof i0,"Unrecognized index type!"),e.index_.toString()),t.orderBy=_d(n),e.startSet_&&(t.startAt=_d(e.indexStartValue_),e.startNameSet_&&(t.startAt+=","+_d(e.indexStartName_))),e.endSet_&&(t.endAt=_d(e.indexEndValue_),e.endNameSet_&&(t.endAt+=","+_d(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function S0(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_)),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_)),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==WI&&(n.i=t.index_.toString()),n}class k0 extends oI{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=yb("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(Yh(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const o=k0.getListenId_(e,r),a={};this.listens_[o]=a;var n=E0(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),Id(this.listens_,o)===a){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=k0.getListenId_(e,t);delete this.listens_[n]}get(e){var t=E0(e._queryParams);const r=e._path.toString(),i=new rd;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},o){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+Cd(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(o&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=yd(r.responseText)}catch(e){Cb("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&Cb("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class C0{constructor(){this.rootNode_=ZI.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function A0(){return{value:null,children:new Map}}function N0(e,t,n){var r;yI(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=hI(t),e.children.has(r)||e.children.set(r,A0()),N0(e.children.get(r),t=fI(t),n))}function R0(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{R0(t,new lI(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class x0{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&Db(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class P0{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new x0(e);var n=1e4+2e4*Math.random();Mb(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Db(e,(e,t)=>{0<t&&bd(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Mb(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function D0(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function O0(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function M0(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(z=ob=ob||{})[z.OVERWRITE=0]="OVERWRITE",z[z.MERGE=1]="MERGE",z[z.ACK_USER_WRITE=2]="ACK_USER_WRITE",z[z.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class L0{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=ob.ACK_USER_WRITE,this.source=D0()}operationForChild(e){if(yI(this.path)){if(null!=this.affectedTree.value)return Yh(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new lI(e));return new L0(uI(),t,this.revert)}return Yh(hI(this.path)===e,"operationForChild called for unrelated child."),new L0(fI(this.path),this.affectedTree,this.revert)}}class F0{constructor(e,t){this.source=e,this.path=t,this.type=ob.LISTEN_COMPLETE}operationForChild(e){return yI(this.path)?new F0(this.source,uI()):new F0(this.source,fI(this.path))}}class U0{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=ob.OVERWRITE}operationForChild(e){return yI(this.path)?new U0(this.source,uI(),this.snap.getImmediateChild(e)):new U0(this.source,fI(this.path),this.snap)}}class q0{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=ob.MERGE}operationForChild(e){if(yI(this.path)){const t=this.children.subtree(new lI(e));return t.isEmpty()?null:t.value?new U0(this.source,uI(),t.value):new q0(this.source,uI(),t)}return Yh(hI(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new q0(this.source,fI(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class j0{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(yI(e))return this.isFullyInitialized()&&!this.filtered_;var t=hI(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class V0{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function B0(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),K0(n,i,"child_removed",e,r,t),K0(n,i,"child_added",e,r,t),K0(n,i,"child_moved",s,r,t),K0(n,i,"child_changed",e,r,t),K0(n,i,"value",e,r,t),i}function K0(s,o,t,e,a,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw Jh("Should only compare child_ events.");var r=new AI(t.childName,t.snapshotNode),i=new AI(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;a.forEach(e=>{e.respondsTo(t.type)&&o.push(e.createEvent(n,s.query_))})})}function $0(e,t){return{eventCache:e,serverCache:t}}function W0(e,t,n,r){return $0(new j0(t,n,r),e.serverCache)}function z0(e,t,n,r){return $0(e.eventCache,new j0(t,n,r))}function G0(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function H0(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Q0;class Y0{constructor(e,t=(Q0=Q0||new MI(wb),Q0)){this.value=e,this.children=t}static fromObject(e){let n=new Y0(null);return Db(e,(e,t)=>{n=n.set(new lI(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:uI(),value:this.value};if(yI(e))return null;{var n=hI(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(fI(e),t);return null==r?null:{path:vI(new lI(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(yI(e))return this;{var t=hI(e);const n=this.children.get(t);return null!==n?n.subtree(fI(e)):new Y0(null)}}set(e,t){if(yI(e))return new Y0(t,this.children);{var n=hI(e);const i=this.children.get(n)||new Y0(null);var r=i.set(fI(e),t),r=this.children.insert(n,r);return new Y0(this.value,r)}}remove(t){if(yI(t))return this.children.isEmpty()?new Y0(null):new Y0(null,this.children);{var n=hI(t);const r=this.children.get(n);if(r){const i=r.remove(fI(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new Y0(null):new Y0(this.value,e)}return this}}get(e){if(yI(e))return this.value;{var t=hI(e);const n=this.children.get(t);return n?n.get(fI(e)):null}}setTree(t,n){if(yI(t))return n;{var r=hI(t);const i=this.children.get(r)||new Y0(null),s=i.setTree(fI(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new Y0(this.value,e)}}fold(e){return this.fold_(uI(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(vI(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,uI(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(yI(e))return null;{r=hI(e);const i=this.children.get(r);return i?i.findOnPath_(fI(e),vI(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,uI(),t)}foreachOnPath_(e,t,n){if(yI(e))return this;{this.value&&n(t,this.value);var r=hI(e);const i=this.children.get(r);return i?i.foreachOnPath_(fI(e),vI(t,r),n):new Y0(null)}}foreach(e){this.foreach_(uI(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(vI(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class J0{constructor(e){this.writeTree_=e}static empty(){return new J0(new Y0(null))}}function X0(t,n,r){if(yI(n))return new J0(new Y0(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=_I(s,n);return e=e.updateChild(i,r),new J0(t.writeTree_.set(s,e))}s=new Y0(r),s=t.writeTree_.setTree(n,s);return new J0(s)}function Z0(e,n,t){let r=e;return Db(t,(e,t)=>{r=X0(r,vI(n,e),t)}),r}function eT(e,t){if(yI(t))return J0.empty();var n=e.writeTree_.setTree(t,new Y0(null));return new J0(n)}function tT(e,t){return null!=nT(e,t)}function nT(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(_I(n.path,t)):null}function rT(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(WI,(e,t)=>{n.push(new AI(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new AI(e,t.value))}),n}function iT(e,t){if(yI(t))return e;var n=nT(e,t);return null!=n?new J0(new Y0(n)):new J0(e.writeTree_.subtree(t))}function sT(e){return e.writeTree_.isEmpty()}function oT(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(Yh(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(vI(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(vI(i,".priority"),n):s}}}(uI(),e.writeTree_,t)}function aT(e,t){return _T(t,e)}function cT(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);Yh(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,o=!1,a=t.allWrites.length-1;for(;s&&0<=a;){var c=t.allWrites[a];c.visible&&(a>=r&&function(e,t){{if(e.snap)return II(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&II(vI(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:II(i.path,c.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=uT(e.allWrites,lT,uI()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=eT(t.visibleWrites,i.path):Db(i.children,e=>{t.visibleWrites=eT(t.visibleWrites,vI(i.path,e))}),!0)}function lT(e){return e.visible}function uT(e,t,n){let r=J0.empty();for(let s=0;s<e.length;++s){const o=e[s];if(t(o)){var i=o.path;let e;if(o.snap)II(n,i)?(e=_I(n,i),r=X0(r,e,o.snap)):II(i,n)&&(e=_I(i,n),r=X0(r,uI(),o.snap.getChild(e)));else{if(!o.children)throw Jh("WriteRecord should have .snap or .children");if(II(n,i))e=_I(n,i),r=Z0(r,e,o.children);else if(II(i,n))if(e=_I(i,n),yI(e))r=Z0(r,uI(),o.children);else{const a=Id(o.children,hI(e));a&&(i=a.getChild(fI(e)),r=X0(r,uI(),i))}}}}return r}function hT(e,t,n,r,i){if(r||i){var s=iT(e.visibleWrites,t);if(!i&&sT(s))return n;if(i||null!=n||tT(s,uI()))return oT(uT(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(II(e.path,t)||II(t,e.path))},t),n||ZI.EMPTY_NODE);return null}s=nT(e.visibleWrites,t);if(null!=s)return s;s=iT(e.visibleWrites,t);return sT(s)?n:null!=n||tT(s,uI())?oT(s,n||ZI.EMPTY_NODE):null}function dT(e,t,n,r){return hT(e.writeTree,e.treePath,t,n,r)}function fT(e,t){return function(e,t,n){let r=ZI.EMPTY_NODE;const i=nT(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(WI,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=iT(e.visibleWrites,t);return n.forEachChild(WI,(e,t)=>{var n=oT(iT(s,new lI(e)),t);r=r.updateImmediateChild(e,n)}),rT(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return rT(iT(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function pT(e,t,n,r){return function(e,t,n,r,i){Yh(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=vI(t,n);return tT(e.visibleWrites,s)?null:sT(s=iT(e.visibleWrites,s))?i.getChild(n):oT(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function gT(e,t){return n=e.writeTree,t=vI(e.treePath,t),nT(n.visibleWrites,t);var n}function mT(e,t,n,r,i,s){return function(e,t,n,r,i,s,o){let a;var c=iT(e.visibleWrites,t),l=nT(c,uI());if(null!=l)a=l;else{if(null==n)return[];a=oT(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const u=[],h=o.getCompare(),d=s?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function vT(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=vI(e,t=t),null!=(s=nT(r.visibleWrites,i))?s:n.isCompleteForChild(t)?oT(iT(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function yT(e,t){return _T(vI(e.treePath,t),e.writeTree)}function _T(e,t){return{treePath:e,writeTree:t}}class wT{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;Yh("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),Yh(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,m0(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,g0(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,p0(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw Jh("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,m0(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const bT=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class IT{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new j0(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return vT(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:H0(this.viewCache_),r=mT(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function TT(e,t,n,r,i){const s=new wT;let o,a;if(n.type===ob.OVERWRITE){var c=n;o=c.source.fromUser?kT(e,t,c.path,c.snap,r,i,s):(Yh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered()&&!yI(c.path),ST(e,t,c.path,c.snap,r,i,a,s))}else if(n.type===ob.MERGE){c=n;o=c.source.fromUser?function(r,i,s,e,o,a,c){let l=i;return e.foreach((e,t)=>{var n=vI(s,e);CT(i,hI(n))&&(l=kT(r,l,n,t,o,a,c))}),e.foreach((e,t)=>{var n=vI(s,e);CT(i,hI(n))||(l=kT(r,l,n,t,o,a,c))}),l}(e,t,c.path,c.children,r,i,s):(Yh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered(),NT(e,t,c.path,c.children,r,i,a,s))}else if(n.type===ob.ACK_USER_WRITE){var l=n;o=l.revert?function(n,r,i,s,e,o){let a;{if(null!=gT(s,i))return r;{var c=new IT(s,r,e);const u=r.eventCache.getNode();let t;if(yI(i)||".priority"===hI(i)){let e;e=r.serverCache.isFullyInitialized()?dT(s,H0(r)):(l=r.serverCache.getNode(),Yh(l instanceof ZI,"serverChildren would be complete if leaf node"),fT(s,l)),e=e,t=n.filter.updateFullNode(u,e,o)}else{var l=hI(i);let e=vT(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,fI(i),c,o):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,ZI.EMPTY_NODE,fI(i),c,o):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(a=dT(s,H0(r)),a.isLeafNode()&&(t=n.filter.updateFullNode(t,a,o)))}return a=r.serverCache.isFullyInitialized()||null!=gT(s,uI()),W0(r,t,a,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,o,a){if(null!=gT(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(yI(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return ST(e,t,i,l.getNode().getChild(i),s,o,c,a);if(yI(i)){let n=new Y0(null);return l.getNode().forEachChild(PI,(e,t)=>{n=n.set(new lI(e),t)}),NT(e,t,i,n,s,o,c,a)}return t}{let r=new Y0(null);return n.foreach((e,t)=>{var n=vI(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),NT(e,t,i,r,s,o,c,a)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==ob.LISTEN_COMPLETE)throw Jh("Unknown operation type: "+n.type);o=function(e,t,n,r,i){const s=t.serverCache,o=z0(t,s.getNode(),s.isFullyInitialized()||yI(n),s.isFiltered());return ET(e,o,n,r,bT,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=G0(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(f0(G0(t)))}}(t,o,l),{viewCache:o,changes:l}}function ET(r,i,s,o,a,c){const l=i.eventCache;if(null!=gT(o,s))return i;{let t,n;if(yI(s)){var e;Yh(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=fT(o,(e=H0(i))instanceof ZI?e:ZI.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=dT(o,H0(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=hI(s);if(".priority"===u){Yh(1===dI(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=pT(o,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=fI(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=pT(o,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):vT(o,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,a,c):l.getNode()}}return W0(i,t,l.isFullyInitialized()||yI(s),r.filter.filtersNodes())}}function ST(e,t,n,r,i,s,o,a){const c=t.serverCache;let l;const u=o?e.filter:e.filter.getIndexedFilter();if(yI(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=hI(n);if(!c.isCompleteForPath(n)&&1<dI(n))return t;var f=fI(n);const p=c.getNode().getImmediateChild(d);h=p.updateChild(f,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,f,bT,null)}f=z0(t,l,c.isFullyInitialized()||yI(n),u.filtersNodes());return ET(e,f,n,i,new IT(i,f,s),a)}function kT(t,n,r,i,e,s,o){const a=n.eventCache;let c,l;const u=new IT(e,n,s);if(yI(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,o),c=W0(n,l,!0,t.filter.filtersNodes());else{var h=hI(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=W0(n,l,a.isFullyInitialized(),a.isFiltered());else{var d=fI(r);const f=a.getNode().getImmediateChild(h);let e;if(yI(d))e=i;else{const p=u.getCompleteChild(h);e=null!=p?".priority"===pI(d)&&p.getChild(mI(d)).isEmpty()?p:p.updateChild(d,i):ZI.EMPTY_NODE}c=f.equals(e)?n:W0(n,t.filter.updateChild(a.getNode(),h,e,d,u,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return c}function CT(e,t){return e.eventCache.isCompleteForChild(t)}function AT(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function NT(r,i,e,t,s,o,a,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=yI(e)?t:new Y0(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=AT(0,i.serverCache.getNode().getImmediateChild(e),t),l=ST(r,l,new lI(e),n,s,o,a,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&void 0===t.value;u.hasChild(e)||n||(n=AT(0,i.serverCache.getNode().getImmediateChild(e),t),l=ST(r,l,new lI(e),n,s,o,a,c))}),l}class RT{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new v0(n.getIndex()),i=(e=n).loadsAllData()?new v0(e.getIndex()):new(e.hasLimit()?_0:y0)(e);this.processor_={filter:i};const s=t.serverCache,o=t.eventCache;var a=r.updateFullNode(ZI.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(ZI.EMPTY_NODE,o.getNode(),null),a=new j0(a,s.isFullyInitialized(),r.filtersNodes()),c=new j0(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=$0(c,a),this.eventGenerator_=new V0(this.query_)}get query(){return this.query_}}function xT(e){return 0===e.eventRegistrations_.length}function PT(n,r,i){const s=[];if(i){Yh(null==r,"A cancel should cancel all event registrations.");const o=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,o);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const a=n.eventRegistrations_[t];if(a.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(a)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function DT(e,t,n,r){t.type===ob.MERGE&&null!==t.source.queryId&&(Yh(H0(e.viewCache_),"We should always have a full cache before handling merges"),Yh(G0(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=TT(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,Yh(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),Yh(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),Yh(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,OT(e,s.changes,s.viewCache.eventCache.getNode(),null)}function OT(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return B0(e.eventGenerator_,t,n,i)}let MT;class LT{constructor(){this.views=new Map}}function FT(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return Yh(null!=e,"SyncTree gave us an op for an invalid query."),DT(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(DT(s,n,r,i));return e}}function UT(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=dT(r,s?i:null),t=!1;t=!!e||(e=i instanceof ZI?fT(r,i):ZI.EMPTY_NODE,!1);o=$0(new j0(e,t,!1),new j0(i,s,!1));return new RT(n,o)}}function qT(e,t,n,r,i,s){var o=UT(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(WI,(e,t)=>{r.push(p0(e,t))})}return n.isFullyInitialized()&&r.push(f0(n.getNode())),OT(e,r,n.getNode(),t)}(o,n)}function jT(e,t,n,r){var i=t._queryIdentifier;const s=[];let o=[];var a=WT(e);if("default"===i)for(var[c,l]of e.views.entries())o=o.concat(PT(l,n,r)),xT(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(o=o.concat(PT(u,n,r)),xT(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return a&&!WT(e)&&s.push((Yh(MT,"Reference.ts has not been loaded"),new MT(t._repo,t._path))),{removed:s,events:o}}function VT(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function BT(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=H0(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!yI(t)&&!n.getImmediateChild(hI(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function KT(e,t){const n=t._queryParams;if(n.loadsAllData())return zT(e);var r=t._queryIdentifier;return e.views.get(r)}function $T(e,t){return null!=KT(e,t)}function WT(e){return null!=zT(e)}function zT(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let GT;let HT=1;class QT{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Y0(null),this.pendingWriteTree_={visibleWrites:J0.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function YT(e,t,n,r,i){var s,o,a,c;return s=e.pendingWriteTree_,o=t,a=n,c=r,r=i,Yh(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:o,snap:a,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=X0(s.visibleWrites,o,a)),s.lastWriteId=c,i?iE(e,new U0(D0(),t,n)):[]}function JT(e,t,n,r){var i,s,o;i=e.pendingWriteTree_,s=t,o=n,r=r,Yh(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:o,writeId:r,visible:!0}),i.visibleWrites=Z0(i.visibleWrites,s,o),i.lastWriteId=r;var a=Y0.fromObject(n);return iE(e,new q0(D0(),t,a))}function XT(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(cT(e.pendingWriteTree_,t)){let t=new Y0(null);return null!=r.snap?t=t.set(uI(),!0):Db(r.children,e=>{t=t.set(new lI(e),!0)}),iE(e,new L0(r.path,t,n))}return[]}function ZT(e,t,n){return iE(e,new U0(O0(),t,n))}function eE(n,e,t,r){var i=e._path,s=n.syncPointTree_.get(i);let o=[];if(s&&("default"===e._queryIdentifier||$T(s,e))){var a=jT(s,e,t,r);0===s.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(i));const h=a.removed;o=a.events;s=-1!==h.findIndex(e=>e._queryParams.loadsAllData()),a=n.syncPointTree_.findOnPath(i,(e,t)=>WT(t));if(s&&!a){const d=n.syncPointTree_.subtree(i);if(!d.isEmpty()){var c=d.fold((e,t,r)=>{if(t&&WT(t))return[zT(t)];{let n=[];return t&&(n=VT(t)),Db(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e],u=l.query,l=oE(n,l);n.listenProvider_.startListening(dE(u),aE(n,u),l.hashFn,l.onComplete)}}}!a&&0<h.length&&!r&&(s?n.listenProvider_.stopListening(dE(e),null):h.forEach(e=>{var t=n.queryToTagMap.get(cE(e));n.listenProvider_.stopListening(dE(e),t)})),function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=cE(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,h)}return o}function tE(e,t,n){const r=t._path;let i=null,s=!1;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=_I(e,r);i=i||BT(t,n),s=s||WT(t)});let o=e.syncPointTree_.get(r);o?(s=s||WT(o),i=i||BT(o,uI())):(o=new LT,e.syncPointTree_=e.syncPointTree_.set(r,o));let a;if(null!=i)a=!0;else{a=!1,i=ZI.EMPTY_NODE;const d=e.syncPointTree_.subtree(r);d.foreachChild((e,t)=>{var n=BT(t,uI());n&&(i=i.updateImmediateChild(e,n))})}var c,l=$T(o,t);l||t._queryParams.loadsAllData()||(u=cE(t),Yh(!e.queryToTagMap.has(u),"View does not exist, but we have a tag"),c=HT++,e.queryToTagMap.set(u,c),e.tagToQueryMap.set(c,u));var u=aT(e.pendingWriteTree_,r);let h=qT(o,t,n,u,i,a);return l||s||(l=KT(o,t),h=h.concat(function(t,e,n){const r=e._path,i=aE(t,e),s=oE(t,n),o=t.listenProvider_.startListening(dE(e),i,s.hashFn,s.onComplete),a=t.syncPointTree_.subtree(r);if(i)Yh(!WT(a.value),"If we're adding a query, it shouldn't be shadowed");else{var c=a.fold((e,t,r)=>{if(!yI(e)&&t&&WT(t))return[zT(t).query];{let n=[];return t&&(n=n.concat(VT(t).map(e=>e.query))),Db(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(dE(l),aE(t,l))}}return o}(e,t,l))),h}function nE(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=BT(t,_I(e,r));if(n)return n});return hT(n,r,i,t,!0)}function rE(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=_I(e,r);i=i||BT(t,n)});let n=e.syncPointTree_.get(r);n?i=i||BT(n,uI()):(n=new LT,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const o=s?new j0(i,!0,!1):null;var a=aT(e.pendingWriteTree_,t._path);return G0(UT(n,t,a,s?o.getNode():ZI.EMPTY_NODE,s).viewCache_)}function iE(e,t){return function t(n,r,i,s){{if(yI(n.path))return sE(n,r,i,s);{const o=r.get(uI());null==i&&null!=o&&(i=BT(o,uI()));let e=[];const a=hI(n.path),c=n.operationForChild(a),l=r.children.get(a);if(l&&c){const u=i?i.getImmediateChild(a):null,h=yT(s,a);e=e.concat(t(c,l,u,h))}return o&&(e=e.concat(FT(o,n,s,i))),e}}}(t,e.syncPointTree_,null,aT(e.pendingWriteTree_,uI()))}function sE(s,e,o,a){var t=e.get(uI());null==o&&null!=t&&(o=BT(t,uI()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=yT(a,e),i=s.operationForChild(e);i&&(c=c.concat(sE(i,t,n,r)))}),t&&(c=c.concat(FT(t,s,a,o))),c}function oE(i,t){const s=t.query,o=aE(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||ZI.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return o?function(e,t,n){if(s=lE(e,n)){var r=uE(s),i=r.path,s=r.queryId,r=_I(i,t);return hE(e,i,new F0(M0(s),r))}return[]}(i,s._path,o):(t=i,n=s._path,iE(t,new F0(O0(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return eE(i,s,null,r)}}}function aE(e,t){var n=cE(t);return e.queryToTagMap.get(n)}function cE(e){return e._path.toString()+"$"+e._queryIdentifier}function lE(e,t){return e.tagToQueryMap.get(t)}function uE(e){var t=e.indexOf("$");return Yh(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new lI(e.substr(0,t))}}function hE(e,t,n){var r=e.syncPointTree_.get(t);return Yh(r,"Missing sync point for query tag that we're tracking"),FT(r,n,aT(e.pendingWriteTree_,t),null)}function dE(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(Yh(GT,"Reference.ts has not been loaded"),new GT(e._repo,e._path)):e}class fE{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new fE(t)}node(){return this.node_}}class pE{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=vI(this.path_,e);return new pE(this.syncTree_,t)}node(){return nE(this.syncTree_,this.path_)}}function gE(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function mE(e,t,n){return e&&"object"==typeof e?(Yh(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?vE(e[".sv"],t,n):"object"==typeof e[".sv"]?yE(e[".sv"],t):void Yh(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const vE=function(e,t,n){if("timestamp"===e)return n.timestamp;Yh(!1,"Unexpected server value: "+e)},yE=function(e,t,n){e.hasOwnProperty("increment")||Yh(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&Yh(!1,"Unexpected increment value: "+r);const i=t.node();if(Yh(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var o=s.getValue();return"number"!=typeof o?r:o+r},_E=function(e,t,n,r){return bE(t,new pE(n,e),r)},wE=function(e,t,n){return bE(e,new fE(t),n)};function bE(e,r,i){var t=e.getPriority().val(),n=mE(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const o=e;t=mE(o.getValue(),r,i);return t!==o.getValue()||n!==o.getPriority().val()?new BI(t,r0(n)):e}{const a=e;return s=a,n!==a.getPriority().val()&&(s=s.updatePriority(new BI(n))),a.forEachChild(WI,(e,t)=>{var n=bE(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class IE{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function TE(e,t){let n=t instanceof lI?t:new lI(t),r=e,i=hI(n);for(;null!==i;){var s=Id(r.node.children,i)||{children:{},childCount:0};r=new IE(i,r,s),n=fI(n),i=hI(n)}return r}function EE(e){return e.node.value}function SE(e,t){e.node.value=t,NE(e)}function kE(e){return 0<e.node.childCount}function CE(n,r){Db(n.node.children,(e,t)=>{r(new IE(e,n,t))})}function AE(e){return new lI(null===e.parent?e.name:AE(e.parent)+"/"+e.name)}function NE(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===EE(e)&&!kE(e)}(e=e),i=bd(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,NE(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,NE(t)))}function RE(e,t,n,r){r&&void 0===t||KE(Md(e,"value"),t,n)}function xE(e,t,r,n){if(!n||void 0!==t){const i=Md(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];Db(t,(e,t)=>{const n=new lI(e);if(KE(i,t,vI(r,n)),".priority"===pI(n)&&!BE(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=gI(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!qE(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(wI);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&II(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function PE(e,t,n){if(!n||void 0!==t){if(Nb(t))throw new Error(Md(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!BE(t))throw new Error(Md(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function DE(e,t,n,r){if(!(r&&void 0===n||qE(n)))throw new Error(Md(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function OE(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),$E(e,t,n,r)}function ME(e,t){if(".info"===hI(t))throw new Error(e+" failed = Can't modify data under /.info/")}const LE=/[\[\].#$\/\u0000-\u001F\u007F]/,FE=/[\[\].#$\u0000-\u001F\u007F]/,UE=10485760,qE=function(e){return"string"==typeof e&&0!==e.length&&!LE.test(e)},jE=function(e){return"string"==typeof e&&0!==e.length&&!FE.test(e)},VE=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),jE(e)},BE=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Nb(e)||e&&"object"==typeof e&&bd(e,".sv")},KE=function(o,e,t){const a=t instanceof lI?new TI(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+SI(a));if("function"==typeof e)throw new Error(o+"contains a function "+SI(a)+" with contents = "+e.toString());if(Nb(e))throw new Error(o+"contains "+e.toString()+" "+SI(a));if("string"==typeof e&&e.length>UE/3&&Ud(e)>UE)throw new Error(o+"contains a string greater than "+UE+" utf8 bytes "+SI(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Db(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!qE(e)))throw new Error(o+" contains an invalid key ("+e+") "+SI(a)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=a,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=Ud(e),EI(n),KE(o,t,a),t=a,r=t.parts_.pop(),t.byteLength_-=Ud(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(o+' contains ".value" child '+SI(a)+" in addition to actual children.")}},$E=function(e,t,n,r){if(!(r&&void 0===n||jE(n)))throw new Error(Md(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},WE=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!qE(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!VE(n))throw new Error(Md(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class zE{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function GE(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||bI(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function HE(e,t,n){GE(e,n),YE(e,e=>bI(e,t))}function QE(e,t,n){GE(e,n),YE(e,e=>II(e,t)||II(t,e))}function YE(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),mb&&Sb("event: "+r.toString()),jb(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const JE="repo_interrupt",XE=25;class ZE{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new zE,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=A0(),this.transactionQueueTree_=new IE,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function eS(o,e,t){if(o.stats_=Xb(o.repoInfo_),o.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())o.server_=new k0(o.repoInfo_,(e,t,n,r)=>{rS(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>iS(o,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{_d(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}o.persistentConnection_=new CI(o.repoInfo_,e,(e,t,n,r)=>{rS(o,e,t,n,r)},e=>{iS(o,e)},e=>{var n;n=o,Db(e,(e,t)=>{sS(n,e,t)})},o.authTokenProvider_,o.appCheckProvider_,t),o.server_=o.persistentConnection_}var n;o.authTokenProvider_.addTokenChangeListener(e=>{o.server_.refreshAuthToken(e)}),o.appCheckProvider_.addTokenChangeListener(e=>{o.server_.refreshAppCheckToken(e.token)}),o.statsReporter_=(e=o.repoInfo_,t=()=>new P0(o.stats_,o.server_),n=e.toString(),Jb[n]||(Jb[n]=t()),Jb[n]),o.infoData_=new C0,o.infoSyncTree_=new QT({startListening:(e,t,n,r)=>{let i=[];const s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=ZT(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),sS(o,"connected",!1),o.serverSyncTree_=new QT({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);QE(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function tS(e){const t=e.infoData_.getNode(new lI(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function nS(e){return gE({timestamp:tS(e)})}function rS(e,t,n,r,i){e.dataUpdateCount++;var s,o,a=new lI(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=Ed(n,e=>r0(e)),function(e,t,n,r){if(a=lE(e,r)){var i=uE(a),s=i.path,o=i.queryId,a=_I(s,t),i=Y0.fromObject(n);return hE(e,s,new q0(M0(o),a,i))}return[]}(e.serverSyncTree_,a,s,i)):(s=r0(n),function(e,t,n,r){if(null==(s=lE(e,r)))return[];var i=(o=uE(s)).path,s=o.queryId,o=_I(i,t);return hE(e,i,new U0(M0(s),o,n))}(e.serverSyncTree_,a,s,i)):r?(o=Ed(n,e=>r0(e)),t=e.serverSyncTree_,i=a,r=o,o=Y0.fromObject(r),iE(t,new q0(O0(),i,o))):(o=r0(n),ZT(e.serverSyncTree_,a,o));let l=a;0<c.length&&(l=mS(e,a)),QE(e.eventQueue_,l,c)}function iS(e,t){sS(e,"connected",t),!1===t&&function(r){dS(r,"onDisconnectEvents");const i=nS(r),s=A0();R0(r.onDisconnect_,uI(),(e,t)=>{var n=_E(e,t,r.serverSyncTree_,i);N0(s,e,n)});let o=[];R0(s,uI(),(e,t)=>{o=o.concat(ZT(r.serverSyncTree_,e,t));var n=wS(r,e);mS(r,n)}),r.onDisconnect_=A0(),QE(r.eventQueue_,uI(),o)}(e)}function sS(e,t,n){var r=new lI("/.info/"+t),i=r0(n);e.infoData_.updateSnapshot(r,i);i=ZT(e.infoSyncTree_,r,i);QE(e.eventQueue_,r,i)}function oS(e){return e.nextWriteId_++}function aS(r,i,e,t,s){dS(r,"set",{path:i.toString(),value:e,priority:t});var n=nS(r);const o=r0(e,t);var a=nE(r.serverSyncTree_,i),n=wE(o,a,n);const c=oS(r);n=YT(r.serverSyncTree_,i,n,c,!0);GE(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e;n||Cb("set at "+i+" failed: "+e);n=XT(r.serverSyncTree_,c,!n);QE(r.eventQueue_,i,n),fS(0,s,e,t)});n=wS(r,i);mS(r,n),QE(r.eventQueue_,n,[])}function cS(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(yI(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(WI,(e,t)=>{N0(n,new lI(e),t)}),e(n,t)}}if(0<n.children.size){var r=hI(t);return t=fI(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),fS(0,i,e,t)})}function lS(n,r,e,i){const s=r0(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&N0(n.onDisconnect_,r,s),fS(0,i,e,t)})}function uS(e,t,n){let r;r=".info"===hI(t._path)?eE(e.infoSyncTree_,t,n):eE(e.serverSyncTree_,t,n),HE(e.eventQueue_,t._path,r)}function hS(e){e.persistentConnection_&&e.persistentConnection_.interrupt(JE)}function dS(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),Sb(n,...t)}function fS(e,r,i,s){r&&jb(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function pS(e,t,n){return nE(e.serverSyncTree_,t,n)||ZI.EMPTY_NODE}function gS(t,e=t.transactionQueueTree_){if(e||_S(t,e),EE(e)){const n=yS(t,e);Yh(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,o){const e=o.map(e=>e.currentWriteId),t=pS(i,s,e);let n=t;var r=t.hash();for(let u=0;u<o.length;u++){const h=o[u];Yh(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var a=_I(s,h.path);n=n.updateChild(a,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{dS(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<o.length;e++)o[e].status=2,n=n.concat(XT(i.serverSyncTree_,o[e].currentWriteId)),o[e].onComplete&&r.push(()=>o[e].onComplete(null,!0,o[e].currentOutputSnapshotResolved)),o[e].unwatcher();_S(i,TE(i.transactionQueueTree_,s)),gS(i,i.transactionQueueTree_),QE(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)jb(r[t])}else{if("datastale"===t)for(let e=0;e<o.length;e++)3===o[e].status?o[e].status=4:o[e].status=0;else{Cb("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<o.length;e++)o[e].status=4,o[e].abortReason=t}mS(i,s)}},r)}(t,AE(e),n)}else kE(e)&&CE(e,e=>{gS(t,e)})}function mS(e,t){var n=vS(e,t),r=AE(n);return function(i,s,o){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var a=_I(o,h.path);let e=!1,t;if(Yh(null!==a,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(XT(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=XE)e=!0,t="maxretry",n=n.concat(XT(i.serverSyncTree_,h.currentWriteId,!0));else{const d=pS(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){KE("transaction failed: Data returned ",c,h.path);let e=r0(c);"object"==typeof c&&null!=c&&bd(c,".priority")||(e=e.updatePriority(d.getPriority()));a=h.currentWriteId,c=nS(i),c=wE(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=oS(i),u.splice(u.indexOf(a),1),n=n.concat(YT(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(XT(i.serverSyncTree_,a,!0))}else e=!0,t="nodata",n=n.concat(XT(i.serverSyncTree_,h.currentWriteId,!0))}QE(i.eventQueue_,o,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}_S(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)jb(l[e]);gS(i,i.transactionQueueTree_)}}(e,yS(e,n),r),r}function vS(e,t){let n,r=e.transactionQueueTree_;for(n=hI(t);null!==n&&void 0===EE(r);)r=TE(r,n),t=fI(t),n=hI(t);return r}function yS(e,t){const n=[];return function t(n,e,r){const i=EE(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);CE(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function _S(t,n){const r=EE(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,SE(n,0<r.length?r:void 0)}CE(n,e=>{_S(t,e)})}function wS(t,e){var n=AE(vS(t,e)),r=TE(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{bS(t,e)}),bS(t,r),function t(e,n,r,i){r&&!i&&n(e),CE(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{bS(t,e)}),n}function bS(i,s){const o=EE(s);if(o){const a=[];let e=[],t=-1;for(let n=0;n<o.length;n++)3===o[n].status||(1===o[n].status?(Yh(t===n-1,"All SENT items should be at beginning of queue."),t=n,o[n].status=3,o[n].abortReason="set"):(Yh(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(XT(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?SE(s,void 0):o.length=t+1,QE(i.eventQueue_,AE(s),e);for(let r=0;r<a.length;r++)jb(a[r])}}const IS=function(e,t){var n=TS(e),r=n.namespace;"firebase.com"===n.domain&&kb(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||kb("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Ab();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Gb(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new lI(n.pathString)}},TS=function(r){let i="",s="",o="",a="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(a=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,f=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):Cb(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const p=i.slice(0,e);"localhost"===p.toLowerCase()?s="localhost":p.split(".").length<=2?s=p:(d=i.indexOf("."),o=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=o),"ns"in f&&(c=f.ns)}return{host:i,port:h,domain:s,subdomain:o,secure:l,scheme:u,pathString:a,namespace:c}};class ES{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+_d(this.snapshot.exportVal())}}class SS{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class kS{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return Yh(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class CS{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new rd;return cS(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){ME("OnDisconnect.remove",this._path);const e=new rd;return lS(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){ME("OnDisconnect.set",this._path),RE("OnDisconnect.set",e,this._path,!1);const t=new rd;return lS(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){ME("OnDisconnect.setWithPriority",this._path),RE("OnDisconnect.setWithPriority",e,this._path,!1),PE("OnDisconnect.setWithPriority",t,!1);const n=new rd;return function(n,r,e,t,i){const s=r0(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&N0(n.onDisconnect_,r,s),fS(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){ME("OnDisconnect.update",this._path),xE("OnDisconnect.update",e,this._path,!1);const t=new rd;return function(r,i,n,s){if(Td(n))return Sb("onDisconnect().update() called with empty data. Don't do anything."),fS(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Db(n,(e,t)=>{var n=r0(t);N0(r.onDisconnect_,vI(i,e),n)}),fS(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class AS{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return yI(this._path)?null:pI(this._path)}get ref(){return new PS(this._repo,this._path)}get _queryIdentifier(){var e=S0(this._queryParams),e=Ib(e);return"{}"===e?"default":e}get _queryObject(){return S0(this._queryParams)}isEqual(e){if(!((e=$d(e))instanceof AS))return!1;var t=this._repo===e._repo,n=bI(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function NS(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function RS(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===PI){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==Rb)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==xb)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===WI){if(null!=t&&!BE(t)||null!=n&&!BE(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(Yh(e.getIndex()instanceof i0||e.getIndex()===a0,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function xS(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class PS extends AS{constructor(e,t){super(e,t,new w0,!1)}get parent(){var e=mI(this._path);return null===e?null:new PS(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class DS{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new lI(e),n=LS(this.ref,e);return new DS(this._node.getChild(t),n,WI)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new DS(t,LS(this.ref,e),WI)))}hasChild(e){var t=new lI(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function OS(e,t){return(e=$d(e))._checkNotDeleted("ref"),void 0!==t?LS(e._root,t):e._root}function MS(e,t){(e=$d(e))._checkNotDeleted("refFromURL");const n=IS(t,e._repo.repoInfo_.nodeAdmin);WE("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||kb("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),OS(e,n.path.toString())}function LS(e,t){return(null===hI((e=$d(e))._path)?OE:$E)("child","path",t,!1),new PS(e._repo,vI(e._path,t))}function FS(e,t){e=$d(e),ME("set",e._path),RE("set",t,e._path,!1);const n=new rd;return aS(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function US(e,t){xE("update",t,e._path,!1);const n=new rd;return function(i,s,e,o){dS(i,"update",{path:s.toString(),value:e});let n=!0;const r=nS(i),a={};if(Db(e,(e,t)=>{n=!1,a[e]=_E(vI(s,e),r0(t),i.serverSyncTree_,r)}),n)Sb("update() called with empty data. Don't do anything."),fS(0,o,"ok",void 0);else{const c=oS(i);var t=JT(i.serverSyncTree_,s,a,c);GE(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||Cb("update at "+s+" failed: "+e);var r=XT(i.serverSyncTree_,c,!n),n=0<r.length?mS(i,s):s;QE(i.eventQueue_,n,r),fS(0,o,e,t)}),Db(e,e=>{var t=wS(i,vI(s,e));mS(i,t)}),QE(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function qS(t){return t=$d(t),r=t._repo,i=t,(null!=(e=rE(r.serverSyncTree_,i))?Promise.resolve(e):r.server_.get(i).then(e=>{var t=r0(e).withIndex(i._queryParams.getIndex()),n=ZT(r.serverSyncTree_,i._path,t);return HE(r.eventQueue_,i._path,n),Promise.resolve(t)},e=>(dS(r,"get for query "+_d(i)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new DS(e,new PS(t._repo,t._path),t._queryParams.getIndex()));var r,i,e}class jS{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new ES("value",this,new DS(e.snapshotNode,new PS(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new SS(this,e,t):null}matches(e){return e instanceof jS&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class VS{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new SS(this,e,t):null}createEvent(e,t){Yh(null!=e.childName,"Child events should have a childName.");var n=LS(new PS(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new ES(e.type,this,new DS(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof VS&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function BS(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var o=(e,t)=>{uS(n._repo,n,a),c(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new kS(t,s||void 0);const a="value"===e?new jS(o):new VS(e,o);return function(e,t,n){let r;r=".info"===hI(t._path)?tE(e.infoSyncTree_,t,n):tE(e.serverSyncTree_,t,n),HE(e.eventQueue_,t._path,r)}(n._repo,n,a),()=>uS(n._repo,n,a)}function KS(e,t,n,r){return BS(e,"value",t,n,r)}function $S(e,t,n,r){return BS(e,"child_added",t,n,r)}function WS(e,t,n,r){return BS(e,"child_changed",t,n,r)}function zS(e,t,n,r){return BS(e,"child_moved",t,n,r)}function GS(e,t,n,r){return BS(e,"child_removed",t,n,r)}function HS(e,t,n){let r=null;var i=n?new kS(n):null;"value"===t?r=new jS(i):t&&(r=new VS(t,i)),uS(e._repo,e,r)}class QS{}class YS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("endAt",this._value,e._path,!0);var t=I0(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class JS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r,i;return i=e.index_===PI?I0(e,t="string"==typeof t?o0(t):t,n):(r=null==n?Rb:o0(n),I0(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class XS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("startAt",this._value,e._path,!0);var t=b0(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class ZS extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){RE("startAfter",this._value,e._path,!1);var t=function(t,n,r){let i;if(t.index_===PI)"string"==typeof n&&(n=s0(n)),i=b0(t,n,r);else{let e;e=null==r?xb:s0(r),i=b0(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(xS(t),RS(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new AS(e._repo,e._path,t,e._orderByCalled)}}class ek extends QS{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new AS(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class tk extends QS{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new AS(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class nk extends QS{constructor(e){super(),this._path=e}_apply(e){NS(e,"orderByChild");var t=new lI(this._path);if(yI(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new i0(t),t=T0(e._queryParams,t);return RS(t),new AS(e._repo,e._path,t,!0)}}class rk extends QS{_apply(e){NS(e,"orderByKey");var t=T0(e._queryParams,PI);return RS(t),new AS(e._repo,e._path,t,!0)}}class ik extends QS{_apply(e){NS(e,"orderByPriority");var t=T0(e._queryParams,WI);return RS(t),new AS(e._repo,e._path,t,!0)}}class sk extends QS{_apply(e){NS(e,"orderByValue");var t=T0(e._queryParams,a0);return RS(t),new AS(e._repo,e._path,t,!0)}}class ok extends QS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(RE("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new YS(this._value,this._key)._apply(new XS(this._value,this._key)._apply(e))}}function ak(e,...t){let n=$d(e);for(const r of t)n=r._apply(n);return n}ab=PS,Yh(!MT,"__referenceConstructor has already been defined"),MT=ab,cb=PS,Yh(!GT,"__referenceConstructor has already been defined"),GT=cb;const ck="FIREBASE_DATABASE_EMULATOR_HOST",lk={};let uk=!1;function hk(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||kb("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Sb("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o=IS(s,i),a=o.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[ck]),l?(c=!0,s=`http://${l}?ns=${a.namespace}`,o=IS(s,i),a=o.repoInfo):c=!o.repoInfo.secure;var u=i&&c?new Kb(Kb.OWNER):new Bb(e.name,e.options,t);WE("Invalid Firebase Database URL",o),yI(o.path)||kb("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=lk[t.name];i||(i={},lk[t.name]=i);var s=i[e.toURLString()];s&&kb("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new ZE(e,uk,n,r),i[e.toURLString()]=s}(a,e,u,new Vb(e.name,n));return new dk(u,e)}class dk{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(eS(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new PS(this._repo,uI())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=lk[t];n&&n[e.key]===e||kb(`Database ${t}(${e.repoInfo_}) has already been deleted.`),hS(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&kb("Cannot call "+e+" on a deleted database.")}}function fk(e,t,n,r={}){(e=$d(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&kb("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let o=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&kb('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Kb(Kb.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:id(r.mockUserToken,e.app.options.projectId),o=new Kb(i)),r=s,e=t,t=n,n=o,r.repoInfo_=new Gb(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams),n&&(r.authTokenProvider_=n)}function pk(e){(e=$d(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(JE)}function gk(e,t){Eb(e,t)}const mk={".sv":"timestamp"};class vk{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function yk(i,e,t){if(i=$d(i),ME("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new rd;var r=KS(i,()=>{});return function(t,n,e,r,i,s){dS(t,"transaction on "+n);const o={path:n,update:e,onComplete:r,status:null,order:pb(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=pS(t,n,void 0);o.currentInputSnapshot=a;var c=o.update(a.val());if(void 0===c)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{KE("transaction failed: Data returned ",c,o.path),o.status=0;var l=TE(t.transactionQueueTree_,n);const u=EE(l)||[];u.push(o),SE(l,u);let e;if("object"==typeof c&&null!==c&&bd(c,".priority"))e=Id(c,".priority"),Yh(BE(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=nE(t.serverSyncTree_,n)||ZI.EMPTY_NODE;e=h.getPriority().val()}l=nS(t),c=r0(c,e),l=wE(c,a,l);o.currentOutputSnapshotRaw=c,o.currentOutputSnapshotResolved=l,o.currentWriteId=oS(t);l=YT(t.serverSyncTree_,n,l,o.currentWriteId,o.applyLocally);QE(t.eventQueue_,n,l),gS(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new DS(n,new PS(i._repo,i._path),WI),s.resolve(new vk(t,r)))},r,n),s.promise}CI.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},CI.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},tb(Tf),_f(new Xd("database",(e,{instanceIdentifier:t})=>{return hk(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),Cf(Zw,"0.12.8",lb),Cf(Zw,"0.12.8","esm2017");function _k(e){var t="FIREBASE WARNING: "+e;wk.warn(t)}const wk=new cf("@firebase/database-compat");class bk{constructor(e){this._delegate=e}cancel(t){Od("OnDisconnect.cancel",0,1,arguments.length),Ld("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Od("OnDisconnect.remove",0,1,arguments.length),Ld("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Od("OnDisconnect.set",1,2,arguments.length),Ld("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Od("OnDisconnect.setWithPriority",2,3,arguments.length),Ld("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Od("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,_k("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}Ld("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class Ik{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Od("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class Tk{constructor(e,t){this._database=e,this._delegate=t}val(){return Od("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Od("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Od("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Od("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Od("DataSnapshot.child",0,1,arguments.length),e=String(e),$E("DataSnapshot.child","path",e,!1),new Tk(this._database,this._delegate.child(e))}hasChild(e){return Od("DataSnapshot.hasChild",1,1,arguments.length),$E("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Od("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Od("DataSnapshot.forEach",1,1,arguments.length),Ld("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new Tk(this._database,e)))}hasChildren(){return Od("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Od("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Od("DataSnapshot.ref",0,0,arguments.length),new Sk(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class Ek{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Od("Query.on",2,4,arguments.length),Ld("Query.on","callback",n,!1);const s=Ek.getCancelAndContextArgs_("Query.on",t,r);var o=(e,t)=>{n.call(s.context,new Tk(this.database,e),t)};o.userCallback=n,o.context=s.context;var a=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return KS(this._delegate,o,a),n;case"child_added":return $S(this._delegate,o,a),n;case"child_removed":return GS(this._delegate,o,a),n;case"child_changed":return WS(this._delegate,o,a),n;case"child_moved":return zS(this._delegate,o,a),n;default:throw new Error(Md("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Od("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(Md(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),Ld("Query.off","callback",t,!0),Fd("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,HS(this._delegate,e,r)):HS(this._delegate,e)}get(){return qS(this._delegate).then(e=>new Tk(this.database,e))}once(e,r,t,n){Od("Query.once",1,4,arguments.length),Ld("Query.once","callback",r,!0);const i=Ek.getCancelAndContextArgs_("Query.once",t,n),s=new rd;var o=(e,t)=>{var n=new Tk(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};o.userCallback=r,o.context=i.context;var a=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":KS(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":$S(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":GS(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":WS(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":zS(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(Md("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return Od("Query.limitToFirst",1,1,arguments.length),new Ek(this.database,ak(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new ek(e)}(e)))}limitToLast(e){return Od("Query.limitToLast",1,1,arguments.length),new Ek(this.database,ak(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new tk(e)}(e)))}orderByChild(e){return Od("Query.orderByChild",1,1,arguments.length),new Ek(this.database,ak(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return $E("orderByChild","path",e,!1),new nk(e)}(e)))}orderByKey(){return Od("Query.orderByKey",0,0,arguments.length),new Ek(this.database,ak(this._delegate,new rk))}orderByPriority(){return Od("Query.orderByPriority",0,0,arguments.length),new Ek(this.database,ak(this._delegate,new ik))}orderByValue(){return Od("Query.orderByValue",0,0,arguments.length),new Ek(this.database,ak(this._delegate,new sk))}startAt(e=null,t){return Od("Query.startAt",0,2,arguments.length),new Ek(this.database,ak(this._delegate,([e=null,t]=[e,t],DE("startAt","key",t,!0),new XS(e,t))))}startAfter(e=null,t){return Od("Query.startAfter",0,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("startAfter","key",t,!0),new ZS(e,t))))}endAt(e=null,t){return Od("Query.endAt",0,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("endAt","key",t,!0),new YS(e,t))))}endBefore(e=null,t){return Od("Query.endBefore",0,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("endBefore","key",t,!0),new JS(e,t))))}equalTo(e,t){return Od("Query.equalTo",1,2,arguments.length),new Ek(this.database,ak(this._delegate,(e=e,t=t,DE("equalTo","key",t,!0),new ok(e,t))))}toString(){return Od("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Od("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Od("Query.isEqual",1,1,arguments.length),e instanceof Ek)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,Ld(e,"cancel",r.cancel,!0),r.context=n,Fd(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(Md(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new Sk(this.database,new PS(this._delegate._repo,this._delegate._path))}}class Sk extends Ek{constructor(e,t){super(e,new AS(t._repo,t._path,new w0,!1)),this.database=e,this._delegate=t}getKey(){return Od("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Od("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new Sk(this.database,LS(this._delegate,e))}getParent(){Od("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new Sk(this.database,e):null}getRoot(){return Od("Reference.root",0,0,arguments.length),new Sk(this.database,this._delegate.root)}set(e,t){Od("Reference.set",1,2,arguments.length),Ld("Reference.set","onComplete",t,!0);const n=FS(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Od("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,_k("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}ME("Reference.update",this._delegate._path),Ld("Reference.update","onComplete",n,!0);const e=US(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Od("Reference.setWithPriority",2,3,arguments.length),Ld("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(ME("setWithPriority",e._path),RE("setWithPriority",t,e._path,!1),PE("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new rd;return aS(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Od("Reference.remove",0,1,arguments.length),Ld("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,ME("remove",n._path),FS(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Od("Reference.transaction",1,3,arguments.length),Ld("Reference.transaction","transactionUpdate",e,!1),Ld("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(Md(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=yk(this._delegate,e,{applyLocally:n}).then(e=>new Ik(e.committed,new Tk(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Od("Reference.setPriority",1,2,arguments.length),Ld("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=$d(e),ME("setPriority",e._path),PE("setPriority",t,!1);const n=new rd;return aS(e._repo,vI(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Od("Reference.push",0,2,arguments.length),Ld("Reference.push","onComplete",t,!0);const n=function(e,t){e=$d(e),ME("push",e._path),RE("push",t,e._path,!0);var n=tS(e._repo),n=d0(n);const r=LS(e,n),i=LS(e,n);let s;return s=null!=t?FS(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new Sk(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new Sk(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return ME("Reference.onDisconnect",this._delegate._path),new bk(new CS(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class kk{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete()}}useEmulator(e,t,n={}){fk(this._delegate,e,t,n)}ref(e){if(Od("database.ref",0,1,arguments.length),e instanceof Sk){var t=MS(this._delegate,e.toString());return new Sk(this,t)}t=OS(this._delegate,e);return new Sk(this,t)}refFromURL(e){Od("database.refFromURL",1,1,arguments.length);var t=MS(this._delegate,e);return new Sk(this,t)}goOffline(){var e;Od("database.goOffline",0,0,arguments.length),(e=$d(e=this._delegate))._checkNotDeleted("goOffline"),hS(e._repo)}goOnline(){return Od("database.goOnline",0,0,arguments.length),pk(this._delegate)}}kk.ServerValue={TIMESTAMP:mk,increment:e=>({".sv":{increment:e}})};var Ck,Ak=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){tb(n);const o=new ef("auth-internal",new tf("database-standalone"));return o.setComponent(new Xd("auth-internal",()=>r,"PRIVATE")),{instance:new kk(hk(e,o,void 0,t,s),e),namespace:i}}});const Nk=kk.ServerValue;(Ck=zf).INTERNAL.registerComponent(new Xd("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new kk(r,n)},"PUBLIC").setServiceProps({Reference:Sk,Query:Ek,Database:kk,DataSnapshot:Tk,enableLogging:gk,INTERNAL:Ak,ServerValue:Nk}).setMultipleInstances(!0)),Ck.registerVersion("@firebase/database-compat","0.1.8");var l="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Rk={},xk=l||self;function Pk(){}function Dk(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Ok(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Mk="closure_uid_"+(1e9*Math.random()>>>0),Lk=0;function Fk(e,t,n){return e.call.apply(e.bind,arguments)}function Uk(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function qk(e,t,n){return(qk=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Fk:Uk).apply(null,arguments)}function jk(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function Vk(e,s){function t(){}t.prototype=s.prototype,e.Z=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Vb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function Bk(){this.s=this.s,this.o=this.o}var Kk={};Bk.prototype.s=!1,Bk.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,Mk)&&t[Mk]||(t[Mk]=++Lk),delete Kk[e])},Bk.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const $k=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1},Wk=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){var r=e.length,i="string"==typeof e?e.split(""):e;for(let s=0;s<r;s++)s in i&&t.call(n,i[s],s,e)};function zk(){return Array.prototype.concat.apply([],arguments)}function Gk(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function Hk(e){return/^[\s\xa0]*$/.test(e)}var Qk,Yk=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function Jk(e,t){return-1!=e.indexOf(t)}function Xk(e,t){return e<t?-1:t<e?1:0}e:{var Zk=xk.navigator;if(Zk){Zk=Zk.userAgent;if(Zk){Qk=Zk;break e}}Qk=""}function eC(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function tC(e){const t={};for(const n in e)t[n]=e[n];return t}var nC="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function rC(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<nC.length;e++)n=nC[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function iC(e){return iC[" "](e),e}iC[" "]=Pk;var sC,oC=Jk(Qk,"Opera"),aC=Jk(Qk,"Trident")||Jk(Qk,"MSIE"),cC=Jk(Qk,"Edge"),lC=cC||aC,uC=Jk(Qk,"Gecko")&&!(Jk(Qk.toLowerCase(),"webkit")&&!Jk(Qk,"Edge"))&&!(Jk(Qk,"Trident")||Jk(Qk,"MSIE"))&&!Jk(Qk,"Edge"),hC=Jk(Qk.toLowerCase(),"webkit")&&!Jk(Qk,"Edge");function dC(){var e=xk.document;return e?e.documentMode:void 0}e:{var fC="",pC=(pC=Qk,uC?/rv:([^\);]+)(\)|;)/.exec(pC):cC?/Edge\/([\d\.]+)/.exec(pC):aC?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(pC):hC?/WebKit\/(\S+)/.exec(pC):oC?/(?:Version)[ \/]?(\S+)/.exec(pC):void 0);if(pC&&(fC=pC?pC[1]:""),aC){pC=dC();if(null!=pC&&pC>parseFloat(fC)){sC=String(pC);break e}}sC=fC}var gC={};function mC(){return e=function(){let e=0;var t=Yk(String(sC)).split("."),n=Yk("9").split("."),r=Math.max(t.length,n.length);for(let o=0;0==e&&o<r;o++)for(var i=t[o]||"",s=n[o]||"";i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],(0!=i[0].length||0!=s[0].length)&&(e=Xk(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||Xk(0==i[2].length,0==s[2].length)||Xk(i[2],s[2]),i=i[3],s=s[3],0==e););return 0<=e},t=gC,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var vC=xk.document&&aC&&(dC()||parseInt(sC,10))||void 0,yC=function(){if(!xk.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{xk.addEventListener("test",Pk,t),xk.removeEventListener("test",Pk,t)}catch(e){}return e}();function _C(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function wC(e,t){if(_C.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(uC){e:{try{iC(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:bC[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&wC.Z.h.call(this)}}_C.prototype.h=function(){this.defaultPrevented=!0},Vk(wC,_C);var bC={2:"touch",3:"pen",4:"mouse"};wC.prototype.h=function(){wC.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var IC="closure_listenable_"+(1e6*Math.random()|0),TC=0;function EC(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ia=i,this.key=++TC,this.ca=this.fa=!1}function SC(e){e.ca=!0,e.listener=null,e.proxy=null,e.src=null,e.ia=null}function kC(e){this.src=e,this.g={},this.h=0}function CC(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=$k(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(SC(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function AC(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.ca&&s.listener==t&&s.capture==!!n&&s.ia==r)return i}return-1}kC.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=AC(e,t,r,i);return-1<o?(t=e[o],n||(t.fa=!1)):((t=new EC(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var NC="closure_lm_"+(1e6*Math.random()|0),RC={};function xC(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);return null}r=UC(r);return t&&t[IC]?t.O(n,r,Ok(i)?!!i.capture:!!i,s):PC(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)xC(e,t[s],n,r,i);return null}return n=UC(n),e&&e[IC]?e.N(t,n,Ok(r)?!!r.capture:!!r,i):PC(e,t,n,!1,r,i)}function PC(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o,a=Ok(i)?!!i.capture:!!i,c=LC(e);if(c||(e[NC]=c=new kC(e)),(n=c.add(t,n,r,a,s)).proxy)return n;if(o=MC,r=function e(t){return o.call(e.src,e.listener,t)},(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!yC?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(OC(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function DC(e){var t,n,r;"number"!=typeof e&&e&&!e.ca&&((t=e.src)&&t[IC]?CC(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(OC(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=LC(t))?(CC(n,e),0==n.h&&(n.src=null,t[NC]=null)):SC(e)))}function OC(e){return e in RC?RC[e]:RC[e]="on"+e}function MC(e,t){var n,r;return e=!!e.ca||(t=new wC(t,this),n=e.listener,r=e.ia||e.src,e.fa&&DC(e),n.call(r,t))}function LC(e){return(e=e[NC])instanceof kC?e:null}var FC="__closure_events_fn_"+(1e9*Math.random()>>>0);function UC(t){return"function"==typeof t?t:(t[FC]||(t[FC]=function(e){return t.handleEvent(e)}),t[FC])}function qC(){Bk.call(this),this.i=new kC(this),(this.P=this).I=null}function jC(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new _C(t,e):t instanceof _C?t.target=t.target||e:(o=t,rC(t=new _C(r,e),o)),o=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],o=VC(s,r,!0,t)&&o;if(o=VC(s=t.g=e,r,!0,t)&&o,o=VC(s,r,!1,t)&&o,n)for(i=0;i<n.length;i++)o=VC(s=t.g=n[i],r,!1,t)&&o}function VC(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o,a,c=t[s];c&&!c.ca&&c.capture==n&&(o=c.listener,a=c.ia||c.src,c.fa&&CC(e.i,c),i=!1!==o.call(a,r)&&i)}return i&&!r.defaultPrevented}Vk(qC,Bk),qC.prototype[IC]=!0,qC.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);else i=Ok(i)?!!i.capture:!!i,r=UC(r),t&&t[IC]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=AC(o=t.g[n],r,i,s))&&(SC(o[r]),Array.prototype.splice.call(o,r,1),0==o.length&&(delete t.g[n],t.h--))):(t=t&&LC(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?AC(n,r,i,s):t)?n[t]:null)&&DC(r))}(this,e,t,n,r)},qC.prototype.M=function(){if(qC.Z.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)SC(n[r]);delete t.g[e],t.h--}}this.I=null},qC.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},qC.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var BC=xk.JSON.stringify;var KC,$C=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new WC,e=>e.reset());class WC{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function zC(e,t){var n;KC||(n=xk.Promise.resolve(void 0),KC=function(){n.then(QC)}),GC||(KC(),GC=!0),HC.add(e,t)}var GC=!1,HC=new class{constructor(){this.h=this.g=null}add(e,t){const n=$C.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function QC(){for(var e;e=function(){var e=HC;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){xk.setTimeout(()=>{throw e},0)}(e)}var t=$C;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}GC=!1}function YC(e,t){qC.call(this),this.h=e||1,this.g=t||xk,this.j=qk(this.kb,this),this.l=Date.now()}function JC(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function XC(e,t,n){if("function"==typeof e)n&&(e=qk(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=qk(e.handleEvent,e)}return 2147483647<Number(t)?-1:xk.setTimeout(e,t||0)}Vk(YC,qC),(ze=YC.prototype).da=!1,ze.S=null,ze.kb=function(){var e;this.da&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.S=this.g.setTimeout(this.j,this.h-e):(this.S&&(this.g.clearTimeout(this.S),this.S=null),jC(this,"tick"),this.da&&(JC(this),this.start())))},ze.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},ze.M=function(){YC.Z.M.call(this),JC(this),delete this.g};class ZC extends Bk{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=XC(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(xk.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function eA(e){Bk.call(this),this.h=e,this.g={}}Vk(eA,Bk);var tA=[];function nA(e,t,n,r){Array.isArray(n)||(n&&(tA[0]=n.toString()),n=tA);for(var i=0;i<n.length;i++){var s=xC(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function rA(e){eC(e.g,function(e,t){this.g.hasOwnProperty(t)&&DC(e)},e),e.g={}}function iA(){this.g=!0}function sA(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return BC(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}eA.prototype.M=function(){eA.Z.M.call(this),rA(this)},eA.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},iA.prototype.Aa=function(){this.g=!1},iA.prototype.info=function(){};var oA={},aA=null;function cA(){return aA=aA||new qC}function lA(e){_C.call(this,oA.Ma,e)}function uA(){var e=cA();jC(e,new lA(e))}function hA(e,t){_C.call(this,oA.STAT_EVENT,e),this.stat=t}function dA(e){var t=cA();jC(t,new hA(t,e))}function fA(e,t){_C.call(this,oA.Na,e),this.size=t}function pA(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return xk.setTimeout(function(){e()},t)}oA.Ma="serverreachability",Vk(lA,_C),oA.STAT_EVENT="statevent",Vk(hA,_C),oA.Na="timingevent",Vk(fA,_C);c={NO_ERROR:0,lb:1,yb:2,xb:3,sb:4,wb:5,zb:6,Ja:7,TIMEOUT:8,Cb:9},yt={qb:"complete",Mb:"success",Ka:"error",Ja:"abort",Eb:"ready",Fb:"readystatechange",TIMEOUT:"timeout",Ab:"incrementaldata",Db:"progress",tb:"downloadprogress",Ub:"uploadprogress"};function gA(){}function mA(e){return e.h||(e.h=e.i())}function vA(){}gA.prototype.h=null;l={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function yA(){_C.call(this,"d")}function _A(){_C.call(this,"c")}function wA(){}function bA(e,t,n,r){this.l=e,this.j=t,this.m=n,this.X=r||1,this.V=new eA(this),this.P=EA,this.W=new YC(e=lC?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.Y=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.N=-1,this.I=!1,this.O=0,this.L=null,this.aa=this.J=this.$=this.U=!1,this.h=new IA}function IA(){this.i=null,this.g="",this.h=!1}Vk(yA,_C),Vk(_A,_C),Vk(wA,gA),wA.prototype.g=function(){return new XMLHttpRequest},wA.prototype.i=function(){return{}};var TA=new wA,EA=45e3,SA={},kA={};function CA(e,t,n){e.K=1,e.v=QA(KA(t)),e.s=n,e.U=!0,AA(e,null)}function AA(e,t){e.F=Date.now(),xA(e),e.A=KA(e.v);var o,a,c,l,u,h,n=e.A,r=e.X;Array.isArray(r)||(r=[String(r)]),cN(n.h,"t",r),e.C=0,n=e.l.H,e.h=new IA,e.g=cR(e.l,n?t:null,!e.s),0<e.O&&(e.L=new ZC(qk(e.Ia,e,e.g),e.O)),nA(e.V,e.g,"readystatechange",e.gb),t=e.H?tC(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.s,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),uA(),o=e.j,a=e.u,c=e.A,l=e.m,u=e.X,h=e.s,o.info(function(){if(o.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+a+"\n"+c+"\n"+e})}function NA(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function RA(e,t,n){let r=!0,i;for(;!e.I&&e.C<n.length;){if(i=(o=n,c=a=void 0,a=(s=e).C,-1==(c=o.indexOf("\n",a))?kA:(a=Number(o.substring(a,c)),isNaN(a)?SA:(c+=1)+a>o.length?kA:(o=o.substr(c,a),s.C=c+a,o))),i==kA){4==t&&(e.o=4,dA(14),r=!1),sA(e.j,e.m,null,"[Incomplete Response]");break}if(i==SA){e.o=4,dA(15),sA(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}sA(e.j,e.m,i,null),LA(e,i)}var s,o,a,c;NA(e)&&i!=kA&&i!=SA&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,dA(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.aa&&(e.aa=!0,(t=e.l).g==e&&t.$&&!t.L&&(t.h.info("Great, no buffering proxy detected. Bytes received: "+n.length),eR(t),t.L=!0,dA(11))):(sA(e.j,e.m,n,"[Invalid Chunked Response]"),MA(e),OA(e))}function xA(e){e.Y=Date.now()+e.P,PA(e,e.P)}function PA(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=pA(qk(e.eb,e),t)}function DA(e){e.B&&(xk.clearTimeout(e.B),e.B=null)}function OA(e){0==e.l.G||e.I||rR(e.l,e)}function MA(e){DA(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,JC(e.W),rA(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function LA(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||gN(n.i,e)))if(n.I=e.N,!e.J&&gN(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;nR(n),WN(n)}ZN(n),dA(18)}}else n.ta=i[1],0<n.ta-n.U&&i[2]<37500&&n.N&&0==n.A&&!n.v&&(n.v=pA(qk(n.ab,n),6e3));if(pN(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else sR(n,11)}else if(!e.J&&n.g!=e||nR(n),!Hk(t))for(i=n.Ca.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.U=s[0],s=s[1],2==n.G)if("c"==s[0]){n.J=s[1],n.la=s[2];var o=s[3];null!=o&&(n.ma=o,n.h.info("VER="+n.ma));var a=s[4];null!=a&&(n.za=a,n.h.info("SVER="+n.za));var c,l,u,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.K=r,n.h.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;g&&(!(c=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(l=r.i).g&&(Jk(c,"spdy")||Jk(c,"quic")||Jk(c,"h2"))&&(l.j=l.l,l.g=new Set,l.h&&(mN(l,l.h),l.h=null)),!r.D||(u=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=u,HA(r.F,r.D,u))),n.G=3,n.j&&n.j.xa(),n.$&&(n.O=Date.now()-e.F,n.h.info("Handshake RTT: "+n.O+"ms"));var d,f,p=e;(r=n).oa=aR(r,r.H?r.la:null,r.W),p.J?(vN(r.i,p),d=p,(f=r.K)&&d.setTimeout(f),d.B&&(DA(d),xA(d)),r.g=p):XN(r),0<n.l.length&&HN(n)}else"stop"!=s[0]&&"close"!=s[0]||sR(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?sR(n,7):$N(n):"noop"!=s[0]&&n.j&&n.j.wa(s),n.A=0)}uA()}catch(e){}}function FA(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Dk(e)||"string"==typeof e)Wk(e,t,void 0);else{if(e.T&&"function"==typeof e.T)var n=e.T();else if(e.R&&"function"==typeof e.R)n=void 0;else if(Dk(e)||"string"==typeof e)for(var n=[],r=e.length,i=0;i<r;i++)n.push(i);else for(i in n=[],r=0,e)n[r++]=i;for(var i=(r=function(e){if(e.R&&"function"==typeof e.R)return e.R();if("string"==typeof e)return e.split("");if(Dk(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e)).length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}}function UA(e,t){this.h={},this.g=[],this.i=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(e)if(e instanceof UA)for(n=e.T(),r=0;r<n.length;r++)this.set(n[r],e.get(n[r]));else for(r in e)this.set(r,e[r])}function qA(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];jA(e.h,r)&&(e.g[n++]=r),t++}e.g.length=n}if(e.i!=e.g.length){for(var i={},n=t=0;t<e.g.length;)jA(i,r=e.g[t])||(i[e.g[n++]=r]=1),t++;e.g.length=n}}function jA(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(ze=bA.prototype).setTimeout=function(e){this.P=e},ze.gb=function(e){e=e.target;const t=this.L;t&&3==qN(e)?t.l():this.Ia(e)},ze.Ia=function(e){try{if(e==this.g)e:{var t=qN(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||lC||this.g&&(this.h.h||this.g.ga()||jN(this.g)))){this.I||4!=t||7==n||uA(),DA(this);var r=this.g.ba();this.N=r;t:if(NA(this)){var i=jN(this.g);e="";var s=i.length,o=4==qN(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){MA(this),OA(this);var a="";break t}this.h.i=new xk.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:o&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.ga();if(this.i=200==r,h=this.j,d=this.u,f=this.A,p=this.m,g=this.X,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+g+"]: "+d+"\n"+f+"\n"+m+" "+v}),this.i){if(this.$&&!this.J){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!Hk(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,dA(12),MA(this),OA(this);break e}sA(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,LA(this,r)}this.U?(RA(this,t,a),lC&&this.i&&3==t&&(nA(this.V,this.W,"tick",this.fb),this.W.start())):(sA(this.j,this.m,a,null),LA(this,a)),4==t&&MA(this),this.i&&!this.I&&(4==t?rR(this.l,this):(this.i=!1,xA(this)))}else 400==r&&0<a.indexOf("Unknown SID")?(this.o=3,dA(12)):(this.o=0,dA(13)),MA(this),OA(this)}}}catch(e){}var h,d,f,p,g,m,v},ze.fb=function(){var e,t;this.g&&(e=qN(this.g),t=this.g.ga(),this.C<t.length&&(DA(this),RA(this,e,t),this.i&&4!=e&&xA(this)))},ze.cancel=function(){this.I=!0,MA(this)},ze.eb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.K&&(uA(),dA(17)),MA(this),this.o=2,OA(this)):PA(this,this.Y-n)},(ze=UA.prototype).R=function(){qA(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},ze.T=function(){return qA(this),this.g.concat()},ze.get=function(e,t){return jA(this.h,e)?this.h[e]:t},ze.set=function(e,t){jA(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},ze.forEach=function(e,t){for(var n=this.T(),r=0;r<n.length;r++){var i=n[r],s=this.get(i);e.call(t,s,i,this)}};var VA=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function BA(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof BA?(this.g=void 0!==t?t:e.g,$A(this,e.j),this.s=e.s,WA(this,e.i),zA(this,e.m),this.l=e.l,t=e.h,(n=new iN).i=t.i,t.g&&(n.g=new UA(t.g),n.h=t.h),GA(this,n),this.o=e.o):e&&(n=String(e).match(VA))?(this.g=!!t,$A(this,n[1]||"",!0),this.s=YA(n[2]||""),WA(this,n[3]||"",!0),zA(this,n[4]),this.l=YA(n[5]||"",!0),GA(this,n[6]||"",!0),this.o=YA(n[7]||"")):(this.g=!!t,this.h=new iN(null,this.g))}function KA(e){return new BA(e)}function $A(e,t,n){e.j=n?YA(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function WA(e,t,n){e.i=n?YA(t,!0):t}function zA(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function GA(e,t,n){var r,i;t instanceof iN?(e.h=t,r=e.h,(i=e.g)&&!r.j&&(sN(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(oN(this,t),cN(this,n,e))},r)),r.j=i):(n||(t=JA(t,nN)),e.h=new iN(t,e.g))}function HA(e,t,n){e.h.set(t,n)}function QA(e){return HA(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function YA(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function JA(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,XA),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function XA(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}BA.prototype.toString=function(){var e=[],t=this.j;t&&e.push(JA(t,ZA,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(JA(t,ZA,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&e.push("/"),e.push(JA(n,"/"==n.charAt(0)?tN:eN,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",JA(n,rN)),e.join("")};var ZA=/[#\/\?@]/g,eN=/[#\?:]/g,tN=/[#\?]/g,nN=/[#\?@]/g,rN=/#/g;function iN(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function sN(n){n.g||(n.g=new UA,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function oN(e,t){sN(e),t=lN(e,t),jA(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,jA((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&qA(e)))}function aN(e,t){return sN(e),t=lN(e,t),jA(e.g.h,t)}function cN(e,t,n){oN(e,t),0<n.length&&(e.i=null,e.g.set(lN(e,t),Gk(n)),e.h+=n.length)}function lN(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(ze=iN.prototype).add=function(e,t){sN(this),this.i=null,e=lN(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},ze.forEach=function(n,r){sN(this),this.g.forEach(function(e,t){Wk(e,function(e){n.call(r,e,t,this)},this)},this)},ze.T=function(){sN(this);for(var e=this.g.R(),t=this.g.T(),n=[],r=0;r<t.length;r++)for(var i=e[r],s=0;s<i.length;s++)n.push(t[r]);return n},ze.R=function(e){sN(this);var t=[];if("string"==typeof e)aN(this,e)&&(t=zk(t,this.g.get(lN(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=zk(t,e[n])}return t},ze.set=function(e,t){return sN(this),this.i=null,aN(this,e=lN(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},ze.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},ze.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=this.g.T(),n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),r=this.R(r),s=0;s<r.length;s++){var o=i;""!==r[s]&&(o+="="+encodeURIComponent(String(r[s]))),e.push(o)}return this.i=e.join("&")};var uN=class{constructor(e,t){this.h=e,this.g=t}};function hN(e){this.l=e||10,e=xk.PerformanceNavigationTiming?0<(e=xk.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(xk.g&&xk.g.Ea&&xk.g.Ea()&&xk.g.Ea().Zb),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var dN;function fN(e){return e.h||e.g&&e.g.size>=e.j}function pN(e){return e.h?1:e.g?e.g.size:0}function gN(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function mN(e,t){e.g?e.g.add(t):e.h=t}function vN(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function yN(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Gk(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function _N(){}function wN(){this.g=new _N}function bN(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function IN(e){this.l=e.$b||null,this.j=e.ib||!1}function TN(e,t){qC.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=EN,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}hN.prototype.cancel=function(){if(this.i=yN(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},_N.prototype.stringify=function(e){return xk.JSON.stringify(e,void 0)},_N.prototype.parse=function(e){return xk.JSON.parse(e,void 0)},Vk(IN,gA),IN.prototype.g=function(){return new TN(this.l,this.j)},IN.prototype.i=(dN={},function(){return dN}),Vk(TN,qC);var EN=0;function SN(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function kN(e){e.readyState=4,e.l=null,e.j=null,e.A=null,CN(e)}function CN(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(ze=TN.prototype).open=function(e,t){if(this.readyState!=EN)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,CN(this)},ze.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||xk).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},ze.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,kN(this)),this.readyState=EN},ze.Va=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,CN(this)),this.g&&(this.readyState=3,CN(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==xk.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;SN(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},ze.Sa=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?kN:CN)(this),3==this.readyState&&SN(this))},ze.Ua=function(e){this.g&&(this.response=this.responseText=e,kN(this))},ze.Ta=function(e){this.g&&(this.response=e,kN(this))},ze.ha=function(){this.g&&kN(this)},ze.setRequestHeader=function(e,t){this.v.append(e,t)},ze.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},ze.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(TN.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var AN=xk.JSON.parse;function NN(e){qC.call(this),this.headers=new UA,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=RN,this.K=this.L=!1}Vk(NN,qC);var RN="",xN=/^https?$/i,PN=["POST","PUT"];function DN(e){return"content-type"==e.toLowerCase()}function ON(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,MN(e),FN(e)}function MN(e){e.D||(e.D=!0,jC(e,"complete"),jC(e,"error"))}function LN(e){if(e.h&&void 0!==Rk&&(!e.C[1]||4!=qN(e)||2!=e.ba()))if(e.v&&4==qN(e))XC(e.Fa,0,e);else if(jC(e,"readystatechange"),4==qN(e)){e.h=!1;try{var t,n,r,i,s=e.ba();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break e;default:o=!1}if((t=o)||((n=0===s)&&(!(i=String(e.H).match(VA)[1]||null)&&xk.self&&xk.self.location&&(i=(r=xk.self.location.protocol).substr(0,r.length-1)),n=!xN.test(i?i.toLowerCase():"")),t=n),t)jC(e,"complete"),jC(e,"success");else{e.m=6;try{var a=2<qN(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.ba()+"]",MN(e)}}finally{FN(e)}}}function FN(e,t){if(e.g){UN(e);const n=e.g,r=e.C[0]?Pk:null;e.g=null,e.C=null,t||jC(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function UN(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(xk.clearTimeout(e.A),e.A=null)}function qN(e){return e.g?e.g.readyState:0}function jN(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case RN:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function VN(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return eC(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):HA(e,t,n))}function BN(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function KN(e){this.za=0,this.l=[],this.h=new iA,this.la=this.oa=this.F=this.W=this.g=this.sa=this.D=this.aa=this.o=this.P=this.s=null,this.Za=this.V=0,this.Xa=BN("failFast",!1,e),this.N=this.v=this.u=this.m=this.j=null,this.X=!0,this.I=this.ta=this.U=-1,this.Y=this.A=this.C=0,this.Pa=BN("baseRetryDelayMs",5e3,e),this.$a=BN("retryDelaySeedMs",1e4,e),this.Ya=BN("forwardChannelMaxRetries",2,e),this.ra=BN("forwardChannelRequestTimeoutMs",2e4,e),this.qa=e&&e.xmlHttpFactory||void 0,this.Ba=e&&e.Yb||!1,this.K=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.J="",this.i=new hN(e&&e.concurrentRequestLimit),this.Ca=new wN,this.ja=e&&e.fastHandshake||!1,this.Ra=e&&e.Wb||!1,e&&e.Aa&&this.h.Aa(),e&&e.forceLongPolling&&(this.X=!1),this.$=!this.ja&&this.X&&e&&e.detectBufferingProxy||!1,this.ka=void 0,this.O=0,this.L=!1,this.B=null,this.Wa=!e||!1!==e.Xb}function $N(e){var t,n;zN(e),3==e.G&&(t=e.V++,HA(n=KA(e.F),"SID",e.J),HA(n,"RID",t),HA(n,"TYPE","terminate"),YN(e,n),(t=new bA(e,e.h,t,void 0)).K=2,t.v=QA(KA(n)),n=!1,!(n=xk.navigator&&xk.navigator.sendBeacon?xk.navigator.sendBeacon(t.v.toString(),""):n)&&xk.Image&&((new Image).src=t.v,n=!0),n||(t.g=cR(t.l,null),t.g.ea(t.v)),t.F=Date.now(),xA(t)),oR(e)}function WN(e){e.g&&(eR(e),e.g.cancel(),e.g=null)}function zN(e){WN(e),e.u&&(xk.clearTimeout(e.u),e.u=null),nR(e),e.i.cancel(),e.m&&("number"==typeof e.m&&xk.clearTimeout(e.m),e.m=null)}function GN(e,t){e.l.push(new uN(e.Za++,t)),3==e.G&&HN(e)}function HN(e){fN(e.i)||e.m||(e.m=!0,zC(e.Ha,e),e.C=0)}function QN(e,t){var n=t?t.m:e.V++,r=KA(e.F);HA(r,"SID",e.J),HA(r,"RID",n),HA(r,"AID",e.U),YN(e,r),e.o&&e.s&&VN(r,e.o,e.s),n=new bA(e,e.h,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.l=t.D.concat(e.l)),t=JN(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),mN(e.i,n),CA(n,r,t)}function YN(e,n){e.j&&FA({},function(e,t){HA(n,t,e)})}function JN(e,t,r){r=Math.min(e.l.length,r);var i=e.j?qk(e.j.Oa,e.j,e):null;e:{var s=e.l;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].h,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var o=s[t].h,a=s[t].g;if((o-=n)<0)n=Math.max(0,s[t].h-100),e=!1;else try{!function(e,r,t){const i=t||"";try{FA(e,function(e,t){let n=e;Ok(e)&&(n=BC(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(a,c,"req"+o+"_")}catch(e){i&&i(a)}}if(e){i=c.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,i}function XN(e){e.g||e.u||(e.Y=1,zC(e.Ga,e),e.A=0)}function ZN(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=pA(qk(e.Ga,e),iR(e,e.A)),e.A++,1)}function eR(e){null!=e.B&&(xk.clearTimeout(e.B),e.B=null)}function tR(e){e.g=new bA(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=KA(e.oa);HA(t,"RID","rpc"),HA(t,"SID",e.J),HA(t,"CI",e.N?"0":"1"),HA(t,"AID",e.U),YN(e,t),HA(t,"TYPE","xmlhttp"),e.o&&e.s&&VN(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=QA(KA(t)),n.s=null,n.U=!0,AA(n,e)}function nR(e){null!=e.v&&(xk.clearTimeout(e.v),e.v=null)}function rR(e,t){var n,r,i,s=null;if(e.g==t){nR(e),eR(e),e.g=null;var o=2}else{if(!gN(e.i,t))return;s=t.D,vN(e.i,t),o=1}if(e.I=t.N,0!=e.G)if(t.i)1==o?(s=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,jC(o=cA(),new fA(o,s)),HN(e)):XN(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=o||(i=t,pN((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.l=i.D.concat(r.l),0):1==r.G||2==r.G||r.C>=(r.Xa?0:r.Ya)||(r.m=pA(qk(r.Ha,r,i),iR(r,r.C)),r.C++,0))))&&(2!=o||!ZN(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:sR(e,5);break;case 4:sR(e,10);break;case 3:sR(e,6);break;default:sR(e,2)}}function iR(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function sR(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=qk(e.jb,e),n||(n=new BA("//www.google.com/images/cleardot.gif"),xk.location&&"http"==xk.location.protocol||$A(n,"https"),QA(n)),function(e,t){var n=new iA;if(xk.Image){const r=new Image;r.onload=jk(bN,n,r,"TestLoadImage: loaded",!0,t),r.onerror=jk(bN,n,r,"TestLoadImage: error",!1,t),r.onabort=jk(bN,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=jk(bN,n,r,"TestLoadImage: timeout",!1,t),xk.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):dA(2),e.G=0,e.j&&e.j.va(t),oR(e),zN(e)}function oR(e){e.G=0,e.I=-1,e.j&&(0==yN(e.i).length&&0==e.l.length||(e.i.i.length=0,Gk(e.l),e.l.length=0),e.j.ua())}function aR(e,t,n){let r=(a=n)instanceof BA?KA(a):new BA(a,void 0);var i,s,o,a,c;return""!=r.i?(t&&WA(r,t+"."+r.i),zA(r,r.m)):(c=xk.location,r=(i=c.protocol,s=t?t+"."+c.hostname:c.hostname,o=+c.port,a=n,c=new BA(null,void 0),i&&$A(c,i),s&&WA(c,s),o&&zA(c,o),a&&(c.l=a),c)),e.aa&&eC(e.aa,function(e,t){HA(r,t,e)}),t=e.D,n=e.sa,t&&n&&HA(r,t,n),HA(r,"VER",e.ma),YN(e,r),r}function cR(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ba&&!e.qa?new NN(new IN({ib:!0})):new NN(e.qa)).L=e.H,t}function lR(){}function uR(){if(aC&&!(10<=Number(vC)))throw Error("Environmental error: no available transport.")}function hR(e,t){qC.call(this),this.g=new KN(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.P=e,(e=t&&t.httpHeadersOverwriteParam)&&!Hk(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Hk(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new pR(this)}function dR(e){yA.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function fR(){_A.call(this),this.status=1}function pR(e){this.g=e}(ze=NN.prototype).ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||TA).g(),this.C=this.u?mA(this.u):mA(TA),this.g.onreadystatechange=qk(this.Fa,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void ON(this,e)}e=n||"";const i=new UA(this.headers);r&&FA(r,function(e,t){i.set(t,e)}),r=function(t){e:{var n=DN,r=t.length,i="string"==typeof t?t.split(""):t;for(let e=0;e<r;e++)if(e in i&&n.call(void 0,i[e],e,t)){n=e;break e}n=-1}return n<0?null:"string"==typeof t?t.charAt(n):t[n]}(i.T()),n=xk.FormData&&e instanceof xk.FormData,0<=$k(PN,t)&&!r&&!n&&i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(e,t){this.g.setRequestHeader(t,e)},this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{UN(this),0<this.B&&((this.K=(s=this.g,aC&&mC()&&"number"==typeof s.timeout&&void 0!==s.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=qk(this.pa,this)):this.A=XC(this.pa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){ON(this,e)}var s},ze.pa=function(){void 0!==Rk&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,jC(this,"timeout"),this.abort(8))},ze.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,jC(this,"complete"),jC(this,"abort"),FN(this))},ze.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),FN(this,!0)),NN.Z.M.call(this)},ze.Fa=function(){this.s||(this.F||this.v||this.l?LN(this):this.cb())},ze.cb=function(){LN(this)},ze.ba=function(){try{return 2<qN(this)?this.g.status:-1}catch(e){return-1}},ze.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},ze.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),AN(t)}},ze.Da=function(){return this.m},ze.La=function(){return"string"==typeof this.j?this.j:String(this.j)},(ze=KN.prototype).ma=8,ze.G=1,ze.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},ze.Ha=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;const s=new bA(this,this.h,t,void 0);let e=this.s;if(this.P&&(e?(e=tC(e),rC(e,this.P)):e=this.P),null===this.o&&(s.H=e),this.ja)e:{for(var n=0,r=0;r<this.l.length;r++){var i=this.l[r];if("__data__"in i.g&&"string"==typeof(i=i.g.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.l.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=JN(this,s,n),HA(r=KA(this.F),"RID",t),HA(r,"CVER",22),this.D&&HA(r,"X-HTTP-Session-Id",this.D),YN(this,r),this.o&&e&&VN(r,this.o,e),mN(this.i,s),this.Ra&&HA(r,"TYPE","init"),this.ja?(HA(r,"$req",n),HA(r,"SID","null"),s.$=!0,CA(s,r,null)):CA(s,r,n),this.G=2}}else 3==this.G&&(t?QN(this,t):0==this.l.length||fN(this.i)||QN(this))},ze.Ga=function(){var e;this.u=null,tR(this),this.$&&!(this.L||null==this.g||this.O<=0)&&(e=2*this.O,this.h.info("BP detection timer enabled: "+e),this.B=pA(qk(this.bb,this),e))},ze.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,dA(10),WN(this),tR(this))},ze.ab=function(){null!=this.v&&(this.v=null,WN(this),ZN(this),dA(19))},ze.jb=function(e){e?(this.h.info("Successfully pinged google.com"),dA(2)):(this.h.info("Failed to ping google.com"),dA(1))},(ze=lR.prototype).xa=function(){},ze.wa=function(){},ze.va=function(){},ze.ua=function(){},ze.Oa=function(){},uR.prototype.g=function(e,t){return new hR(e,t)},Vk(hR,qC),hR.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),zC(qk(e.hb,e,t))),dA(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=aR(e,null,e.W),HN(e)},hR.prototype.close=function(){$N(this.g)},hR.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,GN(this.g,t)):this.v?((t={}).__data__=BC(e),GN(this.g,t)):GN(this.g,e)},hR.prototype.M=function(){this.g.j=null,delete this.j,$N(this.g),delete this.g,hR.Z.M.call(this)},Vk(dR,yA),Vk(fR,_A),Vk(pR,lR),pR.prototype.xa=function(){jC(this.g,"a")},pR.prototype.wa=function(e){jC(this.g,new dR(e))},pR.prototype.va=function(e){jC(this.g,new fR)},pR.prototype.ua=function(){jC(this.g,"b")},uR.prototype.createWebChannel=uR.prototype.g,hR.prototype.send=hR.prototype.u,hR.prototype.open=hR.prototype.m,c.NO_ERROR=0,c.TIMEOUT=8,c.HTTP_ERROR=6,yt.COMPLETE="complete",(vA.EventType=l).OPEN="a",l.CLOSE="b",l.ERROR="c",l.MESSAGE="d",qC.prototype.listen=qC.prototype.N,NN.prototype.listenOnce=NN.prototype.O,NN.prototype.getLastError=NN.prototype.La,NN.prototype.getLastErrorCode=NN.prototype.Da,NN.prototype.getStatus=NN.prototype.ba,NN.prototype.getResponseJson=NN.prototype.Qa,NN.prototype.getResponseText=NN.prototype.ga,NN.prototype.send=NN.prototype.ea;var gR,mR=cA,vR=c,yR=yt,_R=oA,wR=10,bR=11,IR=IN,TR=vA,ER=NN;const SR="@firebase/firestore";class kR{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}kR.UNAUTHENTICATED=new kR(null),kR.GOOGLE_CREDENTIALS=new kR("google-credentials-uid"),kR.FIRST_PARTY=new kR("first-party-uid"),kR.MOCK_USER=new kR("mock-user");let CR="9.7.0";const AR=new cf("@firebase/firestore");function NR(){return AR.logLevel}function RR(e,...t){var n;AR.logLevel<=$h.DEBUG&&(n=t.map(DR),AR.debug(`Firestore (${CR}): ${e}`,...n))}function xR(e,...t){var n;AR.logLevel<=$h.ERROR&&(n=t.map(DR),AR.error(`Firestore (${CR}): ${e}`,...n))}function PR(e,...t){var n;AR.logLevel<=$h.WARN&&(n=t.map(DR),AR.warn(`Firestore (${CR}): ${e}`,...n))}function DR(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function OR(e="Unexpected state"){var t=`FIRESTORE (${CR}) INTERNAL ASSERTION FAILED: `+e;throw xR(t),new Error(t)}function MR(e){e||OR()}const LR={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FR extends gd{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class UR{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class qR{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class jR{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(kR.UNAUTHENTICATED))}shutdown(){}}class VR{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class BR{constructor(e){this.t=e,this.currentUser=kR.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new UR;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new UR,t.enqueueRetryable(()=>i(this.currentUser))};const o=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},a=e=>{RR("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),o()};this.t.onInit(e=>a(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?a(e):(RR("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new UR))},0),o()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(RR("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(MR("string"==typeof e.accessToken),new qR(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return MR(null===e||"string"==typeof e),new kR(e)}}class KR{constructor(e,t,n){this.type="FirstParty",this.user=kR.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);var r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class $R{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new KR(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(kR.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class WR{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class zR{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null,this.p=null}start(t,n){const r=e=>{null!=e.error&&RR("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.p;return this.p=e.token,RR("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{RR("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?i(e):RR("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(MR("string"==typeof e.token),this.p=e.token,new WR(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class GR{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.I(e),this.T=e=>t.writeSequenceNumber(e))}I(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}GR.A=-1;class HR{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function QR(e,t){return e<t?-1:t<e?1:0}function YR(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function JR(e){return e+"\0"}class XR{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new FR(LR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new FR(LR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new FR(LR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new FR(LR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return XR.fromMillis(Date.now())}static fromDate(e){return XR.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new XR(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?QR(this.nanoseconds,e.nanoseconds):QR(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class ZR{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ZR(e)}static min(){return new ZR(new XR(0,0))}static max(){return new ZR(new XR(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function ex(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tx(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function nx(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class rx{constructor(e,t,n){void 0===t?t=0:t>e.length&&OR(),void 0===n?n=e.length-t:n>e.length-t&&OR(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===rx.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof rx?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ix extends rx{construct(e,t,n){return new ix(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new FR(LR.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new ix(t)}static emptyPath(){return new ix([])}}const sx=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ox extends rx{construct(e,t,n){return new ox(e,t,n)}static isValidIdentifier(e){return sx.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!ox.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new ox(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new FR(LR.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new FR(LR.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new FR(LR.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new FR(LR.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new ox(t)}static emptyPath(){return new ox([])}}class ax{constructor(e){(this.fields=e).sort(ox.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return YR(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class cx{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new cx(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new cx(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return QR(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}cx.EMPTY_BYTE_STRING=new cx("");const lx=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ux(t){if(MR(!!t),"string"!=typeof t)return{seconds:hx(t.seconds),nanos:hx(t.nanos)};{let e=0;var n=lx.exec(t);MR(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function hx(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function dx(e){return"string"==typeof e?cx.fromBase64String(e):cx.fromUint8Array(e)}function fx(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function px(e){var t=ux(e.mapValue.fields.__local_write_time__.timestampValue);return new XR(t.seconds,t.nanos)}class gx{constructor(e,t,n,r,i,s,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class mx{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new mx("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof mx&&e.projectId===this.projectId&&e.database===this.database}}function vx(e){return null==e}function yx(e){return 0===e&&1/e==-1/0}function _x(e){return"number"==typeof e&&Number.isInteger(e)&&!yx(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class wx{constructor(e){this.path=e}static fromPath(e){return new wx(ix.fromString(e))}static fromName(e){return new wx(ix.fromString(e).popFirst(5))}static empty(){return new wx(ix.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ix.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ix.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new wx(new ix(e.slice()))}}const bx={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Ix={nullValue:"NULL_VALUE"};function Tx(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?fx(e)?4:Lx(e)?9007199254740991:10:OR()}function Ex(r,i){if(r===i)return!0;var e,t,n=Tx(r);if(n!==Tx(i))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return px(r).isEqual(px(i));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=ux(r.timestampValue),n=ux(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,dx(r.bytesValue).isEqual(dx(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,hx((t=r).geoPointValue.latitude)===hx(e.geoPointValue.latitude)&&hx(t.geoPointValue.longitude)===hx(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return hx(e.integerValue)===hx(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=hx(e.doubleValue),r=hx(t.doubleValue);return n===r?yx(n)===yx(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return YR(r.arrayValue.values||[],i.arrayValue.values||[],Ex);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(ex(t)!==ex(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!Ex(t[e],n[e])))return!1;return!0}(r);default:return OR()}}function Sx(e,t){return void 0!==(e.values||[]).find(e=>Ex(e,t))}function kx(e,t){if(e===t)return 0;var n,r,i,s,o=Tx(e),a=Tx(t);if(o!==a)return QR(o,a);switch(o){case 0:case 9007199254740991:return 0;case 1:return QR(e.booleanValue,t.booleanValue);case 2:return r=t,i=hx(e.integerValue||e.doubleValue),s=hx(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Cx(e.timestampValue,t.timestampValue);case 4:return Cx(px(e),px(t));case 5:return QR(e.stringValue,t.stringValue);case 6:return function(e,t){const n=dx(e),r=dx(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=QR(n[i],r[i]);if(0!==t)return t}return QR(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=QR(hx(n.latitude),hx(r.latitude)))?s:QR(hx(n.longitude),hx(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=kx(n[i],r[i]);if(t)return t}return QR(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===bx.mapValue&&t===bx.mapValue)return 0;if(e===bx.mapValue)return 1;if(t===bx.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let a=0;a<r.length&&a<s.length;++a){const t=QR(r[a],s[a]);if(0!==t)return t;var o=kx(n[r[a]],i[s[a]]);if(0!==o)return o}return QR(r.length,s.length)}(e.mapValue,t.mapValue);default:throw OR()}}function Cx(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return QR(e,t);var n=ux(e),r=ux(t),i=QR(n.seconds,r.seconds);return 0!==i?i:QR(n.nanos,r.nanos)}function Ax(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=ux(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?dx(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,wx.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):OR();var t}(e)}function Nx(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Rx(e){return e&&"integerValue"in e}function xx(e){return!!e&&"arrayValue"in e}function Px(e){return e&&"nullValue"in e}function Dx(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Ox(e){return e&&"mapValue"in e}function Mx(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return tx(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Mx(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Mx(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Lx(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Fx(e,t){var n=kx(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Ux(e,t){var n=kx(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class qx{constructor(e){this.value=e}static empty(){return new qx({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!Ox(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Mx(t)}setAll(e){let n=ox.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Mx(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Ox(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ex(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];Ox(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){tx(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new qx(Mx(this.value))}}class jx{constructor(e,t,n,r,i,s){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=i,this.documentState=s}static newInvalidDocument(e){return new jx(e,0,ZR.min(),ZR.min(),qx.empty(),0)}static newFoundDocument(e,t,n){return new jx(e,1,t,ZR.min(),n,0)}static newNoDocument(e,t){return new jx(e,2,t,ZR.min(),qx.empty(),0)}static newUnknownDocument(e,t){return new jx(e,3,t,ZR.min(),qx.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=qx.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=qx.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof jx&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new jx(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Vx{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Bx(e){return e.fields.find(e=>2===e.kind)}function Kx(e){return e.fields.filter(e=>2!==e.kind)}Vx.UNKNOWN_ID=-1;class $x{constructor(e,t){this.fieldPath=e,this.kind=t}}class Wx{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Wx(0,Gx.min())}}function zx(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=ZR.fromTimestamp(1e9===r?new XR(n+1,0):new XR(n,r));return new Gx(r,wx.empty(),t)}class Gx{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Gx(ZR.min(),wx.empty(),-1)}static max(){return new Gx(ZR.max(),wx.empty(),-1)}}function Hx(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=wx.comparator(e.documentKey,t.documentKey),0!==n?n:QR(e.largestBatchId,t.largestBatchId))}class Qx{constructor(e,t){this.comparator=e,this.root=t||Jx.EMPTY}insert(e,t){return new Qx(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Jx.BLACK,null,null))}remove(e){return new Qx(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Jx.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new Yx(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Yx(this.root,e,this.comparator,!1)}getReverseIterator(){return new Yx(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Yx(this.root,e,this.comparator,!0)}}class Yx{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class Jx{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Jx.RED,this.left=null!=r?r:Jx.EMPTY,this.right=null!=i?i:Jx.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new Jx(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return Jx.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return Jx.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,Jx.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,Jx.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw OR();if(this.right.isRed())throw OR();var e=this.left.check();if(e!==this.right.check())throw OR();return e+(this.isRed()?0:1)}}Jx.EMPTY=null,Jx.RED=!0,Jx.BLACK=!1,Jx.EMPTY=new class{constructor(){this.size=0}get key(){throw OR()}get value(){throw OR()}get color(){throw OR()}get left(){throw OR()}get right(){throw OR()}copy(e,t,n,r,i){return this}insert(e,t,n){return new Jx(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class Xx{constructor(e){this.comparator=e,this.data=new Qx(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Zx(this.data.getIterator())}getIteratorFrom(e){return new Zx(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof Xx))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new Xx(this.comparator);return t.data=e,t}}class Zx{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function eP(e){return e.hasNext()?e.getNext():void 0}class tP{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.P=null}}function nP(e,t=null,n=[],r=[],i=null,s=null,o=null){return new tP(e,t,n,r,i,s,o)}function rP(e){const t=e;if(null===t.P){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>{return(t=e).field.canonicalString()+t.op.toString()+Ax(t.value);var t}).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),vx(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ax(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ax(e)).join(",")),t.P=e}return t.P}function iP(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let o=0;o<e.orderBy.length;o++)if(n=e.orderBy[o],r=t.orderBy[o],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,i,s;if(e.filters.length!==t.filters.length)return!1;for(let a=0;a<e.filters.length;a++)if(i=e.filters[a],s=t.filters[a],i.op!==s.op||!i.field.isEqual(s.field)||!Ex(i.value,s.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!bP(e.startAt,t.startAt)&&bP(e.endAt,t.endAt)}function sP(e){return wx.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function oP(e,t){return e.filters.filter(e=>e instanceof lP&&e.field.isEqual(t))}function aP(t,n,r){let i=Ix,s=!0;for(const r of oP(t,n)){let e=Ix,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(o=r.value)?Ix:"booleanValue"in o?{booleanValue:!1}:"integerValue"in o||"doubleValue"in o?{doubleValue:NaN}:"timestampValue"in o?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in o?{stringValue:""}:"bytesValue"in o?{bytesValue:""}:"referenceValue"in o?Nx(mx.empty(),wx.empty()):"geoPointValue"in o?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in o?{arrayValue:{}}:"mapValue"in o?{mapValue:{}}:OR();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Ix}Fx({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var o;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Fx({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function cP(t,n,r){let i=bx,s=!0;for(const r of oP(t,n)){let e=bx,t=!0;switch(r.op){case">=":case">":e="nullValue"in(o=r.value)?{booleanValue:!1}:"booleanValue"in o?{doubleValue:NaN}:"integerValue"in o||"doubleValue"in o?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in o?{stringValue:""}:"stringValue"in o?{bytesValue:""}:"bytesValue"in o?Nx(mx.empty(),wx.empty()):"referenceValue"in o?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in o?{arrayValue:{}}:"arrayValue"in o?{mapValue:{}}:"mapValue"in o?bx:OR(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=bx}0<Ux({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var o;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Ux({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class lP extends class{}{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.V(e,t,n):new uP(e,t,n):"array-contains"===t?new pP(e,n):"in"===t?new gP(e,n):"not-in"===t?new mP(e,n):"array-contains-any"===t?new vP(e,n):new lP(e,t,n)}static V(e,t,n){return new("in"===t?hP:dP)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.v(kx(t,this.value)):null!==t&&Tx(this.value)===Tx(t)&&this.v(kx(t,this.value))}v(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return OR()}}S(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class uP extends lP{constructor(e,t,n){super(e,t,n),this.key=wx.fromName(n.referenceValue)}matches(e){var t=wx.comparator(e.key,this.key);return this.v(t)}}class hP extends lP{constructor(e,t){super(e,"in",t),this.keys=fP(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class dP extends lP{constructor(e,t){super(e,"not-in",t),this.keys=fP(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function fP(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>wx.fromName(e.referenceValue))}class pP extends lP{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return xx(t)&&Sx(t.arrayValue,this.value)}}class gP extends lP{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Sx(this.value.arrayValue,t)}}class mP extends lP{constructor(e,t){super(e,"not-in",t)}matches(e){if(Sx(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Sx(this.value.arrayValue,t)}}class vP extends lP{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!xx(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Sx(this.value.arrayValue,e))}}class yP{constructor(e,t){this.position=e,this.inclusive=t}}class _P{constructor(e,t="asc"){this.field=e,this.dir=t}}function wP(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?wx.comparator(wx.fromName(o.referenceValue),n.key):kx(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function bP(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ex(e.position[n],t.position[n]))return!1;return!0}class IP{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.D=null,this.C=null,this.startAt,this.endAt}}function TP(e,t,n,r,i,s,o,a){return new IP(e,t,n,r,i,s,o,a)}function EP(e){return new IP(e)}function SP(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function kP(e){for(const t of e.filters)if(t.S())return t.field;return null}function CP(e){return null!==e.collectionGroup}function AP(t){const n=t;if(null===n.D){n.D=[];const t=kP(n),e=SP(n);if(null!==t&&null===e)t.isKeyField()||n.D.push(new _P(t)),n.D.push(new _P(ox.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.D.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.D.push(new _P(ox.keyField(),t))}}}return n.D}function NP(e){const t=e;if(!t.C)if("F"===t.limitType)t.C=nP(t.path,t.collectionGroup,AP(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of AP(t)){const t="desc"===i.dir?"asc":"desc";e.push(new _P(i.field,t))}var n=t.endAt?new yP(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new yP(t.startAt.position,t.startAt.inclusive):null;t.C=nP(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.C}function RP(e,t,n){return new IP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function xP(e,t){return iP(NP(e),NP(t))&&e.limitType===t.limitType}function PP(e){return`${rP(NP(e))}|lt:${e.limitType}`}function DP(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>{return`${(t=e).field.canonicalString()} ${t.op} ${Ax(t.value)}`;var t}).join(", ")}]`),vx(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ax(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ax(e)).join(",")),`Target(${t})`}(NP(e))}; limitType=${e.limitType})`}function OP(n,e){return e.isFoundDocument()&&(i=n,o=(s=e).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(o):wx.isDocumentKey(i.path)?i.path.isEqual(o):i.path.isImmediateParentOf(o))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(i=e,(!(e=n).startAt||(t=e.startAt,r=wP(t,AP(e),i),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=wP(t,AP(e),i),t.inclusive?0<=r:0<r)));var t,r,i,s,o}function MP(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function LP(i){return(e,t)=>{let n=!1;for(const r of AP(i)){const i=function(e,i,t){var n=e.field.isKeyField()?wx.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?kx(n,r):OR()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return OR()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}function FP(e,t){if(e.N){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:yx(t)?"-0":t}}function UP(e){return{integerValue:""+e}}function qP(e,t){return _x(t)?UP(t):FP(e,t)}class jP{constructor(){this._=void 0}}function VP(e,t){return e instanceof GP?Rx(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class BP extends jP{}class KP extends jP{constructor(e){super(),this.elements=e}}function $P(e,t){const n=QP(t);for(const t of e.elements)n.some(e=>Ex(e,t))||n.push(t);return{arrayValue:{values:n}}}class WP extends jP{constructor(e){super(),this.elements=e}}function zP(e,t){let n=QP(t);for(const t of e.elements)n=n.filter(e=>!Ex(e,t));return{arrayValue:{values:n}}}class GP extends jP{constructor(e,t){super(),this.M=e,this.k=t}}function HP(e){return hx(e.integerValue||e.doubleValue)}function QP(e){return xx(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class YP{constructor(e,t){this.field=e,this.transform=t}}class JP{constructor(e,t){this.version=e,this.transformResults=t}}class XP{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new XP}static exists(e){return new XP(void 0,e)}static updateTime(e){return new XP(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function ZP(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class eD{}function tD(e,t,n){e instanceof sD?function(e,t,n){const r=e.value.clone(),i=cD(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof oD?function(e,t,n){if(!ZP(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=cD(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(aD(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function nD(e,t,n){e instanceof sD?function(e,t,n){if(ZP(e.precondition,t)){const r=e.value.clone(),i=lD(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(iD(t),r).setHasLocalMutations()}}(e,t,n):e instanceof oD?function(e,t,n){if(ZP(e.precondition,t)){const r=lD(e.fieldTransforms,n,t),i=t.data;i.setAll(aD(e)),i.setAll(r),t.convertToFoundDocument(iD(t),i).setHasLocalMutations()}}(e,t,n):(t=t,ZP(e.precondition,t)&&t.convertToNoDocument(ZR.min()))}function rD(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&YR(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof KP&&t instanceof KP||e instanceof WP&&t instanceof WP?YR(e.elements,t.elements,Ex):e instanceof GP&&t instanceof GP?Ex(e.k,t.k):e instanceof BP&&t instanceof BP)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}function iD(e){return e.isFoundDocument()?e.version:ZR.min()}class sD extends eD{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class oD extends eD{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}}function aD(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function cD(e,t,n){const r=new Map;MR(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,o=t.data.field(i.field);r.set(i.field,(a=s,c=o,l=n[u],a instanceof KP?$P(a,c):a instanceof WP?zP(a,c):l))}var a,c,l;return r}function lD(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,o=t,c=a=void 0,i instanceof BP?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}};return s&&(e.fields.__previous_value__=s),{mapValue:e}}():i instanceof KP?$P(i,s):i instanceof WP?zP(i,s):(a=VP(i=i,s),c=HP(a)+HP(i.k),Rx(a)&&Rx(i.k)?UP(c):FP(i.M,c))))}var i,s,o,a,c;return r}class uD extends eD{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class hD extends eD{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class dD{constructor(e){this.count=e}}function fD(e){switch(e){default:return OR(),0;case LR.CANCELLED:case LR.UNKNOWN:case LR.DEADLINE_EXCEEDED:case LR.RESOURCE_EXHAUSTED:case LR.INTERNAL:case LR.UNAVAILABLE:case LR.UNAUTHENTICATED:return;case LR.INVALID_ARGUMENT:case LR.NOT_FOUND:case LR.ALREADY_EXISTS:case LR.PERMISSION_DENIED:case LR.FAILED_PRECONDITION:case LR.ABORTED:case LR.OUT_OF_RANGE:case LR.UNIMPLEMENTED:case LR.DATA_LOSS:return 1}}function pD(e){if(void 0===e)return xR("GRPC error has no .code"),LR.UNKNOWN;switch(e){case gR.OK:return LR.OK;case gR.CANCELLED:return LR.CANCELLED;case gR.UNKNOWN:return LR.UNKNOWN;case gR.DEADLINE_EXCEEDED:return LR.DEADLINE_EXCEEDED;case gR.RESOURCE_EXHAUSTED:return LR.RESOURCE_EXHAUSTED;case gR.INTERNAL:return LR.INTERNAL;case gR.UNAVAILABLE:return LR.UNAVAILABLE;case gR.UNAUTHENTICATED:return LR.UNAUTHENTICATED;case gR.INVALID_ARGUMENT:return LR.INVALID_ARGUMENT;case gR.NOT_FOUND:return LR.NOT_FOUND;case gR.ALREADY_EXISTS:return LR.ALREADY_EXISTS;case gR.PERMISSION_DENIED:return LR.PERMISSION_DENIED;case gR.FAILED_PRECONDITION:return LR.FAILED_PRECONDITION;case gR.ABORTED:return LR.ABORTED;case gR.OUT_OF_RANGE:return LR.OUT_OF_RANGE;case gR.UNIMPLEMENTED:return LR.UNIMPLEMENTED;case gR.DATA_LOSS:return LR.DATA_LOSS;default:return OR()}}(c=gR=gR||{})[c.OK=0]="OK",c[c.CANCELLED=1]="CANCELLED",c[c.UNKNOWN=2]="UNKNOWN",c[c.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",c[c.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",c[c.NOT_FOUND=5]="NOT_FOUND",c[c.ALREADY_EXISTS=6]="ALREADY_EXISTS",c[c.PERMISSION_DENIED=7]="PERMISSION_DENIED",c[c.UNAUTHENTICATED=16]="UNAUTHENTICATED",c[c.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",c[c.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",c[c.ABORTED=10]="ABORTED",c[c.OUT_OF_RANGE=11]="OUT_OF_RANGE",c[c.UNIMPLEMENTED=12]="UNIMPLEMENTED",c[c.INTERNAL=13]="INTERNAL",c[c.UNAVAILABLE=14]="UNAVAILABLE",c[c.DATA_LOSS=15]="DATA_LOSS";class gD{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){tx(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return nx(this.inner)}size(){return this.innerSize}}const mD=new Qx(wx.comparator);const vD=new Qx(wx.comparator);function yD(...e){let t=vD;for(const n of e)t=t.insert(n.key,n);return t}function _D(){return new gD(e=>e.toString(),(e,t)=>e.isEqual(t))}const wD=new Qx(wx.comparator),bD=new Xx(wx.comparator);function ID(...e){let t=bD;for(const n of e)t=t.add(n);return t}const TD=new Xx(QR);class ED{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,SD.createSynthesizedTargetChangeForCurrentChange(e,t)),new ED(ZR.min(),n,TD,mD,ID())}}class SD{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t){return new SD(cx.EMPTY_BYTE_STRING,t,ID(),ID(),ID())}}class kD{constructor(e,t,n,r){this.O=e,this.removedTargetIds=t,this.key=n,this.F=r}}class CD{constructor(e,t){this.targetId=e,this.$=t}}class AD{constructor(e,t,n=cx.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ND{constructor(){this.B=0,this.L=PD(),this.U=cx.EMPTY_BYTE_STRING,this.q=!1,this.K=!0}get current(){return this.q}get resumeToken(){return this.U}get G(){return 0!==this.B}get j(){return this.K}W(e){0<e.approximateByteSize()&&(this.K=!0,this.U=e)}H(){let n=ID(),r=ID(),i=ID();return this.L.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:OR()}}),new SD(this.U,this.q,n,r,i)}J(){this.K=!1,this.L=PD()}Y(e,t){this.K=!0,this.L=this.L.insert(e,t)}X(e){this.K=!0,this.L=this.L.remove(e)}Z(){this.B+=1}tt(){--this.B}et(){this.K=!0,this.q=!0}}class RD{constructor(e){this.nt=e,this.st=new Map,this.it=mD,this.rt=xD(),this.ot=new Xx(QR)}ut(e){for(const t of e.O)e.F&&e.F.isFoundDocument()?this.at(t,e.F):this.ct(t,e.key,e.F);for(const n of e.removedTargetIds)this.ct(n,e.key,e.F)}ht(n){this.forEachTarget(n,e=>{const t=this.lt(e);switch(n.state){case 0:this.ft(e)&&t.W(n.resumeToken);break;case 1:t.tt(),t.G||t.J(),t.W(n.resumeToken);break;case 2:t.tt(),t.G||this.removeTarget(e);break;case 3:this.ft(e)&&(t.et(),t.W(n.resumeToken));break;case 4:this.ft(e)&&(this.dt(e),t.W(n.resumeToken));break;default:OR()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.st.forEach((e,t)=>{this.ft(t)&&n(t)})}_t(e){const t=e.targetId,n=e.$.count,r=this.wt(t);if(r){const e=r.target;if(sP(e))if(0===n){const n=new wx(e.path);this.ct(t,n,jx.newNoDocument(n,ZR.min()))}else MR(1===n);else this.gt(t)!==n&&(this.dt(t),this.ot=this.ot.add(t))}}yt(r){const i=new Map;this.st.forEach((e,t)=>{var n=this.wt(t);if(n){if(e.current&&sP(n.target)){const i=new wx(n.target.path);null!==this.it.get(i)||this.It(t,i)||this.ct(t,i,jx.newNoDocument(i,r))}e.j&&(i.set(t,e.H()),e.J())}});let s=ID();this.rt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.wt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.it.forEach((e,t)=>t.setReadTime(r));var e=new ED(r,i,this.ot,this.it,s);return this.it=mD,this.rt=xD(),this.ot=new Xx(QR),e}at(e,t){var n;this.ft(e)&&(n=this.It(e,t.key)?2:0,this.lt(e).Y(t.key,n),this.it=this.it.insert(t.key,t),this.rt=this.rt.insert(t.key,this.Tt(t.key).add(e)))}ct(e,t,n){if(this.ft(e)){const r=this.lt(e);this.It(e,t)?r.Y(t,1):r.X(t),this.rt=this.rt.insert(t,this.Tt(t).delete(e)),n&&(this.it=this.it.insert(t,n))}}removeTarget(e){this.st.delete(e)}gt(e){var t=this.lt(e).H();return this.nt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Z(e){this.lt(e).Z()}lt(e){let t=this.st.get(e);return t||(t=new ND,this.st.set(e,t)),t}Tt(e){let t=this.rt.get(e);return t||(t=new Xx(QR),this.rt=this.rt.insert(e,t)),t}ft(e){var t=null!==this.wt(e);return t||RR("WatchChangeAggregator","Detected inactive target",e),t}wt(e){var t=this.st.get(e);return t&&t.G?null:this.nt.Et(e)}dt(t){this.st.set(t,new ND),this.nt.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}It(e,t){return this.nt.getRemoteKeysForTarget(e).has(t)}}function xD(){return new Qx(wx.comparator)}function PD(){return new Qx(wx.comparator)}const DD={asc:"ASCENDING",desc:"DESCENDING"},OD={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class MD{constructor(e,t){this.databaseId=e,this.N=t}}function LD(e,t){return e.N?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function FD(e,t){return e.N?t.toBase64():t.toUint8Array()}function UD(e){return MR(!!e),ZR.fromTimestamp((t=ux(e),new XR(t.seconds,t.nanos)));var t}function qD(e,t){return e=e,new ix(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function jD(e){var t=ix.fromString(e);return MR(i1(t)),t}function VD(e,t){return qD(e.databaseId,t.path)}function BD(e,t){const n=jD(t);if(n.get(1)!==e.databaseId.projectId)throw new FR(LR.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new FR(LR.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new wx(zD(n))}function KD(e,t){return qD(e.databaseId,t)}function $D(e){var t=jD(e);return 4===t.length?ix.emptyPath():zD(t)}function WD(e){return new ix(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function zD(e){return MR(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function GD(e,t,n){return{name:VD(e,t),fields:n.value.mapValue.fields}}function HD(e,t,n){const r=BD(e,t.name),i=UD(t.updateTime),s=new qx({mapValue:{fields:t.fields}}),o=jx.newFoundDocument(r,i,s);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function QD(e,t){let n;if(t instanceof sD)n={update:GD(e,t.key,t.value)};else if(t instanceof uD)n={delete:VD(e,t.key)};else if(t instanceof oD)n={update:GD(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof hD))return OR();n={verify:VD(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof BP)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof KP)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof WP)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof GP)return{fieldPath:e.field.canonicalString(),increment:t.k};throw OR()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,LD(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:OR()),n;var r}function YD(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?XP.updateTime(UD(i.updateTime)):void 0!==i.exists?XP.exists(i.exists):XP.none():XP.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)MR("REQUEST_TIME"===t.setToServerValue),n=new BP;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new KP(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new WP(e)}else"increment"in t?n=new GP(e,t.increment):OR();var r=ox.fromServerFormat(t.fieldPath);return new YP(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=BD(t,n.update.name),o=new qx({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new ax(e.map(e=>ox.fromServerFormat(e)))}();return new oD(s,o,t,e,r)}return new sD(s,o,e,r)}if(n.delete){const r=BD(t,n.delete);return new uD(r,e)}if(n.verify){const r=BD(t,n.verify);return new hD(r,e)}return OR()}function JD(e,t){return{documents:[KD(e,t.path)]}}function XD(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=KD(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=KD(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if(Dx(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NAN"}};if(Px(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Dx(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NOT_NAN"}};if(Px(e.value))return{unaryFilter:{field:e1(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:e1(e.field),op:(t=e.op,OD[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:e1(e.field),direction:(e=e.dir,DD[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.N||vx(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(i=t.startAt).inclusive,values:i.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function ZD(e){let t=$D(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){MR(1===r);const p=n.from[0];p.allDescendants?i=p.collectionId:t=t.child(p.collectionId)}let s=[];n.where&&(s=function t(e){return e?void 0!==e.unaryFilter?[r1(e)]:void 0!==e.fieldFilter?[n1(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):OR():[]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new _P(t1(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let a=null;var c,l,u,h;n.limit&&(a=(e=n.limit,vx(c="object"==typeof e?e.value:e)?null:c));let d=null;n.startAt&&(d=(l=n.startAt,h=!!l.before,u=l.values||[],new yP(u,h)));let f=null;return n.endAt&&(f=(l=n.endAt,u=!l.before,h=l.values||[],new yP(h,u))),TP(t,i,o,s,a,"F",d,f)}function e1(e){return{fieldPath:e.canonicalString()}}function t1(e){return ox.fromServerFormat(e.fieldPath)}function n1(e){return lP.create(t1(e.fieldFilter.field),function(){switch(e.fieldFilter.op){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return OR()}}(),e.fieldFilter.value)}function r1(e){switch(e.unaryFilter.op){case"IS_NAN":var t=t1(e.unaryFilter.field);return lP.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=t1(e.unaryFilter.field);return lP.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=t1(e.unaryFilter.field);return lP.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=t1(e.unaryFilter.field);return lP.create(n,"!=",{nullValue:"NULL_VALUE"});default:return OR()}}function i1(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function s1(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=o1(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return o1(t)}function o1(e){return e+""}function a1(t){const n=t.length;if(MR(2<=n),2===n)return MR(""===t.charAt(0)&&""===t.charAt(1)),ix.emptyPath();const r=n-2,i=[];let s="";for(let o=0;o<n;){const n=t.indexOf("",o);switch((n<0||n>r)&&OR(),t.charAt(n+1)){case"":const r=t.substring(o,n);let e;0===s.length?e=r:(s+=r,e=s,s=""),i.push(e);break;case"":s+=t.substring(o,n),s+="\0";break;case"":s+=t.substring(o,n+1);break;default:OR()}o=n+2}return new ix(i)}const c1=["userId","batchId"];function l1(e,t){return[e,s1(t)]}function u1(e,t,n){return[e,s1(t),n]}const h1={},d1=["prefixPath","collectionGroup","readTime","documentId"],f1=["prefixPath","collectionGroup","documentId"],p1=["collectionGroup","readTime","prefixPath","documentId"],g1=["canonicalId","targetId"],m1=["targetId","path"],v1=["path","targetId"],y1=["collectionId","parent"],_1=["indexId","uid"],w1=["uid","sequenceNumber"],b1=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],I1=["indexId","uid","orderedDocumentKey"],T1=["userId","collectionPath","documentId"],E1=["userId","collectionPath","largestBatchId"],S1=["userId","collectionGroup","largestBatchId"],k1=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],C1=[...k1,"documentOverlays"],A1=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],N1=[...A1,"indexConfiguration","indexState","indexEntries"],R1="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class x1{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class P1{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&OR(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new P1((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof P1?t:P1.resolve(t)}catch(e){return P1.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):P1.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):P1.reject(t)}static resolve(n){return new P1((e,t)=>{e(n)})}static reject(n){return new P1((e,t)=>{t(n)})}static waitFor(e){return new P1((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=P1.resolve(!1);for(const n of e)t=t.next(e=>e?P1.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}}class D1{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.At=new UR,this.transaction.oncomplete=()=>{this.At.resolve()},this.transaction.onabort=()=>{e.error?this.At.reject(new L1(n,e.error)):this.At.resolve()},this.transaction.onerror=e=>{var t=V1(e.target.error);this.At.reject(new L1(n,t))}}static open(e,t,n,r){try{return new D1(t,e.transaction(r,n))}catch(e){throw new L1(t,e)}}get Rt(){return this.At.promise}abort(e){e&&this.At.reject(e),this.aborted||(RR("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}Pt(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new U1(t)}}class O1{constructor(e,t,n){this.name=e,this.version=t,this.bt=n,12.2===O1.Vt(sd())&&xR("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return RR("SimpleDb","Removing database:",e),q1(window.indexedDB.deleteDatabase(e)).toPromise()}static vt(){if(!dd())return!1;if(O1.St())return!0;const e=sd(),t=O1.Vt(e),n=0<t&&t<10,r=O1.Dt(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static St(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Ct)}static xt(e,t){return e.store(t)}static Vt(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static Dt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Nt(s){return this.db||(RR("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new L1(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new FR(LR.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new FR(LR.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new L1(s,t))},i.onupgradeneeded=e=>{RR("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.bt.kt(t,i.transaction,e.oldVersion,this.version).next(()=>{RR("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Mt&&(this.db.onversionchange=e=>this.Mt(e)),this.db}Ot(t){this.Mt=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.Nt(e);const t=D1.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.Pt(),e)).catch(e=>(t.abort(e),P1.reject(e))).toPromise();return s.catch(()=>{}),await t.Rt,s}catch(e){const t="FirebaseError"!==e.name&&s<3;if(RR("SimpleDb","Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}class M1{constructor(e){this.Ft=e,this.$t=!1,this.Bt=null}get isDone(){return this.$t}get Lt(){return this.Bt}set cursor(e){this.Ft=e}done(){this.$t=!0}Ut(e){this.Bt=e}delete(){return q1(this.Ft.delete())}}class L1 extends FR{constructor(e,t){super(LR.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function F1(e){return"IndexedDbTransactionError"===e.name}class U1{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(RR("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(RR("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),q1(n)}add(e){return RR("SimpleDb","ADD",this.store.name,e,e),q1(this.store.add(e))}get(t){return q1(this.store.get(t)).next(e=>(RR("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return RR("SimpleDb","DELETE",this.store.name,e),q1(this.store.delete(e))}count(){return RR("SimpleDb","COUNT",this.store.name),q1(this.store.count())}qt(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.Kt(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new P1((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}Gt(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new P1((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Qt(e,t){RR("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.jt=!1;var r=this.cursor(n);return this.Kt(r,(e,t,n)=>n.delete())}Wt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Kt(r,t)}zt(i){const e=this.cursor({});return new P1((n,r)=>{e.onerror=e=>{var t=V1(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}Kt(e,s){const o=[];return new P1((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new M1(t),r=s(t.primaryKey,t.value,n);if(r instanceof P1){const e=r.catch(e=>(n.done(),P1.reject(e)));o.push(e)}n.isDone?i():null===n.Lt?t.continue():t.continue(n.Lt)}else i()}}).next(()=>P1.waitFor(o))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.jt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function q1(e){return new P1((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=V1(e.target.error);r(t)}})}let j1=!1;function V1(e){const t=O1.Vt(sd());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new FR("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return j1||(j1=!0,setTimeout(()=>{throw e},0)),e}}return e}class B1 extends x1{constructor(e,t){super(),this.Ht=e,this.currentSequenceNumber=t}}function K1(e,t){var n=e;return O1.xt(n.Ht,t)}class $1{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&tD(i,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&nD(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&nD(n,e,this.localWriteTime)}applyToLocalDocumentSet(r){this.mutations.forEach(e=>{const t=r.get(e.key),n=t;this.applyToLocalView(n),t.isValidDocument()||n.convertToNoDocument(ZR.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),ID())}isEqual(e){return this.batchId===e.batchId&&YR(this.mutations,e.mutations,(e,t)=>rD(e,t))&&YR(this.baseMutations,e.baseMutations,(e,t)=>rD(e,t))}}class W1{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){MR(e.mutations.length===n.length);let r=wD;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new W1(e,t,n,r)}}class z1{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class G1{constructor(e,t,n,r,i=ZR.min(),s=ZR.min(),o=cx.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o}withSequenceNumber(e){return new G1(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new G1(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new G1(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class H1{constructor(e){this.Jt=e}}function Q1(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Y1(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:VD(i=e.Jt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:LD(i,e.version.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:J1(t.version)};else{if(!t.isUnknownDocument())return OR();r.unknownDocument={path:n.path.toArray(),version:J1(t.version)}}var i;return r}function Y1(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function J1(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function X1(e){var t=new XR(e.seconds,e.nanoseconds);return ZR.fromTimestamp(t)}function Z1(t,e){const n=(e.baseMutations||[]).map(e=>YD(t.Jt,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>YD(t.Jt,e)),i=XR.fromMillis(e.localWriteTimeMs);return new $1(e.batchId,i,n,r)}function eO(e){var t,n=X1(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?X1(e.lastLimboFreeSnapshotVersion):ZR.min();let i;return i=void 0!==e.query.documents?(MR(1===(t=e.query).documents.length),NP(EP($D(t.documents[0])))):NP(ZD(e.query)),new G1(i,e.targetId,0,e.lastListenSequenceNumber,n,r,cx.fromBase64String(e.resumeToken))}function tO(e,t){var n=J1(t.snapshotVersion),r=J1(t.lastLimboFreeSnapshotVersion),i=(sP(t.target)?JD:XD)(e.Jt,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:rP(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function nO(e){var t=ZD({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?RP(t,t.limit,"L"):t}function rO(e,t){return new z1(t.largestBatchId,YD(e.Jt,t.overlayMutation))}function iO(e,t){var n=t.path.lastSegment();return[e,s1(t.path.popLast()),n]}class sO{getBundleMetadata(e,t){return oO(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:X1(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return oO(e).put({bundleId:(n=t).id,createTime:J1(UD(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return aO(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:nO(t.bundledQuery),readTime:X1(t.readTime)};var t})}saveNamedQuery(e,t){return aO(e).put({name:(t=t).name,readTime:J1(UD(t.readTime)),bundledQuery:t.bundledQuery})}}function oO(e){return K1(e,"bundles")}function aO(e){return K1(e,"namedQueries")}class cO{constructor(e,t){this.M=e,this.userId=t}static Yt(e,t){var n=t.uid||"";return new cO(e,n)}getOverlay(e,t){return lO(e).get(iO(this.userId,t)).next(e=>e?rO(this.M,e):null)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new z1(i,t);s.push(this.Xt(r,n))}),P1.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(s1(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(lO(n).Qt("collectionPathOverlayIndex",t))}),P1.waitFor(i)}getOverlaysForCollection(e,t,n){const r=_D(),i=s1(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return lO(e).qt("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=rO(this.M,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=_D();let o;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return lO(e).Wt({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=rO(this.M,t);s.size()<i||r.largestBatchId===o?(s.set(r.getKey(),r),o=r.largestBatchId):n.done()}).next(()=>s)}Xt(e,t){return lO(e).put(function(e,t,n){var[,r,i]=iO(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:QD(e.Jt,n.mutation)}}(this.M,this.userId,t))}}function lO(e){return K1(e,"documentOverlays")}class uO{constructor(){}Zt(e,t){this.te(e,t),t.ee()}te(e,t){var n,r;"nullValue"in e?this.ne(t,5):"booleanValue"in e?(this.ne(t,10),t.se(e.booleanValue?1:0)):"integerValue"in e?(this.ne(t,15),t.se(hx(e.integerValue))):"doubleValue"in e?(n=hx(e.doubleValue),isNaN(n)?this.ne(t,13):(this.ne(t,15),yx(n)?t.se(0):t.se(n))):"timestampValue"in e?(r=e.timestampValue,this.ne(t,20),"string"==typeof r?t.ie(r):(t.ie(`${r.seconds||""}`),t.se(r.nanos||0))):"stringValue"in e?(this.re(e.stringValue,t),this.oe(t)):"bytesValue"in e?(this.ne(t,30),t.ue(dx(e.bytesValue)),this.oe(t)):"referenceValue"in e?this.ae(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.ne(t,45),t.se(r.latitude||0),t.se(r.longitude||0)):"mapValue"in e?Lx(e)?this.ne(t,Number.MAX_SAFE_INTEGER):(this.ce(e.mapValue,t),this.oe(t)):"arrayValue"in e?(this.he(e.arrayValue,t),this.oe(t)):OR()}re(e,t){this.ne(t,25),this.le(e,t)}le(e,t){t.ie(e)}ce(e,t){var n=e.fields||{};this.ne(t,55);for(const e of Object.keys(n))this.re(e,t),this.te(n[e],t)}he(e,t){var n=e.values||[];this.ne(t,50);for(const e of n)this.te(e,t)}ae(e,t){this.ne(t,37),wx.fromName(e).path.forEach(e=>{this.ne(t,60),this.le(e,t)})}ne(e,t){e.se(t)}oe(e){e.se(2)}}function hO(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}uO.fe=new uO;class dO{constructor(){this.buffer=new Uint8Array(1024),this.position=0}de(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this._e(n.value),n=t.next();this.we()}me(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.ge(n.value),n=t.next();this.ye()}pe(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this._e(e);else if(e<2048)this._e(960|e>>>6),this._e(128|63&e);else if(t<"\ud800"||"\udbff"<t)this._e(480|e>>>12),this._e(128|63&e>>>6),this._e(128|63&e);else{const e=t.codePointAt(0);this._e(240|e>>>18),this._e(128|63&e>>>12),this._e(128|63&e>>>6),this._e(128|63&e)}}this.we()}Ie(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.ge(e);else if(e<2048)this.ge(960|e>>>6),this.ge(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.ge(480|e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e);else{const e=t.codePointAt(0);this.ge(240|e>>>18),this.ge(128|63&e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e)}}this.ye()}Te(e){var t=this.Ee(e),n=hO(t);this.Ae(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Re(e){var t=this.Ee(e),n=hO(t);this.Ae(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}Pe(){this.be(255),this.be(255)}Ve(){this.ve(255),this.ve(255)}reset(){this.position=0}seed(e){this.Ae(e.length),this.buffer.set(e,this.position),this.position+=e.length}Se(){return this.buffer.slice(0,this.position)}Ee(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}_e(e){var t=255&e;0==t?(this.be(0),this.be(255)):255==t?(this.be(255),this.be(0)):this.be(t)}ge(e){var t=255&e;0==t?(this.ve(0),this.ve(255)):255==t?(this.ve(255),this.ve(0)):this.ve(e)}we(){this.be(0),this.be(1)}ye(){this.ve(0),this.ve(1)}be(e){this.Ae(1),this.buffer[this.position++]=e}ve(e){this.Ae(1),this.buffer[this.position++]=~e}Ae(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class fO{constructor(e){this.De=e}ue(e){this.De.de(e)}ie(e){this.De.pe(e)}se(e){this.De.Te(e)}ee(){this.De.Pe()}}class pO{constructor(e){this.De=e}ue(e){this.De.me(e)}ie(e){this.De.Ie(e)}se(e){this.De.Re(e)}ee(){this.De.Ve()}}class gO{constructor(){this.De=new dO,this.Ce=new fO(this.De),this.xe=new pO(this.De)}seed(e){this.De.seed(e)}Ne(e){return 0===e?this.Ce:this.xe}Se(){return this.De.Se()}reset(){this.De.reset()}}class mO{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}ke(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new mO(this.indexId,this.documentKey,this.arrayValue,n)}}function vO(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=yO(e.arrayValue,t.arrayValue),0!==n?n:(n=yO(e.directionalValue,t.directionalValue),0!==n?n:wx.comparator(e.documentKey,t.documentKey)))}function yO(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class _O{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Me=e.orderBy,this.Oe=[];for(const t of e.filters){const e=t;e.S()?this.Fe=e:this.Oe.push(e)}}$e(e){var t=Bx(e);if(void 0!==t&&!this.Be(t))return!1;var n=Kx(e);let r=0,i=0;for(;r<n.length&&this.Be(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Fe){const e=n[r];if(!this.Le(this.Fe,e)||!this.Ue(this.Me[i++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(i>=this.Me.length||!this.Ue(this.Me[i++],e))return!1}return!0}Be(e){for(const t of this.Oe)if(this.Le(t,e))return!0;return!1}Le(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}Ue(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}class wO{constructor(){this.qe=new bO}addToCollectionParentIndex(e,t){return this.qe.add(t),P1.resolve()}getCollectionParents(e,t){return P1.resolve(this.qe.getEntries(t))}addFieldIndex(e,t){return P1.resolve()}deleteFieldIndex(e,t){return P1.resolve()}getDocumentsMatchingTarget(e,t){return P1.resolve(null)}getIndexType(e,t){return P1.resolve(0)}getFieldIndexes(e,t){return P1.resolve([])}getNextCollectionGroupToUpdate(e){return P1.resolve(null)}getMinOffset(e,t){return P1.resolve(Gx.min())}updateCollectionGroup(e,t,n){return P1.resolve()}updateIndexEntries(e,t){return P1.resolve()}}class bO{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Xx(ix.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new Xx(ix.comparator)).toArray()}}const IO=new Uint8Array(0);class TO{constructor(e,t){this.user=e,this.databaseId=t,this.Ke=new bO,this.Ge=new gD(e=>rP(e),(e,t)=>iP(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Ke.has(t))return P1.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ke.add(t)});r={collectionId:n,parent:s1(r)};return EO(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[JR(n),""],!1,!0);return EO(e).qt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(a1(t.parent))}return r})}addFieldIndex(e,t){const n=kO(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};return delete r.indexId,n.add(r).next()}deleteFieldIndex(e,t){const n=kO(e),r=CO(e),i=SO(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,l){const u=SO(e);let h=!0;const n=new Map;return P1.forEach(this.Qe(l),t=>this.je(e,t).next(e=>{h=h&&!!e,n.set(t,e)})).next(()=>{if(h){let c=ID();const h=[];return P1.forEach(n,(e,t)=>{RR("IndexedDbIndexManager",`Using index ${a=e,`id=${a.indexId}|cg=${a.collectionGroup}|f=${a.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${rP(l)}`);var n=function(e,t){var n=Bx(t);if(void 0===n)return null;for(const t of oP(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of Kx(t))for(const t of oP(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),i=function(e,t){const n=[];let r=!0;for(const i of Kx(t)){const t=(0===i.kind?aP:cP)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new yP(n,r)}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of Kx(t)){const t=(0===i.kind?cP:aP)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new yP(n,r)}(t,e),o=this.We(e,t,i),a=this.We(e,t,s),r=this.ze(e,t,r),r=this.He(e.indexId,n,o,i.inclusive,a,s.inclusive,r);return P1.forEach(r,e=>u.Gt(e,l.limit).next(e=>{e.forEach(e=>{var t=wx.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),h.push(t))})}))}).next(()=>h)}return P1.resolve(null)})}Qe(e){var t;return(t=this.Ge.get(e))||(this.Ge.set(e,t=[e]),t)}He(t,e,n,r,i,s,o){const a=(null!=e?e.length:1)*Math.max(n.length,i.length),c=a/(null!=e?e.length:1),l=[];for(let u=0;u<a;++u){const a=e?this.Je(e[u/c]):IO,h=this.Ye(t,a,n[u%c],r),d=this.Xe(t,a,i[u%c],s),f=o.map(e=>this.Ye(t,a,e,!0));l.push(...this.createRange(h,d,f))}return l}Ye(e,t,n,r){const i=new mO(e,wx.empty(),t,n);return r?i:i.ke()}Xe(e,t,n,r){const i=new mO(e,wx.empty(),t,n);return r?i.ke():i}je(e,t){const r=new _O(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.$e(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;return P1.forEach(this.Qe(t),t=>this.je(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new Xx(ox.comparator),n=!1;for(const r of e.filters){const e=r;e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field))}for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>n)}Ze(e,t){const n=new gO;for(const i of Kx(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Ne(i.kind);uO.fe.Zt(e,r)}return n.Se()}Je(e){const t=new gO;return uO.fe.Zt(e,t.Ne(0)),t.Se()}tn(e,t){const n=new gO;return uO.fe.Zt(Nx(this.databaseId,t),n.Ne(0===(r=Kx(e)).length?0:r[r.length-1].kind)),n.Se();var r}ze(e,t,n){if(null===n)return[];let r=[];r.push(new gO);let i=0;for(const s of Kx(e)){const e=n[i++];for(const n of r)if(this.en(t,s.fieldPath)&&xx(e))r=this.nn(r,s,e);else{const t=n.Ne(s.kind);uO.fe.Zt(e,t)}}return this.sn(r)}We(e,t,n){return this.ze(e,t,n.position)}sn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Se();return t}nn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new gO;r.seed(n.Se()),uO.fe.Zt(e,r.Ne(t.kind)),i.push(r)}return i}en(e,t){return!!e.filters.find(e=>e instanceof lP&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=kO(e),r=CO(e);return(t?n.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.qt()).next(e=>{const s=[];return P1.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new Wx(e.sequenceNumber,new Gx(X1(e.readTime),new wx(a1(e.documentKey)),e.largestBatchId)):Wx.empty(),r=t.fields.map(([e,t])=>new $x(ox.fromServerFormat(e),t)),new Vx(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:QR(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){const i=kO(e),s=CO(e);return this.rn(e).next(r=>i.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(e=>P1.forEach(e,e=>s.put(function(e,t,n){return{indexId:e,uid:t.uid||"",sequenceNumber:r,readTime:J1(n.readTime),documentKey:s1(n.documentKey.path),largestBatchId:n.largestBatchId}}(e.indexId,this.user,n)))))}updateIndexEntries(i,e){const n=new Map;return P1.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?P1.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),P1.forEach(e,n=>this.on(i,t,n).next(e=>{var t=this.un(r,n);return e.isEqual(t)?P1.resolve():this.an(i,r,n,e,t)}))))})}cn(e,t,n,r){return SO(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.tn(n,t.key),documentKey:t.key.path.toArray()})}hn(e,t,n,r){return SO(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.tn(n,t.key),t.key.path.toArray()])}on(e,n,r){const t=SO(e);let i=new Xx(vO);return t.Wt({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.tn(r,n)])},(e,t)=>{i=i.add(new mO(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}un(e,t){let n=new Xx(vO);var r=this.Ze(t,e);if(null==r)return n;const i=Bx(t);if(null!=i){var s=e.data.field(i.fieldPath);if(xx(s))for(const i of s.arrayValue.values||[])n=n.add(new mO(t.indexId,e.key,this.Je(i),r))}else n=n.add(new mO(t.indexId,e.key,IO,r));return n}an(t,n,r,l,e){RR("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const i=[];return function(e,n,r,i){var s=l.getIterator(),o=e.getIterator();let a=eP(s),c=eP(o);for(;a||c;){let e=!1,t=!1;if(a&&c){const r=n(a,c);r<0?t=!0:0<r&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(c),c=eP(o)):t?(i(a),a=eP(s)):(a=eP(s),c=eP(o))}}(e,vO,e=>{i.push(this.cn(t,n,r,e))},e=>{i.push(this.hn(t,n,r,e))}),P1.waitFor(i)}rn(e){let r=1;return CO(e).Wt({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>vO(e,t)).filter((e,t,n)=>!t||0!==vO(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=vO(i,e),s=vO(i,t);if(0===n)r[0]=e.ke();else if(0<n&&s<0)r.push(i),r.push(i.ke());else if(0<s)break}r.push(t);const i=[];for(let o=0;o<r.length;o+=2)i.push(IDBKeyRange.bound([r[o].indexId,this.uid,r[o].arrayValue,r[o].directionalValue,IO,[]],[r[o+1].indexId,this.uid,r[o+1].arrayValue,r[o+1].directionalValue,IO,[]]));return i}getMinOffset(t,e){let n;return P1.forEach(this.Qe(e),e=>this.je(t,e).next(e=>{e?(!n||Hx(e.indexState.offset,n)<0)&&(n=e.indexState.offset):n=Gx.min()})).next(()=>n)}}function EO(e){return K1(e,"collectionParents")}function SO(e){return K1(e,"indexEntries")}function kO(e){return K1(e,"indexConfiguration")}function CO(e){return K1(e,"indexState")}const AO={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class NO{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new NO(e,NO.DEFAULT_COLLECTION_PERCENTILE,NO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function RO(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.Wt({range:o},(e,t,n)=>(a++,n.delete()));s.push(c.next(()=>{MR(1===a)}));const l=[];for(const e of n.mutations){const r=u1(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return P1.waitFor(s).next(()=>l)}function xO(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw OR();t=e.noDocument}return JSON.stringify(t).length}NO.DEFAULT_COLLECTION_PERCENTILE=10,NO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,NO.DEFAULT=new NO(41943040,NO.DEFAULT_COLLECTION_PERCENTILE,NO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),NO.DISABLED=new NO(-1,0,0);class PO{constructor(e,t,n,r){this.userId=e,this.M=t,this.indexManager=n,this.referenceDelegate=r,this.ln={}}static Yt(e,t,n,r){MR(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new PO(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return OO(e).Wt({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,f){const p=MO(u),g=OO(u);return g.add({}).next(e=>{MR("number"==typeof e);const t=new $1(e,h,d,f),n=(i=this.M,s=this.userId,o=t,a=o.baseMutations.map(e=>QD(i.Jt,e)),c=o.mutations.map(e=>QD(i.Jt,e)),{userId:s,batchId:o.batchId,localWriteTimeMs:o.localWriteTime.toMillis(),baseMutations:a,mutations:c}),r=[];var i,s,o,a,c;let l=new Xx((e,t)=>QR(e.canonicalString(),t.canonicalString()));for(const u of f){const h=u1(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(p.put(h,h1))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.ln[e]=t.keys()}),P1.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return OO(e).get(t).next(e=>e?(MR(e.userId===this.userId),Z1(this.M,e)):null)}fn(e,n){return this.ln[n]?P1.resolve(this.ln[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.ln[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return OO(e).Wt({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(MR(t.batchId>=r),i=Z1(this.M,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return OO(e).Wt({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return OO(e).qt("userMutationsIndex",t).next(e=>e.map(e=>Z1(this.M,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=l1(this.userId,a.path),t=IDBKeyRange.lowerBound(e),c=[];return MO(o).Wt({range:t},(e,t,n)=>{var[r,i,s]=e,i=a1(i);if(r===this.userId&&a.path.isEqual(i))return OO(o).get(s).next(e=>{if(!e)throw OR();MR(e.userId===this.userId),c.push(Z1(this.M,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new Xx(QR);const n=[];return e.forEach(o=>{var e=l1(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=MO(t).Wt({range:e},(e,t,n)=>{var[r,i,s]=e,i=a1(i);r===this.userId&&o.path.isEqual(i)?a=a.add(s):n.done()});n.push(e)}),P1.waitFor(n).next(()=>this.dn(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=l1(this.userId,o),r=IDBKeyRange.lowerBound(n);let c=new Xx(QR);return MO(e).Wt({range:r},(e,t,n)=>{var[r,i,s]=e,i=a1(i);r===this.userId&&o.isPrefixOf(i)?i.length===a&&(c=c.add(s)):n.done()}).next(()=>this.dn(e,c))}dn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(OO(t).get(e).next(e=>{if(null===e)throw OR();MR(e.userId===this.userId),n.push(Z1(this.M,e))}))}),P1.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return RO(t.Ht,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this._n(n.batchId)}),P1.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}_n(e){delete this.ln[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return P1.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return MO(n).Wt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=a1(e[1]);r.push(t)}else n.done()}).next(()=>{MR(0===r.length)})})}containsKey(e,t){return DO(e,this.userId,t)}wn(e){return LO(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function DO(e,s,t){const n=l1(s,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return MO(e).Wt({range:r,jt:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===o&&(a=!0),n.done()}).next(()=>a)}function OO(e){return K1(e,"mutations")}function MO(e){return K1(e,"documentMutations")}function LO(e){return K1(e,"mutationQueues")}class FO{constructor(e){this.mn=e}next(){return this.mn+=2,this.mn}static gn(){return new FO(0)}static yn(){return new FO(-1)}}class UO{constructor(e,t){this.referenceDelegate=e,this.M=t}allocateTargetId(n){return this.pn(n).next(e=>{const t=new FO(e.highestTargetId);return e.highestTargetId=t.next(),this.In(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.pn(e).next(e=>ZR.fromTimestamp(new XR(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.pn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.pn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.In(t,e)))}addTargetData(t,n){return this.Tn(t,n).next(()=>this.pn(t).next(e=>(e.targetCount+=1,this.En(n,e),this.In(t,e))))}updateTargetData(e,t){return this.Tn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>qO(t).delete(e.targetId)).next(()=>this.pn(t)).next(e=>(MR(0<e.targetCount),--e.targetCount,this.In(t,e)))}removeTargets(r,i,s){let o=0;const a=[];return qO(r).Wt((e,t)=>{var n=eO(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>P1.waitFor(a)).next(()=>o)}forEachTarget(e,r){return qO(e).Wt((e,t)=>{var n=eO(t);r(n)})}pn(e){return jO(e).get("targetGlobalKey").next(e=>(MR(null!==e),e))}In(e,t){return jO(e).put("targetGlobalKey",t)}Tn(e,t){return qO(e).put(tO(this.M,t))}En(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.pn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=rP(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return qO(e).Wt({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=eO(t);iP(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=VO(n);return e.forEach(e=>{var t=s1(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),P1.waitFor(i)}removeMatchingKeys(n,e,r){const i=VO(n);return P1.forEach(e,e=>{var t=s1(e.path);return P1.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=VO(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=VO(e);let i=ID();return r.Wt({range:n,jt:!0},(e,t,n)=>{var r=a1(e[1]),r=new wx(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=s1(t.path),n=IDBKeyRange.bound([n],[JR(n)],!1,!0);let r=0;return VO(e).Wt({index:"documentTargetsIndex",jt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Et(e,t){return qO(e).get(t).next(e=>e?eO(e):null)}}function qO(e){return K1(e,"targets")}function jO(e){return K1(e,"targetGlobal")}function VO(e){return K1(e,"targetDocuments")}async function BO(e){if(e.code!==LR.FAILED_PRECONDITION||e.message!==R1)throw e;RR("LocalStore","Unexpectedly lost primary lease")}function KO([e,t],[n,r]){var i=QR(e,n);return 0===i?QR(t,r):i}class $O{constructor(e){this.An=e,this.buffer=new Xx(KO),this.Rn=0}Pn(){return++this.Rn}bn(e){var t=[e,this.Pn()];if(this.buffer.size<this.An)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();KO(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class WO{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.Vn=!1,this.vn=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Sn(e)}stop(){this.vn&&(this.vn.cancel(),this.vn=null)}get started(){return null!==this.vn}Sn(e){var t=this.Vn?3e5:6e4;RR("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.vn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.vn=null,this.Vn=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){F1(e)?RR("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await BO(e)}await this.Sn(e)})}}class zO{constructor(e,t){this.Dn=e,this.params=t}calculateTargetCount(e,t){return this.Dn.Cn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return P1.resolve(GR.A);const n=new $O(t);return this.Dn.forEachTarget(e,e=>n.bn(e.sequenceNumber)).next(()=>this.Dn.xn(e,e=>n.bn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Dn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Dn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(RR("LruGarbageCollector","Garbage collection skipped; disabled"),P1.resolve(AO)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(RR("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),AO):this.Nn(t,n))}getCacheSize(e){return this.Dn.getCacheSize(e)}Nn(t,n){let r,i,s,o,a,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(RR("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,o=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,a=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),NR()<=$h.DEBUG&&RR("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-u}ms\n\tDetermined least recently used ${i} in `+(a-o)+"ms\n"+`\tRemoved ${s} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),P1.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class GO{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new zO(e,t))}Cn(e){const n=this.kn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}kn(e){let t=0;return this.xn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}xn(e,n){return this.Mn(e,(e,t)=>n(t))}addReference(e,t,n){return HO(e,n)}removeReference(e,t,n){return HO(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return HO(e,t)}On(t,n){let r=!1;return LO(t).zt(e=>DO(t,e,n).next(e=>(e&&(r=!0),P1.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let o=0;return this.Mn(n,(t,e)=>{if(e<=r){const r=this.On(n,t).next(e=>{if(!e)return o++,i.getEntry(n,t).next(()=>(i.removeEntry(t,ZR.min()),VO(n).delete([0,s1(t.path)])))});s.push(r)}}).next(()=>P1.waitFor(s)).next(()=>i.apply(n)).next(()=>o)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return HO(e,t)}Mn(e,r){const t=VO(e);let i,s=GR.A;return t.Wt({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==GR.A&&r(new wx(a1(i)),s),s=n,i=t):s=GR.A}).next(()=>{s!==GR.A&&r(new wx(a1(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function HO(e,t){return VO(e).put((e=e.currentSequenceNumber,{targetId:0,path:s1(t.path),sequenceNumber:e}))}class QO{constructor(){this.changes=new gD(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,jx.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?P1.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class YO{constructor(e){this.M=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return ZO(e).put(n)}removeEntry(e,n,t){return ZO(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],Y1(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Fn(t,e)))}getEntry(e,n){let r=jx.newInvalidDocument(n);return ZO(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(eM(n))},(e,t)=>{r=this.$n(n,t)}).next(()=>r)}Bn(e,n){let r={size:0,document:jx.newInvalidDocument(n)};return ZO(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(eM(n))},(e,t)=>{r={document:this.$n(n,t),size:xO(t)}}).next(()=>r)}getEntries(e,t){let r=mD;return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n)}).next(()=>r)}Un(e,t){let r=mD,i=new Qx(wx.comparator);return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n),i=i.insert(e,xO(t))}).next(()=>({documents:r,qn:i}))}Ln(e,t,i){if(t.isEmpty())return P1.resolve();let n=new Xx(nM);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(eM(n.first()),eM(n.last())),s=n.getIterator();let o=s.getNext();return ZO(e).Wt({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=wx.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);o&&nM(o,r)<0;)i(o,null),o=s.getNext();o&&o.isEqual(r)&&(i(o,t),o=s.hasNext()?s.getNext():null),o?n.Ut(eM(o)):n.done()}).next(()=>{for(;o;)i(o,null),o=s.hasNext()?s.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),Y1(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],i=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return ZO(e).qt(IDBKeyRange.bound(r,i,!0)).next(e=>{let t=mD;for(const n of e){const e=this.$n(wx.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,i){let s=mD;var r=tM(t,n),o=tM(t,Gx.max());return ZO(e).Wt({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,o,!0)},(e,t,n)=>{var r=this.$n(wx.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new JO(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return XO(e).get("remoteDocumentGlobalKey").next(e=>(MR(!!e),e))}Fn(e,t){return XO(e).put("remoteDocumentGlobalKey",t)}$n(e,t){if(t){const e=function(e,t){let n;if(t.document)n=HD(e.Jt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=wx.fromSegments(t.noDocument.path),i=X1(t.noDocument.readTime);n=jx.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return OR();{const e=wx.fromSegments(t.unknownDocument.path),s=X1(t.unknownDocument.version);n=jx.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new XR(t[0],t[1]),ZR.fromTimestamp(r))),n;var r}(this.M,t);if(!e.isNoDocument()||!e.version.isEqual(ZR.min()))return e}return jx.newInvalidDocument(e)}}class JO extends QO{constructor(e,t){super(),this.Kn=e,this.trackRemovals=t,this.Gn=new gD(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const o=[];let a=0,c=new Xx((e,t)=>QR(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Gn.get(e);if(o.push(this.Kn.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Q1(this.Kn.M,t);c=c.add(e.path.popLast());var i=xO(r);a+=i-n.size,o.push(this.Kn.addEntry(s,e,r))}else if(a-=n.size,this.trackRemovals){const a=Q1(this.Kn.M,t.convertToNoDocument(ZR.min()));o.push(this.Kn.addEntry(s,e,a))}}),c.forEach(e=>{o.push(this.Kn.indexManager.addToCollectionParentIndex(s,e))}),o.push(this.Kn.updateMetadata(s,a)),P1.waitFor(o)}getFromCache(e,t){return this.Kn.Bn(e,t).next(e=>(this.Gn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Kn.Un(e,t).next(({documents:n,qn:e})=>(e.forEach((e,t)=>{this.Gn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function XO(e){return K1(e,"remoteDocumentGlobal")}function ZO(e){return K1(e,"remoteDocumentsV14")}function eM(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function tM(e,t){const n=t.documentKey.path.toArray();return[e,Y1(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function nM(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=QR(n[s],r[s]),i)return i;return i=QR(n.length,r.length),i||(i=QR(n[n.length-2],r[r.length-2]),i||QR(n[n.length-1],r[r.length-1]))}class rM{constructor(e){this.M=e}kt(t,e,n,r){const i=new D1("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",c1,{unique:!0}),s.createObjectStore("documentMutations"),iM(t),t.createObjectStore("remoteDocuments"));let o=P1.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),iM(t)),o=o.next(()=>function(){const e=i.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ZR.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(o=o.next(()=>function(r,i){return i.store("mutations").qt().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",c1,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return P1.waitFor(n)})}(t,i))),o=o.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(o=o.next(()=>this.Qn(i))),n<6&&6<=r&&(o=o.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.jn(i)))),n<7&&7<=r&&(o=o.next(()=>this.Wn(i))),n<8&&8<=r&&(o=o.next(()=>this.zn(t,i))),n<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(o=o.next(()=>this.Hn(i))),n<11&&11<=r&&(o=o.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(o=o.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:T1});e.createIndex("collectionPathOverlayIndex",E1,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",S1,{unique:!1})}()})),n<13&&13<=r&&(o=o.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:d1});e.createIndex("documentKeyIndex",f1),e.createIndex("collectionGroupIndex",p1)}()).next(()=>this.Jn(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(o=o.next(()=>{var e;(e=t).createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:_1}).createIndex("sequenceNumberIndex",w1,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:b1}).createIndex("documentKeyIndex",I1,{unique:!1})})),o}jn(t){let n=0;return t.store("remoteDocuments").Wt((e,t)=>{n+=xO(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Qn(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.qt().next(e=>P1.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.qt("userMutationsIndex",e).next(e=>P1.forEach(e,e=>{MR(e.userId===n.userId);var t=Z1(this.M,e);return RO(r,n.userId,t).next(()=>{})}))}))}Wn(e){const o=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Wt((e,t)=>{const n=new ix(e),r=[0,s1(n)];s.push(o.get(r).next(e=>e?P1.resolve():(e=>o.put({targetId:0,path:s1(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>P1.waitFor(s))})}zn(e,t){e.createObjectStore("collectionParents",{keyPath:y1});const n=t.store("collectionParents"),r=new bO,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:s1(r)})}};return t.store("remoteDocuments").Wt({jt:!0},(e,t)=>{const n=new ix(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Wt({jt:!0},([,e],t)=>{const n=a1(e);return i(n.popLast())}))}Hn(e){const r=e.store("targets");return r.Wt((e,t)=>{var n=eO(t),n=tO(this.M,n);return r.put(n)})}Jn(e,s){const t=s.store("remoteDocuments"),o=[];return t.Wt((e,t)=>{const n=s.store("remoteDocumentsV14"),r=((i=t).document?new wx(ix.fromString(i.document.name).popFirst(5)):i.noDocument?wx.fromSegments(i.noDocument.path):i.unknownDocument?wx.fromSegments(i.unknownDocument.path):OR()).path.toArray();var i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};o.push(n.put(i))}).next(()=>P1.waitFor(o))}}function iM(e){e.createObjectStore("targetDocuments",{keyPath:m1}).createIndex("documentTargetsIndex",v1,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",g1,{unique:!0}),e.createObjectStore("targetGlobal")}const sM="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class oM{constructor(e,t,n,r,i,s,o,a,c,l,u=13){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Yn=i,this.window=s,this.document=o,this.Xn=c,this.Zn=l,this.ts=u,this.es=null,this.ns=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ss=null,this.inForeground=!1,this.rs=null,this.os=null,this.us=Number.NEGATIVE_INFINITY,this.cs=e=>Promise.resolve(),!oM.vt())throw new FR(LR.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new GO(this,r),this.hs=t+"main",this.M=new H1(a),this.ls=new O1(this.hs,this.ts,new rM(this.M)),this.fs=new UO(this.referenceDelegate,this.M),this.ds=(a=this.M,new YO(a)),this._s=new sO,this.window&&this.window.localStorage?this.ws=this.window.localStorage:(this.ws=null,!1===l&&xR("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.gs().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new FR(LR.FAILED_PRECONDITION,sM);return this.ys(),this.ps(),this.Is(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.fs.getHighestSequenceNumber(e))}).then(e=>{this.es=new GR(e,this.Xn)}).then(()=>{this.ns=!0}).catch(e=>(this.ls&&this.ls.close(),Promise.reject(e)))}Ts(t){return this.cs=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ls.Ot(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Yn.enqueueAndForget(async()=>{this.started&&await this.gs()}))}gs(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>cM(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Es(t).next(e=>{e||(this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)))})}).next(()=>this.As(t)).next(e=>this.isPrimary&&!e?this.Rs(t).next(()=>!1):!!e&&this.Ps(t).next(()=>!0))).catch(e=>{if(F1(e))return RR("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return RR("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Yn.enqueueRetryable(()=>this.cs(e)),this.isPrimary=e})}Es(e){return aM(e).get("owner").next(e=>P1.resolve(this.bs(e)))}Vs(e){return cM(e).delete(this.clientId)}async vs(){if(this.isPrimary&&!this.Ss(this.us,18e5)){this.us=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=K1(e,"clientMetadata");return r.qt().next(e=>{const t=this.Ds(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return P1.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.ws)for(const t of e)this.ws.removeItem(this.Cs(t.clientId))}}Is(){this.os=this.Yn.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.gs().then(()=>this.vs()).then(()=>this.Is()))}bs(e){return!!e&&e.ownerId===this.clientId}As(t){return this.Zn?P1.resolve(!0):aM(t).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)){if(this.bs(e)&&this.networkEnabled)return!0;if(!this.bs(e)){if(!e.allowTabSynchronization)throw new FR(LR.FAILED_PRECONDITION,sM);return!1}}return!(!this.networkEnabled||!this.inForeground)||cM(t).qt().next(e=>void 0===this.Ds(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&RR("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.ns=!1,this.Ns(),this.os&&(this.os.cancel(),this.os=null),this.ks(),this.Ms(),await this.ls.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new B1(e,GR.A);return this.Rs(t).next(()=>this.Vs(t))}),this.ls.close(),this.Os()}Ds(e,t){return e.filter(e=>this.Ss(e.updateTimeMs,t)&&!this.xs(e.clientId))}Fs(){return this.runTransaction("getActiveClients","readonly",e=>cM(e).qt().next(e=>this.Ds(e,18e5).map(e=>e.clientId)))}get started(){return this.ns}getMutationQueue(e,t){return PO.Yt(e,this.M,t,this.referenceDelegate)}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getIndexManager(e){return new TO(e,this.M.Jt.databaseId)}getDocumentOverlayCache(e){return cO.Yt(this.M,e)}getBundleCache(){return this._s}runTransaction(t,n,r){RR("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",e=14===(e=this.ts)?N1:13===e?A1:12===e?C1:11===e?k1:void OR();let s;return this.ls.runTransaction(t,i,e,e=>(s=new B1(e,this.es?this.es.next():GR.A),"readwrite-primary"===n?this.Es(s).next(e=>!!e||this.As(s)).next(e=>{if(!e)throw xR(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)),new FR(LR.FAILED_PRECONDITION,R1);return r(s)}).next(e=>this.Ps(s).next(()=>e)):this.$s(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}$s(e){return aM(e).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)&&!this.bs(e)&&!(this.Zn||this.allowTabSynchronization&&e.allowTabSynchronization))throw new FR(LR.FAILED_PRECONDITION,sM)})}Ps(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return aM(e).put("owner",t)}static vt(){return O1.vt()}Rs(e){const t=aM(e);return t.get("owner").next(e=>this.bs(e)?(RR("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):P1.resolve())}Ss(e,t){var n=Date.now();return!(e<n-t||n<e&&(xR(`Detected an update time that is in the future: ${e} > ${n}`),1))}ys(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.rs=()=>{this.Yn.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.gs()))},this.document.addEventListener("visibilitychange",this.rs),this.inForeground="visible"===this.document.visibilityState)}ks(){this.rs&&(this.document.removeEventListener("visibilitychange",this.rs),this.rs=null)}ps(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ss=()=>{this.Ns(),!ad()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match(/Version\/1[45]/)&&this.Yn.enterRestrictedMode(!0),this.Yn.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ss))}Ms(){this.ss&&(this.window.removeEventListener("pagehide",this.ss),this.ss=null)}xs(e){var t;try{var n=null!==(null===(t=this.ws)||void 0===t?void 0:t.getItem(this.Cs(e)));return RR("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return xR("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ns(){if(this.ws)try{this.ws.setItem(this.Cs(this.clientId),String(Date.now()))}catch(e){xR("Failed to set zombie client id.",e)}}Os(){if(this.ws)try{this.ws.removeItem(this.Cs(this.clientId))}catch(e){}}Cs(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function aM(e){return K1(e,"owner")}function cM(e){return K1(e,"clientMetadata")}function lM(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class uM{constructor(e,t,n){this.ds=e,this.Bs=t,this.indexManager=n}Ls(t,n){return this.Bs.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.Us(t,n,e))}Us(e,t,n){return this.ds.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}qs(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Ks(t,e){return this.ds.getEntries(t,e).next(e=>this.Gs(t,e).next(()=>e))}Gs(e,t){return this.Bs.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.qs(t,e))}Qs(e,t,n){return r=t,wx.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.js(e,t.path):CP(t)?this.Ws(e,t,n):this.zs(e,t,n);var r}js(e,t){return this.Ls(e,new wx(t)).next(e=>{let t=yD();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Ws(r,i,s){const o=i.collectionGroup;let a=yD();return this.indexManager.getCollectionParents(r,o).next(e=>P1.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new IP(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.zs(r,n,s).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}zs(t,n,e){let i;return this.ds.getAllFromCollection(t,n.path,e).next(e=>(i=e,this.Bs.getAllMutationBatchesAffectingQuery(t,n))).next(t=>{for(const r of t)for(const t of r.mutations){var n=t.key;let e=i.get(n);null==e&&(e=jx.newInvalidDocument(n),i=i.insert(n,e)),nD(t,e,r.localWriteTime),e.isFoundDocument()||(i=i.remove(n))}}).next(()=>(i.forEach((e,t)=>{OP(n,t)||(i=i.remove(e))}),i))}}class hM{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Hs=n,this.Js=r}static Ys(e,t){let n=ID(),r=ID();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new hM(e,t.fromCache,n,r)}}class dM{constructor(){this.Xs=!1}initialize(e,t){this.Zs=e,this.indexManager=t,this.Xs=!0}Qs(t,n,r,i){return this.ti(t,n).next(e=>e||this.ei(t,n,i,r)).next(e=>e||this.ni(t,n))}ti(e,t){return P1.resolve(null)}ei(n,r,i,s){return 0===(e=r).filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())||s.isEqual(ZR.min())?this.ni(n,r):this.Zs.Ks(n,i).next(e=>{var t=this.si(r,e);return this.ii(r,t,i,s)?this.ni(n,r):(NR()<=$h.DEBUG&&RR("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),DP(r)),this.ri(n,t,r,zx(s,-1)))});var e}si(n,e){let r=new Xx(LP(n));return e.forEach((e,t)=>{OP(n,t)&&(r=r.add(t))}),r}ii(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}ni(e,t){return NR()<=$h.DEBUG&&RR("QueryEngine","Using full collection scan to execute query:",DP(t)),this.Zs.Qs(e,t,Gx.min())}ri(e,n,t,r){return this.Zs.Qs(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class fM{constructor(e,t,n,r){this.persistence=e,this.oi=t,this.M=r,this.ui=new Qx(QR),this.ai=new gD(e=>rP(e),iP),this.ci=new Map,this.hi=e.getRemoteDocumentCache(),this.fs=e.getTargetCache(),this._s=e.getBundleCache(),this.li(n)}li(e){this.indexManager=this.persistence.getIndexManager(e),this.Bs=this.persistence.getMutationQueue(e,this.indexManager),this.fi=new uM(this.hi,this.Bs,this.indexManager),this.hi.setIndexManager(this.indexManager),this.oi.initialize(this.fi,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ui))}}function pM(e,t,n,r){return new fM(e,t,n,r)}async function gM(e,t){const o=e;return o.persistence.runTransaction("Handle user change","readonly",i=>{let s;return o.Bs.getAllMutationBatches(i).next(e=>(s=e,o.li(t),o.Bs.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=ID();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return o.fi.Ks(i,r).next(e=>({di:e,removedBatchIds:t,addedBatchIds:n}))})})}function mM(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.fs.getLastRemoteSnapshotVersion(e))}function vM(e,l){const u=e,h=l.snapshotVersion;let d=u.ui;return u.persistence.runTransaction("Apply remote event","readwrite-primary",a=>{const e=u.hi.newChangeBuffer({trackRemovals:!0});d=u.ui;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.fs.removeMatchingKeys(a,t.removedDocuments,n).next(()=>u.fs.addMatchingKeys(a,t.addedDocuments,n)));let e=r.withSequenceNumber(a.currentSequenceNumber);var i,s,o;l.targetMismatches.has(n)?e=e.withResumeToken(cx.EMPTY_BYTE_STRING,ZR.min()).withLastLimboFreeSnapshotVersion(ZR.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,o=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||c.push(u.fs.updateTargetData(a,e))}});let t=mD;if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(a,e))}),c.push(yM(a,e,l.documentUpdates).next(e=>{t=e})),!h.isEqual(ZR.min())){const l=u.fs.getLastRemoteSnapshotVersion(a).next(e=>u.fs.setTargetsMetadata(a,a.currentSequenceNumber,h));c.push(l)}return P1.waitFor(c).next(()=>e.apply(a)).next(()=>u.fi.Gs(a,t)).next(()=>t)}).then(e=>(u.ui=d,e))}function yM(e,s,t){let n=ID();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=mD;return t.forEach((e,t)=>{const n=r.get(e);t.isNoDocument()&&t.version.isEqual(ZR.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):RR("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),i})}function _M(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.fs.getTargetData(t,r).next(e=>e?(n=e,P1.resolve(n)):i.fs.allocateTargetId(t).next(e=>(n=new G1(r,e,0,t.currentSequenceNumber),i.fs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.ui.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.ui=i.ui.insert(e.targetId,e),i.ai.set(r,e.targetId)),e})}async function wM(e,t,n){const r=e,i=r.ui.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!F1(e))throw e;RR("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ui=r.ui.remove(t),r.ai.delete(i.target)}function bM(e,n,r){const i=e;let s=ZR.min(),o=ID();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.ai.get(n);return void 0!==i?P1.resolve(r.ui.get(i)):r.fs.getTargetData(t,n)}(i,t,NP(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.fs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>i.oi.Qs(t,n,r?s:ZR.min(),r?o:ID())).next(e=>(EM(i,MP(n),e),{documents:e,_i:o})))}function IM(e,t){const n=e,r=n.fs,i=n.ui.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.Et(e,t).next(e=>e?e.target:null))}function TM(e,t){const n=e,r=n.ci.get(t)||ZR.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.hi.getAllFromCollectionGroup(e,t,zx(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(EM(n,t,e),e))}function EM(e,t,n){let r=ZR.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.ci.set(t,r)}class SM{constructor(e){this.M=e,this.yi=new Map,this.pi=new Map}getBundleMetadata(e,t){return P1.resolve(this.yi.get(t))}saveBundleMetadata(e,t){return this.yi.set(t.id,{id:t.id,version:t.version,createTime:UD(t.createTime)}),P1.resolve()}getNamedQuery(e,t){return P1.resolve(this.pi.get(t))}saveNamedQuery(e,t){return this.pi.set(t.name,{name:(t=t).name,query:nO(t.bundledQuery),readTime:UD(t.readTime)}),P1.resolve()}}class kM{constructor(){this.overlays=new Qx(wx.comparator),this.Ii=new Map}getOverlay(e,t){return P1.resolve(this.overlays.get(t))}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.Xt(n,r,t)}),P1.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Ii.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Ii.delete(n)),P1.resolve()}getOverlaysForCollection(e,t,n){const r=_D(),i=t.length+1,s=new wx(t.child("")),o=this.overlays.getIteratorFrom(s);for(;o.hasNext();){const e=o.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return P1.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new Qx((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=_D(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const o=_D(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach((e,t)=>o.set(e,t)),!(o.size()>=r)););return P1.resolve(o)}Xt(t,n,r){if(null!==r){var i=this.overlays.get(r.key);if(null!==i){const t=this.Ii.get(i.largestBatchId).delete(r.key);this.Ii.set(i.largestBatchId,t)}this.overlays=this.overlays.insert(r.key,new z1(n,r));let e=this.Ii.get(n);void 0===e&&(e=ID(),this.Ii.set(n,e)),this.Ii.set(n,e.add(r.key))}}}class CM{constructor(){this.Ti=new Xx(AM.Ei),this.Ai=new Xx(AM.Ri)}isEmpty(){return this.Ti.isEmpty()}addReference(e,t){var n=new AM(e,t);this.Ti=this.Ti.add(n),this.Ai=this.Ai.add(n)}Pi(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.bi(new AM(e,t))}Vi(e,t){e.forEach(e=>this.removeReference(e,t))}vi(e){const t=new wx(new ix([])),n=new AM(t,e),r=new AM(t,e+1),i=[];return this.Ai.forEachInRange([n,r],e=>{this.bi(e),i.push(e.key)}),i}Si(){this.Ti.forEach(e=>this.bi(e))}bi(e){this.Ti=this.Ti.delete(e),this.Ai=this.Ai.delete(e)}Di(e){var t=new wx(new ix([])),n=new AM(t,e),t=new AM(t,e+1);let r=ID();return this.Ai.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new AM(e,0),t=this.Ti.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class AM{constructor(e,t){this.key=e,this.Ci=t}static Ei(e,t){return wx.comparator(e.key,t.key)||QR(e.Ci,t.Ci)}static Ri(e,t){return QR(e.Ci,t.Ci)||wx.comparator(e.key,t.key)}}class NM{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.Bs=[],this.xi=1,this.Ni=new Xx(AM.Ei)}checkEmpty(e){return P1.resolve(0===this.Bs.length)}addMutationBatch(e,t,n,r){var i=this.xi;this.xi++,0<this.Bs.length&&this.Bs[this.Bs.length-1];var s=new $1(i,t,n,r);this.Bs.push(s);for(const t of r)this.Ni=this.Ni.add(new AM(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return P1.resolve(s)}lookupMutationBatch(e,t){return P1.resolve(this.ki(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.Mi(t+1),n=n<0?0:n;return P1.resolve(this.Bs.length>n?this.Bs[n]:null)}getHighestUnacknowledgedBatchId(){return P1.resolve(0===this.Bs.length?-1:this.xi-1)}getAllMutationBatches(e){return P1.resolve(this.Bs.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new AM(t,0),r=new AM(t,Number.POSITIVE_INFINITY),i=[];return this.Ni.forEachInRange([n,r],e=>{var t=this.ki(e.Ci);i.push(t)}),P1.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new Xx(QR);return t.forEach(e=>{var t=new AM(e,0),n=new AM(e,Number.POSITIVE_INFINITY);this.Ni.forEachInRange([t,n],e=>{r=r.add(e.Ci)})}),P1.resolve(this.Oi(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;wx.isDocumentKey(i)||(i=i.child(""));var s=new AM(new wx(i),0);let o=new Xx(QR);return this.Ni.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.Ci)),!0)},s),P1.resolve(this.Oi(o))}Oi(e){const n=[];return e.forEach(e=>{var t=this.ki(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){MR(0===this.Fi(r.batchId,"removed")),this.Bs.shift();let i=this.Ni;return P1.forEach(r.mutations,e=>{var t=new AM(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Ni=i})}_n(e){}containsKey(e,t){var n=new AM(t,0),n=this.Ni.firstAfterOrEqual(n);return P1.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.Bs.length,P1.resolve()}Fi(e,t){return this.Mi(e)}Mi(e){return 0===this.Bs.length?0:e-this.Bs[0].batchId}ki(e){var t=this.Mi(e);return t<0||t>=this.Bs.length?null:this.Bs[t]}}class RM{constructor(e){this.$i=e,this.docs=new Qx(wx.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.$i(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return P1.resolve(n?n.document.mutableCopy():jx.newInvalidDocument(t))}getEntries(e,t){let n=mD;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():jx.newInvalidDocument(e))}),P1.resolve(n)}getAllFromCollection(e,t,n){let r=mD;const i=new wx(t.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i}}=s.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||Hx((o=i,new Gx(o.readTime,o.key,-1)),n)<=0||(r=r.insert(i.key,i.mutableCopy()))}var o;return P1.resolve(r)}getAllFromCollectionGroup(e,t,n,r){OR()}Bi(e,t){return P1.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new xM(this)}getSize(e){return P1.resolve(this.size)}}class xM extends QO{constructor(e){super(),this.Kn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Kn.addEntry(n,t)):this.Kn.removeEntry(e)}),P1.waitFor(r)}getFromCache(e,t){return this.Kn.getEntry(e,t)}getAllFromCache(e,t){return this.Kn.getEntries(e,t)}}class PM{constructor(e){this.persistence=e,this.Li=new gD(e=>rP(e),iP),this.lastRemoteSnapshotVersion=ZR.min(),this.highestTargetId=0,this.Ui=0,this.qi=new CM,this.targetCount=0,this.Ki=FO.gn()}forEachTarget(e,n){return this.Li.forEach((e,t)=>n(t)),P1.resolve()}getLastRemoteSnapshotVersion(e){return P1.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return P1.resolve(this.Ui)}allocateTargetId(e){return this.highestTargetId=this.Ki.next(),P1.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Ui&&(this.Ui=t),P1.resolve()}Tn(e){this.Li.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Ki=new FO(t),this.highestTargetId=t),e.sequenceNumber>this.Ui&&(this.Ui=e.sequenceNumber)}addTargetData(e,t){return this.Tn(t),this.targetCount+=1,P1.resolve()}updateTargetData(e,t){return this.Tn(t),P1.resolve()}removeTargetData(e,t){return this.Li.delete(t.target),this.qi.vi(t.targetId),--this.targetCount,P1.resolve()}removeTargets(n,r,i){let s=0;const o=[];return this.Li.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Li.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),P1.waitFor(o).next(()=>s)}getTargetCount(e){return P1.resolve(this.targetCount)}getTargetData(e,t){var n=this.Li.get(t)||null;return P1.resolve(n)}addMatchingKeys(e,t,n){return this.qi.Pi(t,n),P1.resolve()}removeMatchingKeys(t,e,n){this.qi.Vi(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),P1.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.qi.vi(t),P1.resolve()}getMatchingKeysForTargetId(e,t){var n=this.qi.Di(t);return P1.resolve(n)}containsKey(e,t){return P1.resolve(this.qi.containsKey(t))}}class DM{constructor(e,t){this.Gi={},this.overlays={},this.es=new GR(0),this.ns=!1,this.ns=!0,this.referenceDelegate=e(this),this.fs=new PM(this),this.indexManager=new wO,this.ds=(e=e=>this.referenceDelegate.Qi(e),new RM(e)),this.M=new H1(t),this._s=new SM(this.M)}start(){return Promise.resolve()}shutdown(){return this.ns=!1,Promise.resolve()}get started(){return this.ns}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new kM,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Gi[e.toKey()];return n||(n=new NM(t,this.referenceDelegate),this.Gi[e.toKey()]=n),n}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getBundleCache(){return this._s}runTransaction(e,t,n){RR("MemoryPersistence","Starting transaction:",e);const r=new OM(this.es.next());return this.referenceDelegate.ji(),n(r).next(e=>this.referenceDelegate.Wi(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}zi(t,n){return P1.or(Object.values(this.Gi).map(e=>()=>e.containsKey(t,n)))}}class OM extends x1{constructor(e){super(),this.currentSequenceNumber=e}}class MM{constructor(e){this.persistence=e,this.Hi=new CM,this.Ji=null}static Yi(e){return new MM(e)}get Xi(){if(this.Ji)return this.Ji;throw OR()}addReference(e,t,n){return this.Hi.addReference(n,t),this.Xi.delete(n.toString()),P1.resolve()}removeReference(e,t,n){return this.Hi.removeReference(n,t),this.Xi.add(n.toString()),P1.resolve()}markPotentiallyOrphaned(e,t){return this.Xi.add(t.toString()),P1.resolve()}removeTarget(e,t){this.Hi.vi(t.targetId).forEach(e=>this.Xi.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Xi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}ji(){this.Ji=new Set}Wi(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return P1.forEach(this.Xi,e=>{const t=wx.fromPath(e);return this.Zi(n,t).next(e=>{e||r.removeEntry(t,ZR.min())})}).next(()=>(this.Ji=null,r.apply(n)))}updateLimboDocument(e,t){return this.Zi(e,t).next(e=>{e?this.Xi.delete(t.toString()):this.Xi.add(t.toString())})}Qi(e){return 0}Zi(e,t){return P1.or([()=>P1.resolve(this.Hi.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.zi(e,t)])}}function LM(e,t){return`firestore_clients_${e}_${t}`}function FM(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function UM(e,t){return`firestore_targets_${e}_${t}`}class qM{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static tr(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new FR(r.error.code,r.error.message))),s?new qM(e,t,r.state,i):(xR("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}er(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class jM{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static tr(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new FR(n.error.code,n.error.message))),i?new jM(e,n.state,r):(xR("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}er(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class VM{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static tr(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=TD;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=_x(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new VM(e,i):(xR("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class BM{constructor(e,t){this.clientId=e,this.onlineState=t}static tr(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new BM(t.clientId,t.onlineState):(xR("SharedClientState",`Failed to parse online state: ${e}`),null)}}class KM{constructor(){this.activeTargetIds=TD}nr(e){this.activeTargetIds=this.activeTargetIds.add(e)}sr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}er(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class $M{constructor(e,t,n,r,i){this.window=e,this.Yn=t,this.persistenceKey=n,this.ir=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.rr=this.ur.bind(this),this.ar=new Qx(QR),this.started=!1,this.cr=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.hr=LM(this.persistenceKey,this.ir),this.lr=`firestore_sequence_number_${this.persistenceKey}`,this.ar=this.ar.insert(this.ir,new KM),this.dr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this._r=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.wr=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.mr=`firestore_online_state_${this.persistenceKey}`,this.gr=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.rr)}static vt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Fs();for(const n of e)if(n!==this.ir){const e=this.getItem(LM(this.persistenceKey,n));var t;!e||(t=VM.tr(n,e))&&(this.ar=this.ar.insert(t.clientId,t))}this.yr();const n=this.storage.getItem(this.mr);if(n){const e=this.pr(n);e&&this.Ir(e)}for(const e of this.cr)this.ur(e);this.cr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.lr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Tr(this.ar)}isActiveQueryTarget(n){let r=!1;return this.ar.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Er(e,"pending")}updateMutationState(e,t,n){this.Er(e,t,n),this.Ar(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(UM(this.persistenceKey,e)))||(n=jM.tr(e,n))&&(t=n.state)),this.Rr.nr(e),this.yr(),t}removeLocalQueryTarget(e){this.Rr.sr(e),this.yr()}isLocalQueryTarget(e){return this.Rr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(UM(this.persistenceKey,e))}updateQueryState(e,t,n){this.Pr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Ar(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Vr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.rr),this.removeItem(this.hr),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return RR("SharedClientState","READ",e,t),t}setItem(e,t){RR("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){RR("SharedClientState","REMOVE",e),this.storage.removeItem(e)}ur(e){const i=e;i.storageArea===this.storage&&(RR("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.hr?this.Yn.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.dr.test(i.key)){if(null==i.newValue){var e=this.vr(i.key);return this.Sr(e,null)}e=this.Dr(i.key,i.newValue);if(e)return this.Sr(e.clientId,e)}else if(this._r.test(i.key)){if(null!==i.newValue){var t=this.Cr(i.key,i.newValue);if(t)return this.Nr(t)}}else if(this.wr.test(i.key)){if(null!==i.newValue){t=this.kr(i.key,i.newValue);if(t)return this.Mr(t)}}else if(i.key===this.mr){if(null!==i.newValue){var n=this.pr(i.newValue);if(n)return this.Ir(n)}}else if(i.key===this.lr){n=function(e){let t=GR.A;if(null!=e)try{var n=JSON.parse(e);MR("number"==typeof n),t=n}catch(e){xR("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==GR.A&&this.sequenceNumberHandler(n)}else if(i.key===this.gr){const r=this.Or(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Fr(e)))}}else this.cr.push(i)}):xR("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Rr(){return this.ar.get(this.ir)}yr(){this.setItem(this.hr,this.Rr.er())}Er(e,t,n){const r=new qM(this.currentUser,e,t,n),i=FM(this.persistenceKey,this.currentUser,e);this.setItem(i,r.er())}Ar(e){var t=FM(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){var t={clientId:this.ir,onlineState:e};this.storage.setItem(this.mr,JSON.stringify(t))}Pr(e,t,n){const r=UM(this.persistenceKey,e),i=new jM(e,t,n);this.setItem(r,i.er())}Vr(e){var t=JSON.stringify(Array.from(e));this.setItem(this.gr,t)}vr(e){var t=this.dr.exec(e);return t?t[1]:null}Dr(e,t){var n=this.vr(e);return VM.tr(n,t)}Cr(e,t){var n=this._r.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return qM.tr(new kR(n),r,t)}kr(e,t){var n=this.wr.exec(e),n=Number(n[1]);return jM.tr(n,t)}pr(e){return BM.tr(e)}Or(e){return JSON.parse(e)}async Nr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.$r(e.batchId,e.state,e.error);RR("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Mr(e){return this.syncEngine.Br(e.targetId,e.state,e.error)}Sr(e,t){const n=t?this.ar.insert(e,t):this.ar.remove(e),r=this.Tr(this.ar),i=this.Tr(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.Lr(s,o).then(()=>{this.ar=n})}Ir(e){this.ar.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Tr(e){let n=TD;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class WM{constructor(){this.Ur=new KM,this.qr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Ur.nr(e),this.qr[e]||"not-current"}updateQueryState(e,t,n){this.qr[e]=t}removeLocalQueryTarget(e){this.Ur.sr(e)}isLocalQueryTarget(e){return this.Ur.activeTargetIds.has(e)}clearQueryState(e){delete this.qr[e]}getAllActiveQueryTargets(){return this.Ur.activeTargetIds}isActiveQueryTarget(e){return this.Ur.activeTargetIds.has(e)}start(){return this.Ur=new KM,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class zM{Kr(e){}shutdown(){}}class GM{constructor(){this.Gr=()=>this.Qr(),this.jr=()=>this.Wr(),this.zr=[],this.Hr()}Kr(e){this.zr.push(e)}shutdown(){window.removeEventListener("online",this.Gr),window.removeEventListener("offline",this.jr)}Hr(){window.addEventListener("online",this.Gr),window.addEventListener("offline",this.jr)}Qr(){RR("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.zr)e(0)}Wr(){RR("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.zr)e(1)}static vt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const HM={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class QM{constructor(e){this.Jr=e.Jr,this.Yr=e.Yr}Xr(e){this.Zr=e}eo(e){this.no=e}onMessage(e){this.so=e}close(){this.Yr()}send(e){this.Jr(e)}io(){this.Zr()}ro(e){this.no(e)}oo(e){this.so(e)}}class YM extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.uo=t+"://"+e.host,this.ao="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}co(t,e,n,r,i){const s=this.ho(t,e);RR("RestConnection","Sending: ",s,n);var o={};return this.lo(o,r,i),this.fo(t,s,o,n).then(e=>(RR("RestConnection","Received: ",e),e),e=>{throw PR("RestConnection",`${t} failed with error: `,e,"url: ",s,"request:",n),e})}_o(e,t,n,r,i){return this.co(e,t,n,r,i)}lo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+CR,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}ho(e,t){var n=HM[e];return`${this.uo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(a,t,n,r){return new Promise((i,s)=>{const o=new ER;o.listenOnce(yR.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case vR.NO_ERROR:var e=o.getResponseJson();RR("Connection","XHR received:",JSON.stringify(e)),i(e);break;case vR.TIMEOUT:RR("Connection",'RPC "'+a+'" timed out'),s(new FR(LR.DEADLINE_EXCEEDED,"Request time out"));break;case vR.HTTP_ERROR:var t,n=o.getStatus();if(RR("Connection",'RPC "'+a+'" failed with status:',n,"response text:",o.getResponseText()),0<n){const a=o.getResponseJson().error;a&&a.status&&a.message?(r=a.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(LR).indexOf(r)?r:LR.UNKNOWN,s(new FR(t,a.message))):s(new FR(LR.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new FR(LR.UNAVAILABLE,"Connection failed."));break;default:OR()}}finally{RR("Connection",'RPC "'+a+'" completed.')}var r});var e=JSON.stringify(r);o.send(t,"POST",e,n,15)})}wo(e,t,n){const r=[this.uo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=new uR,s=mR(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(o.xmlHttpFactory=new IR({})),this.lo(o.initMessageHeaders,t,n),od()||ld()||0<=sd().indexOf("Electron/")||ud()||0<=sd().indexOf("MSAppHost/")||cd()||(o.httpHeadersOverwriteParam="$httpHeaders");var a=r.join("");RR("Connection","Creating WebChannel: "+a,o);const c=i.createWebChannel(a,o);let l=!1,u=!1;const h=new QM({Jr:e=>{u?RR("Connection","Not sending because WebChannel is closed:",e):(l||(RR("Connection","Opening WebChannel transport."),c.open(),l=!0),RR("Connection","WebChannel sending:",e),c.send(e))},Yr:()=>c.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(c,TR.EventType.OPEN,()=>{u||RR("Connection","WebChannel transport opened.")}),d(c,TR.EventType.CLOSE,()=>{u||(u=!0,RR("Connection","WebChannel transport closed"),h.ro())}),d(c,TR.EventType.ERROR,e=>{u||(u=!0,PR("Connection","WebChannel transport errored:",e),h.ro(new FR(LR.UNAVAILABLE,"The operation could not be completed")))}),d(c,TR.EventType.MESSAGE,n=>{if(!u){var e=n.data[0];MR(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){RR("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=gR[e];if(void 0!==t)return pD(t)}(n),t=r.message;void 0===e&&(e=LR.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),u=!0,h.ro(new FR(e,t)),c.close()}else RR("Connection","WebChannel received:",e),h.oo(e)}}),d(s,_R.STAT_EVENT,e=>{e.stat===wR?RR("Connection","Detected buffering proxy"):e.stat===bR&&RR("Connection","Detected no buffering proxy")}),setTimeout(()=>{h.io()},0),h}}function JM(){return"undefined"!=typeof window?window:null}function XM(){return"undefined"!=typeof document?document:null}function ZM(e){return new MD(e,!0)}class eL{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Yn=e,this.timerId=t,this.mo=n,this.yo=r,this.po=i,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();var t=Math.floor(this.Io+this.Po()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);0<r&&RR("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Io} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.To=this.Yn.enqueueAfterDelay(this.timerId,r,()=>(this.Eo=Date.now(),e())),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}bo(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}Po(){return(Math.random()-.5)*this.Io}}class tL{constructor(e,t,n,r,i,s,o,a){this.Yn=e,this.Vo=n,this.vo=r,this.So=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Do=0,this.Co=null,this.xo=null,this.stream=null,this.No=new eL(e,t)}ko(){return 1===this.state||5===this.state||this.Mo()}Mo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Oo()}async stop(){this.ko()&&await this.close(0)}Fo(){this.state=0,this.No.reset()}$o(){this.Mo()&&null===this.Co&&(this.Co=this.Yn.enqueueAfterDelay(this.Vo,6e4,()=>this.Bo()))}Lo(e){this.Uo(),this.stream.send(e)}async Bo(){if(this.Mo())return this.close(0)}Uo(){this.Co&&(this.Co.cancel(),this.Co=null)}qo(){this.xo&&(this.xo.cancel(),this.xo=null)}async close(e,t){this.Uo(),this.qo(),this.No.cancel(),this.Do++,4!==e?this.No.reset():t&&t.code===LR.RESOURCE_EXHAUSTED?(xR(t.toString()),xR("Using maximum backoff delay to prevent overloading the backend."),this.No.Ao()):t&&t.code===LR.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Ko(),this.stream.close(),this.stream=null),this.state=e,await this.listener.eo(t)}Ko(){}auth(){this.state=1;const e=this.Go(this.Do),n=this.Do;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Do===n&&this.Qo(e,t)},t=>{e(()=>{var e=new FR(LR.UNKNOWN,"Fetching auth token failed: "+t.message);return this.jo(e)})})}Qo(e,t){const n=this.Go(this.Do);this.stream=this.Wo(e,t),this.stream.Xr(()=>{n(()=>(this.state=2,this.xo=this.Yn.enqueueAfterDelay(this.vo,1e4,()=>(this.Mo()&&(this.state=3),Promise.resolve())),this.listener.Xr()))}),this.stream.eo(e=>{n(()=>this.jo(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Oo(){this.state=5,this.No.Ro(async()=>{this.state=0,this.start()})}jo(e){return RR("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Go(t){return e=>{this.Yn.enqueueAndForget(()=>this.Do===t?e():(RR("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class nL extends tL{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.M=i}Wo(e,t){return this.So.wo("Listen",e,t)}onMessage(e){this.No.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:OR(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.N?(MR(void 0===f||"string"==typeof f),cx.fromBase64String(f||"")):(MR(void 0===f||f instanceof Uint8Array),cx.fromUint8Array(f||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(f=o).code?LR.UNKNOWN:pD(f.code),new FR(a,f.message||""));n=new AD(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var a=BD(e,c.document.name),l=UD(c.document.updateTime),u=new qx({mapValue:{fields:c.document.fields}}),l=jx.newFoundDocument(a,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new kD(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=BD(e,u.document),l=u.readTime?UD(u.readTime):ZR.min(),l=jx.newNoDocument(c,l),u=u.removedTargetIds||[];n=new kD([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=BD(e,h.document),h=h.removedTargetIds||[];n=new kD([],h,d,null)}else{if(!("filter"in t))return OR();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new dD(h),h=e.targetId;n=new CD(h,d)}}var a,f;return n}(this.M,e),n=function(e){if(!("targetChange"in e))return ZR.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?UD(t.readTime):ZR.min()}(e);return this.listener.zo(t,n)}Ho(e){const t={};t.database=WD(this.M),t.addTarget=function(e,t){let n;var r=t.target;return n=sP(r)?{documents:JD(e,r)}:{query:XD(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=FD(e,t.resumeToken):0<t.snapshotVersion.compareTo(ZR.min())&&(n.readTime=LD(e,t.snapshotVersion.toTimestamp())),n}(this.M,e);var n,r,r=(this.M,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return OR()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Lo(t)}Jo(e){const t={};t.database=WD(this.M),t.removeTarget=e,this.Lo(t)}}class rL extends tL{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.M=i,this.Yo=!1}get Xo(){return this.Yo}start(){this.Yo=!1,this.lastStreamToken=void 0,super.start()}Ko(){this.Yo&&this.Zo([])}Wo(e,t){return this.So.wo("Write",e,t)}onMessage(e){if(MR(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Yo){this.No.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(MR(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?UD(e.updateTime):UD(t);return n.isEqual(ZR.min())&&(n=UD(t)),new JP(n,e.transformResults||[])}(e,i))):[]),n=UD(e.commitTime);return this.listener.tu(n,t)}var r,i;return MR(!e.writeResults||0===e.writeResults.length),this.Yo=!0,this.listener.eu()}nu(){const e={};e.database=WD(this.M),this.Lo(e)}Zo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>QD(this.M,e))};this.Lo(t)}}class iL extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.So=n,this.M=r,this.su=!1}iu(){if(this.su)throw new FR(LR.FAILED_PRECONDITION,"The client has already been terminated.")}co(n,r,i){return this.iu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.So.co(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===LR.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FR(LR.UNKNOWN,e.toString())})}_o(n,r,i){return this.iu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.So._o(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===LR.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FR(LR.UNKNOWN,e.toString())})}terminate(){this.su=!0}}class sL{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.ru=0,this.ou=null,this.uu=!0}au(){0===this.ru&&(this.cu("Unknown"),this.ou=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.ou=null,this.hu("Backend didn't respond within 10 seconds."),this.cu("Offline"),Promise.resolve())))}lu(e){"Online"===this.state?this.cu("Unknown"):(this.ru++,1<=this.ru&&(this.fu(),this.hu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.cu("Offline")))}set(e){this.fu(),this.ru=0,"Online"===e&&(this.uu=!1),this.cu(e)}cu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}hu(e){var t=`Could not reach Cloud Firestore backend. ${e}\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.uu?(xR(t),this.uu=!1):RR("OnlineStateTracker",t)}fu(){null!==this.ou&&(this.ou.cancel(),this.ou=null)}}class oL{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.du=[],this._u=new Map,this.wu=new Set,this.mu=[],this.gu=i,this.gu.Kr(e=>{n.enqueueAndForget(async()=>{gL(this)&&(RR("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.wu.add(4),await cL(t),t.yu.set("Unknown"),t.wu.delete(4),await aL(t)}(this))})}),this.yu=new sL(n,r)}}async function aL(e){if(gL(e))for(const t of e.mu)await t(!0)}async function cL(e){for(const t of e.mu)await t(!1)}function lL(e,t){const n=e;n._u.has(t.targetId)||(n._u.set(t.targetId,t),pL(n)?fL(n):EL(n).Mo()&&hL(n,t))}function uL(e,t){const n=e,r=EL(n);n._u.delete(t),r.Mo()&&dL(n,t),0===n._u.size&&(r.Mo()?r.$o():gL(n)&&n.yu.set("Unknown"))}function hL(e,t){e.pu.Z(t.targetId),EL(e).Ho(t)}function dL(e,t){e.pu.Z(t),EL(e).Jo(t)}function fL(t){t.pu=new RD({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t._u.get(e)||null}),EL(t).start(),t.yu.au()}function pL(e){return gL(e)&&!EL(e).ko()&&0<e._u.size}function gL(e){return 0===e.wu.size}function mL(e){e.pu=void 0}async function vL(e,t,n){if(!F1(t))throw t;e.wu.add(1),await cL(e),e.yu.set("Offline"),n=n||(()=>mM(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{RR("RemoteStore","Retrying IndexedDB access"),await n(),e.wu.delete(1),await aL(e)})}function yL(t,n){return n().catch(e=>vL(t,e,n))}async function _L(e){const t=e,n=SL(t);let r=0<t.du.length?t.du[t.du.length-1].batchId:-1;for(;gL(i=t)&&i.du.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.Bs.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.du.length&&n.$o();break}r=e.batchId,function(e,t){e.du.push(t);const n=SL(e);n.Mo()&&n.Xo&&n.Zo(t.mutations)}(t,e)}catch(e){await vL(t,e)}var i;wL(t)&&bL(t)}function wL(e){return gL(e)&&!SL(e).ko()&&0<e.du.length}function bL(e){SL(e).start()}async function IL(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),RR("RemoteStore","RemoteStore received new credentials");var r=gL(n);n.wu.add(3),await cL(n),r&&n.yu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.wu.delete(3),await aL(n)}async function TL(e,t){const n=e;t?(n.wu.delete(2),await aL(n)):(n.wu.add(2),await cL(n),n.yu.set("Unknown"))}function EL(t){return t.Iu||(t.Iu=function(e,t,n){const r=e;return r.iu(),new nL(t,r.So,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Xr:(async function(n){n._u.forEach((e,t)=>{hL(n,e)})}).bind(null,t),eo:(async function(e,t){mL(e),pL(e)?(e.yu.lu(t),fL(e)):e.yu.set("Unknown")}).bind(null,t),zo:(async function(e,r,t){if(e.yu.set("Online"),r instanceof AD&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e._u.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e._u.delete(n),e.pu.removeTarget(n))}(e)}catch(t){RR("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await vL(e,t)}else if(r instanceof kD?e.pu.ut(r):r instanceof CD?e.pu._t(r):e.pu.ht(r),!t.isEqual(ZR.min()))try{const r=await mM(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.pu.yt(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r._u.get(t);n&&r._u.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r._u.get(e);var n;t&&(r._u.set(e,t.withResumeToken(cx.EMPTY_BYTE_STRING,t.snapshotVersion)),dL(r,e),n=new G1(t.target,e,1,t.sequenceNumber),hL(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){RR("RemoteStore","Failed to raise snapshot:",r),await vL(e,r)}}).bind(null,t)}),t.mu.push(async e=>{e?(t.Iu.Fo(),pL(t)?fL(t):t.yu.set("Unknown")):(await t.Iu.stop(),mL(t))})),t.Iu}function SL(t){return t.Tu||(t.Tu=function(e,t,n){const r=e;return r.iu(),new rL(t,r.So,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Xr:(async function(e){SL(e).nu()}).bind(null,t),eo:(async function(e,t){t&&SL(e).Xo&&await async function(e,t){if(fD(n=t.code)&&n!==LR.ABORTED){const n=e.du.shift();SL(e).Fo(),await yL(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await _L(e)}var n}(e,t),wL(e)&&bL(e)}).bind(null,t),eu:(async function(e){const t=SL(e);for(const n of e.du)t.Zo(n.mutations)}).bind(null,t),tu:(async function(e,t,n){const r=e.du.shift(),i=W1.from(r,t,n);await yL(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await _L(e)}).bind(null,t)}),t.mu.push(async e=>{e?(t.Tu.Fo(),await _L(t)):(await t.Tu.stop(),0<t.du.length&&(RR("RemoteStore",`Stopping write stream with ${t.du.length} pending writes`),t.du=[]))})),t.Tu}class kL{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new UR,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new kL(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FR(LR.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function CL(e,t){if(xR("AsyncQueue",`${t}: ${e}`),F1(e))return new FR(LR.UNAVAILABLE,`${t}: ${e}`);throw e}class AL{constructor(n){this.comparator=n?(e,t)=>n(e,t)||wx.comparator(e.key,t.key):(e,t)=>wx.comparator(e.key,t.key),this.keyedMap=yD(),this.sortedSet=new Qx(this.comparator)}static emptySet(e){return new AL(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof AL))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new AL;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class NL{constructor(){this.Eu=new Qx(wx.comparator)}track(e){var t=e.doc.key,n=this.Eu.get(t);!n||0!==e.type&&3===n.type?this.Eu=this.Eu.insert(t,e):3===e.type&&1!==n.type?this.Eu=this.Eu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Eu=this.Eu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Eu=this.Eu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Eu=this.Eu.remove(t):1===e.type&&2===n.type?this.Eu=this.Eu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Eu=this.Eu.insert(t,{type:2,doc:e.doc}):OR()}Au(){const n=[];return this.Eu.inorderTraversal((e,t)=>{n.push(t)}),n}}class RL{constructor(e,t,n,r,i,s,o,a){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(e,t,n,r){const i=[];return t.forEach(e=>{i.push({type:0,doc:e})}),new RL(e,t,AL.emptySet(t),i,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&xP(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class xL{constructor(){this.Ru=void 0,this.listeners=[]}}class PL{constructor(){this.queries=new gD(e=>PP(e),xP),this.onlineState="Unknown",this.Pu=new Set}}async function DL(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new xL),i)try{s.Ru=await n.onListen(r)}catch(e){const n=CL(e,`Initialization of query '${DP(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.bu(n.onlineState),!s.Ru||t.Vu(s.Ru)&&ML(n)}async function OL(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function ML(e){e.Pu.forEach(e=>{e.next()})}class LL{constructor(e,t,n){this.query=e,this.vu=t,this.Su=!1,this.Du=null,this.onlineState="Unknown",this.options=n||{}}Vu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new RL(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.Su?this.Cu(e)&&(this.vu.next(e),t=!0):this.xu(e,this.onlineState)&&(this.Nu(e),t=!0),this.Du=e,t}onError(e){this.vu.error(e)}bu(e){this.onlineState=e;let t=!1;return this.Du&&!this.Su&&this.xu(this.Du,e)&&(this.Nu(this.Du),t=!0),t}xu(e,t){return!e.fromCache||!(this.options.ku&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}Cu(e){if(0<e.docChanges.length)return!0;var t=this.Du&&this.Du.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Nu(e){e=RL.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.Su=!0,this.vu.next(e)}}class FL{constructor(e,t){this.payload=e,this.byteLength=t}Mu(){return"metadata"in this.payload}}class UL{constructor(e){this.M=e}wi(e){return BD(this.M,e)}mi(e){return e.metadata.exists?HD(this.M,e.document,!1):jx.newNoDocument(this.wi(e.metadata.name),this.gi(e.metadata.readTime))}gi(e){return UD(e)}}class qL{constructor(e,t,n){this.Ou=e,this.localStore=t,this.M=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=jL(e)}Fu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.payload.namedQuery)this.queries.push(e.payload.namedQuery);else if(e.payload.documentMetadata){this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t;const n=ix.fromString(e.payload.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}$u(e){const t=new Map,n=new UL(this.M);for(const i of e)if(i.metadata.queries){const e=n.wi(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||ID()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=ID(),o=mD;for(const e of n){const n=t.wi(e.metadata.name);e.document&&(s=s.add(n));const l=t.mi(e);l.setReadTime(t.gi(e.metadata.readTime)),o=o.insert(n,l)}const a=i.hi.newChangeBuffer({trackRemovals:!0}),c=await _M(i,(r=r,NP(EP(ix.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>yM(t,a,o).next(e=>(a.apply(t),e)).next(e=>i.fs.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.fs.addMatchingKeys(t,s,c.targetId)).next(()=>i.fi.Gs(t,e)).next(()=>e)))}(this.localStore,new UL(this.M),this.documents,this.Ou.id),t=this.$u(this.documents);for(const e of this.queries)await async function(e,n,r=ID()){const i=await _M(e,NP(nO(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=UD(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s._s.saveNamedQuery(e,n);t=i.withResumeToken(cx.EMPTY_BYTE_STRING,t);return s.ui=s.ui.insert(t.targetId,t),s.fs.updateTargetData(e,t).next(()=>s.fs.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.fs.addMatchingKeys(e,r,i.targetId)).next(()=>s._s.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function jL(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class VL{constructor(e){this.key=e}}class BL{constructor(e){this.key=e}}class KL{constructor(e,t){this.query=e,this.Uu=t,this.qu=null,this.current=!1,this.Ku=ID(),this.mutatedKeys=ID(),this.Gu=LP(e),this.Qu=new AL(this.Gu)}get ju(){return this.Uu}Wu(e,t){const a=t?t.zu:new NL,c=(t||this).Qu;let l=(t||this).mutatedKeys,u=c,h=!1;const d="F"===this.query.limitType&&c.size===this.query.limit?c.last():null,f="L"===this.query.limitType&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=OP(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let o=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(a.track({type:3,doc:r}),o=!0):this.Hu(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.Gu(r,d)||f&&this.Gu(r,f)<0)&&(h=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||f)&&(h=!0)),o&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){const e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),a.track({type:1,doc:e})}return{Qu:u,zu:a,ii:h,mutatedKeys:l}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const i=e.zu.Au();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return OR()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc)),this.Ju(n);var s=t?this.Yu():[],o=0===this.Ku.size&&this.current?1:0,a=o!==this.qu;return this.qu=o,0!==i.length||a?{snapshot:new RL(this.query,e.Qu,r,i,e.mutatedKeys,0==o,a,!1),Xu:s}:{Xu:s}}bu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new NL,mutatedKeys:this.mutatedKeys,ii:!1},!1)):{Xu:[]}}Zu(e){return!this.Uu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}Ju(e){e&&(e.addedDocuments.forEach(e=>this.Uu=this.Uu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Uu=this.Uu.delete(e)),this.current=e.current)}Yu(){if(!this.current)return[];const t=this.Ku;this.Ku=ID(),this.Qu.forEach(e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))});const n=[];return t.forEach(e=>{this.Ku.has(e)||n.push(new BL(e))}),this.Ku.forEach(e=>{t.has(e)||n.push(new VL(e))}),n}ta(e){this.Uu=e._i,this.Ku=ID();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}ea(){return RL.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.qu)}}class $L{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class WL{constructor(e){this.key=e,this.na=!1}}class zL{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.sa={},this.ia=new gD(e=>PP(e),xP),this.ra=new Map,this.oa=new Set,this.ua=new Qx(wx.comparator),this.aa=new Map,this.ca=new CM,this.ha={},this.la=new Map,this.fa=FO.yn(),this.onlineState="Unknown",this.da=void 0}get isPrimaryClient(){return!0===this.da}}async function GL(n,e,t,r){n._a=(e,s,t)=>async function(e,t,n){let r=t.view.Wu(s);r.ii&&(r=await bM(e.localStore,t.query,!1).then(({documents:e})=>t.view.Wu(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return nF(e,t.targetId,i.Xu),i.snapshot}(n,e,t);const i=await bM(n.localStore,e,!0),s=new KL(e,i._i),o=s.Wu(i.documents),a=SD.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),c=s.applyChanges(o,n.isPrimaryClient,a);nF(n,t,c.Xu);var l=new $L(e,t,s);return n.ia.set(e,l),n.ra.has(t)?n.ra.get(t).push(e):n.ra.set(t,[e]),c.snapshot}async function HL(e,t,n){const r=lF(e);try{const e=await function(e,r){const i=e,s=XR.now(),t=r.reduce((e,t)=>e.add(t.key),ID());let o;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>i.fi.Ks(n,t).next(e=>{o=e;const t=[];for(const n of r){const r=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=VP(r.transform,e||null);null!=i&&(null==n&&(n=qx.empty()),n.set(r.field,i))}return n||null}(n,o.get(n.key));null!=r&&t.push(new oD(n.key,r,function r(e){const i=[];return tx(e.fields,(e,t)=>{const n=new ox([e]);if(Ox(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new ax(i)}(r.value.mapValue),XP.exists(!0)))}return i.Bs.addMutationBatch(n,s,t,r)})).then(e=>(e.applyToLocalDocumentSet(o),{batchId:e.batchId,changes:o}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.ha[e.currentUser.toKey()];r=r||new Qx(QR),r=r.insert(t,n),e.ha[e.currentUser.toKey()]=r}(r,e.batchId,n),await iF(r,e.changes),await _L(r.remoteStore)}catch(e){const t=CL(e,"Failed to persist write");n.reject(t)}}async function QL(e,t){const r=e;try{const e=await vM(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.aa.get(t);n&&(MR(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.na=!0:0<e.modifiedDocuments.size?MR(n.na):0<e.removedDocuments.size&&(MR(n.na),n.na=!1))}),await iF(r,e,t)}catch(e){await BO(e)}}function YL(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ia.forEach((e,t)=>{var n=t.view.bu(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.bu(n)&&(r=!0)}),r&&ML(t)}(t.eventManager,i),r.length&&t.sa.zo(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function JL(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.hi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let o=P1.resolve();return n.forEach(n=>{o=o.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);MR(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),o.next(()=>e.Bs.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.Bs.performConsistencyCheck(e)).next(()=>i.fi.Ks(e,t))})}(n.localStore,t);ZL(n,r,null),XL(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await iF(n,e)}catch(e){await BO(e)}}function XL(e,t){(e.la.get(t)||[]).forEach(e=>{e.resolve()}),e.la.delete(t)}function ZL(e,t,n){const r=e;let i=r.ha[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.ha[r.currentUser.toKey()]=i}}function eF(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.ra.get(e))t.ia.delete(r),n&&t.sa.wa(r,n);t.ra.delete(e),t.isPrimaryClient&&t.ca.vi(e).forEach(e=>{t.ca.containsKey(e)||tF(t,e)})}function tF(e,t){e.oa.delete(t.path.canonicalString());var n=e.ua.get(t);null!==n&&(uL(e.remoteStore,n),e.ua=e.ua.remove(t),e.aa.delete(n),rF(e))}function nF(e,t,n){for(const r of n)r instanceof VL?(e.ca.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.ua.get(n)||e.oa.has(r)||(RR("SyncEngine","New document in limbo: "+n),e.oa.add(r),rF(e))}(e,r)):r instanceof BL?(RR("SyncEngine","Document no longer in limbo: "+r.key),e.ca.removeReference(r.key,t),e.ca.containsKey(r.key)||tF(e,r.key)):OR()}function rF(e){for(;0<e.oa.size&&e.ua.size<e.maxConcurrentLimboResolutions;){var t=e.oa.values().next().value;e.oa.delete(t);var n=new wx(ix.fromString(t)),t=e.fa.next();e.aa.set(t,new WL(n)),e.ua=e.ua.insert(n,t),lL(e.remoteStore,new G1(NP(EP(n.path)),t,2,GR.A))}}async function iF(e,t,r){const i=e,s=[],o=[],a=[];i.ia.isEmpty()||(i.ia.forEach((e,n)=>{a.push(i._a(n,t,r).then(e=>{var t;e&&(i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),s.push(e),t=hM.Ys(n.targetId,e),o.push(t))}))}),await Promise.all(a),i.sa.zo(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>P1.forEach(t,t=>P1.forEach(t.Hs,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>P1.forEach(t.Js,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!F1(e))throw e;RR("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ui.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.ui=r.ui.insert(t,i)}}}(i.localStore,o))}async function sF(r,e){const i=r;if(cF(i),lF(i),!0===e&&!0!==i.da){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await oF(i,r.toArray());i.da=!0,await TL(i.remoteStore,!0);for(const r of e)lL(i.remoteStore,r)}else if(!1===e&&!1!==i.da){const r=[];let n=Promise.resolve();i.ra.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(eF(i,t),wM(i.localStore,t,!0))),uL(i.remoteStore,t)}),await n,await oF(i,r),function(){const n=i;n.aa.forEach((e,t)=>{uL(n.remoteStore,t)}),n.ca.Si(),n.aa=new Map,n.ua=new Qx(wx.comparator)}(),i.da=!1,await TL(i.remoteStore,!1)}}async function oF(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.ra.get(t);if(u&&0!==u.length){e=await _M(r.localStore,NP(u[0]));for(const t of u){const n=r.ia.get(t),u=(o=r,a=n,l=c=void 0,l=await bM((c=o).localStore,a.query,!0),l=a.view.ta(l),c.isPrimaryClient&&nF(c,a.targetId,l.Xu),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await IM(r.localStore,t);e=await _M(r.localStore,u),await GL(r,aF(u),t,!1)}i.push(e)}var o,a,c,l;return r.sa.zo(s),i}function aF(e){return TP(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function cF(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=QL.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.aa.get(t);if(r&&r.na)return ID().add(r.key);{let e=ID();const r=n.ra.get(t);if(!r)return e;for(const t of r){const r=n.ia.get(t);e=e.unionWith(r.view.ju)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.aa.get(t),s=i&&i.key;if(s){let e=new Qx(wx.comparator);e=e.insert(s,jx.newNoDocument(s,ZR.min()));const n=ID().add(s),i=new ED(ZR.min(),new Map,new Xx(QR),e,n);await QL(r,i),r.ua=r.ua.remove(s),r.aa.delete(t),rF(r)}else await wM(r.localStore,t,!1).then(()=>eF(r,t,n)).catch(BO)}).bind(null,t),t.sa.zo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.Vu(e)&&(r=!0);i.Ru=e}}r&&ML(n)}).bind(null,t.eventManager),t.sa.wa=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function lF(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=JL.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.Bs.lookupMutationBatch(t,r).next(e=>(MR(null!==e),n=e.keys(),i.Bs.removeMutationBatch(t,e))).next(()=>i.Bs.performConsistencyCheck(t)).next(()=>i.fi.Ks(t,n))})}(r.localStore,t);ZL(r,t,n),XL(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await iF(r,e)}catch(n){await BO(n)}}).bind(null,t),t}class uF{constructor(){this.synchronizeTabs=!1}async initialize(e){this.M=ZM(e.databaseInfo.databaseId),this.sharedClientState=this.ga(e),this.persistence=this.ya(e),await this.persistence.start(),this.gcScheduler=this.pa(e),this.localStore=this.Ia(e)}pa(e){return null}Ia(e){return pM(this.persistence,new dM,e.initialUser,this.M)}ya(e){return new DM(MM.Yi,this.M)}ga(e){return new WM}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class hF extends uF{constructor(e,t,n){super(),this.Ta=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ta.initialize(this,e),await lF(this.Ta.syncEngine),await _L(this.Ta.remoteStore),await this.persistence.Ts(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Ia(e){return pM(this.persistence,new dM,e.initialUser,this.M)}pa(e){var t=this.persistence.referenceDelegate.garbageCollector;return new WO(t,e.asyncQueue)}ya(e){var t=lM(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?NO.withCacheSize(this.cacheSizeBytes):NO.DEFAULT;return new oM(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,JM(),XM(),this.M,this.sharedClientState,!!this.forceOwnership)}ga(e){return new WM}}class dF extends hF{constructor(e,t){super(e,t,!1),this.Ta=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ta.syncEngine;this.sharedClientState instanceof $M&&(this.sharedClientState.syncEngine={$r:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.Bs;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.fn(t,n).next(e=>e?r.fi.Ks(t,e):P1.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await _L(i.remoteStore):"acknowledged"===n||"rejected"===n?(ZL(i,t,r||null),XL(i,t),i.localStore.Bs._n(t)):OR(),await iF(i,s)):RR("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Br:(async function(e,t,n,r){const i=e;if(i.da)RR("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.ra.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await TM(i.localStore,MP(s[0])),r=ED.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await iF(i,e,r);break}case"rejected":await wM(i.localStore,t,!0),eF(i,t,r);break;default:OR()}}}).bind(null,t),Lr:(async function(e,t,n){const r=cF(e);if(r.da){for(const e of t)if(r.ra.has(e))RR("SyncEngine","Adding an already active target "+e);else{const t=await IM(r.localStore,e),n=await _M(r.localStore,t);await GL(r,aF(t),n.targetId,!1),lL(r.remoteStore,n)}for(const e of n)r.ra.has(e)&&await wM(r.localStore,e,!1).then(()=>{uL(r.remoteStore,e),eF(r,e)}).catch(BO)}}).bind(null,t),Fs:(function(e){return e.localStore.persistence.Fs()}).bind(null,t),Fr:(async function(e,t){const n=e;return TM(n.localStore,t).then(e=>iF(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ts(async e=>{await sF(this.Ta.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}ga(e){var t=JM();if(!$M.vt(t))throw new FR(LR.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=lM(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new $M(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class fF{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>YL(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){RR("SyncEngine","User change. New user:",t.toKey());const r=await gM(n.localStore,t);n.currentUser=t,(e=n).la.forEach(e=>{e.forEach(e=>{e.reject(new FR(LR.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.la.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await iF(n,r.di)}}).bind(null,this.syncEngine),await TL(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new PL}createDatastore(e){var t,n,r,i,s=ZM(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new YM(t));return n=e.authCredentials,r=e.appCheckCredentials,i=t,e=s,new iL(n,r,i,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>YL(this.syncEngine,e,0),s=new(GM.vt()?GM:zM),new oL(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new zL(e,t,n,r,i,s);return o&&(a.da=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;RR("RemoteStore","RemoteStore shutting down."),t.wu.add(5),await cL(t),t.gu.shutdown(),t.yu.set("Unknown")}(this.remoteStore)}}function pF(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class gF{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Ea(this.observer.next,e)}error(e){this.observer.error?this.Ea(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}Aa(){this.muted=!0}Ea(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class mF{constructor(e,t){this.Ra=e,this.M=t,this.metadata=new UR,this.buffer=new Uint8Array,this.Pa=new TextDecoder("utf-8"),this.ba().then(e=>{e&&e.Mu()?this.metadata.resolve(e.payload.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.payload)}`))},e=>this.metadata.reject(e))}close(){return this.Ra.cancel()}async getMetadata(){return this.metadata.promise}async ma(){return await this.getMetadata(),this.ba()}async ba(){var e=await this.Va();if(null===e)return null;var t=this.Pa.decode(e),n=Number(t);isNaN(n)&&this.va(`length string (${t}) is not valid number`);t=await this.Sa(n);return new FL(JSON.parse(t),e.length+n)}Da(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Va(){for(;this.Da()<0&&!await this.Ca(););if(0===this.buffer.length)return null;var e=this.Da();e<0&&this.va("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Sa(e){for(;this.buffer.length<e;)await this.Ca()&&this.va("Reached the end of bundle when more is expected.");var t=this.Pa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}va(e){throw this.Ra.cancel(),new Error(`Invalid bundle format: ${e}`)}async Ca(){var e=await this.Ra.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class vF{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new FR(LR.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=WD(r.M)+"/documents",i={documents:t.map(e=>VD(r.M,e))},s=await r._o("BatchGetDocuments",n,i),o=new Map;s.forEach(e=>{const t=(n=r.M,"found"in(e=e)?function(e,t){MR(!!t.found),t.found.name,t.found.updateTime;var n=BD(e,t.found.name),r=UD(t.found.updateTime),i=new qx({mapValue:{fields:t.found.fields}});return jx.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){MR(!!t.missing),MR(!!t.readTime);var n=BD(e,t.missing),r=UD(t.readTime);return jx.newNoDocument(n,r)}(n,e):OR());var n;o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=o.get(e.toString());MR(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new uD(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=wx.fromPath(t);this.mutations.push(new hD(n,this.precondition(n)))}),await async function(e,t){const n=e,r=WD(n.M)+"/documents",i={writes:t.map(e=>QD(n.M,e))};await n.co("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw OR();t=ZR.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new FR(LR.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?XP.updateTime(t):XP.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return XP.exists(!0);if(t.isEqual(ZR.min()))throw new FR(LR.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return XP.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class yF{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.xa=5,this.No=new eL(this.asyncQueue,"transaction_retry")}run(){--this.xa,this.Na()}Na(){this.No.Ro(async()=>{const t=new vF(this.datastore),e=this.ka(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Ma(e)}))}).catch(e=>{this.Ma(e)})})}ka(e){try{var t=this.updateFunction(e);return!vx(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Ma(e){0<this.xa&&this.Oa(e)?(--this.xa,this.asyncQueue.enqueueAndForget(()=>(this.Na(),Promise.resolve()))):this.deferred.reject(e)}Oa(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!fD(t)}}class _F{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=kR.UNAUTHENTICATED,this.clientId=HR.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{RR("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(RR("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new FR(LR.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new UR;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=CL(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function wF(e,t){e.asyncQueue.verifyOperationInProgress(),RR("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await gM(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function bF(e,n){e.asyncQueue.verifyOperationInProgress();var t=await IF(e);RR("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>IL(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>IL(n.remoteStore,t)),e.onlineComponents=n}async function IF(e){return e.offlineComponents||(RR("FirestoreClient","Using default OfflineComponentProvider"),await wF(e,new uF)),e.offlineComponents}async function TF(e){return e.onlineComponents||(RR("FirestoreClient","Using default OnlineComponentProvider"),await bF(e,new fF)),e.onlineComponents}function EF(e){return IF(e).then(e=>e.persistence)}function SF(e){return IF(e).then(e=>e.localStore)}function kF(e){return TF(e).then(e=>e.remoteStore)}function CF(e){return TF(e).then(e=>e.syncEngine)}async function AF(e){const t=await TF(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=cF(e);let r,i;const s=n.ia.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.ea();else{const e=await _M(n.localStore,NP(t));n.isPrimaryClient&&lL(n.remoteStore,e);const s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await GL(n,t,r,"current"===s)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ia.get(t),i=n.ra.get(r.targetId);if(1<i.length)return n.ra.set(r.targetId,i.filter(e=>!xP(e,t))),void n.ia.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await wM(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),uL(n.remoteStore,r.targetId),eF(n,r.targetId)}).catch(BO)):(eF(n,r.targetId),await wM(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function NF(e,t,n={}){const r=new UR;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,o){const e=new gF({next:e=>{r.enqueueAndForget(()=>OL(n,a));var t=e.docs.has(i);!t&&e.fromCache?o.reject(new FR(LR.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?o.reject(new FR(LR.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):o.resolve(e)},error:e=>o.reject(e)}),a=new LL(EP(i.path),e,{includeMetadataChanges:!0,ku:!0});return DL(n,a)}(await AF(e),e.asyncQueue,t,n,r)),r.promise}function RF(e,t,n={}){const r=new UR;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new gF({next:e=>{n.enqueueAndForget(()=>OL(t,o)),e.fromCache&&"server"===r.source?i.reject(new FR(LR.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),o=new LL(e,s,{includeMetadataChanges:!0,ku:!0});return DL(t,o)}(await AF(e),e.asyncQueue,t,n,r)),r.promise}function xF(e,t,n,r){const i=(n=n,t=ZM(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return pF(e,void 0);if(e instanceof ArrayBuffer)return pF(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new mF(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=UD(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n._s.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(jL(i));const o=new qL(i,t.localStore,n.M);let e=await n.ma();for(;e;){const t=await o.Fu(e);t&&r._updateProgress(t),e=await n.ma()}var s=await o.complete();return await iF(t,s.Lu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n._s.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.Bu)}catch(t){return PR("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await CF(e),i,r)})}const PF=new Map;function DF(e,t,n){if(!n)throw new FR(LR.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function OF(e,t,n,r){if(!0===t&&!0===r)throw new FR(LR.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function MF(e){if(!wx.isDocumentKey(e))throw new FR(LR.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function LF(e){if(wx.isDocumentKey(e))throw new FR(LR.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function FF(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":OR();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function UF(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new FR(LR.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=FF(e);throw new FR(LR.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function qF(e,t){if(t<=0)throw new FR(LR.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class jF{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new FR(LR.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new FR(LR.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,OF("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class VF{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new jF({}),this._settingsFrozen=!1,e instanceof mx?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new FR(LR.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new mx(e.options.projectId)}(e))}get app(){if(!this._app)throw new FR(LR.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new FR(LR.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new jF(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new jR;switch(e.type){case"gapi":var t=e.client;return MR(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new $R(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new FR(LR.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=PF.get(e);t&&(RR("ComponentProvider","Removing Datastore"),PF.delete(e),t.terminate())}(this),Promise.resolve()}}class BF{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new $F(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new BF(this.firestore,e,this._key)}}class KF{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new KF(this.firestore,e,this._query)}}class $F extends KF{constructor(e,t,n){super(e,t,EP(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new BF(this.firestore,null,new wx(e))}withConverter(e){return new $F(this.firestore,e,this._path)}}function WF(e,t,...n){if(e=$d(e),DF("collection","path",t),e instanceof VF){var r=ix.fromString(t,...n);return LF(r),new $F(e,null,r)}if(!(e instanceof BF||e instanceof $F))throw new FR(LR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ix.fromString(t,...n));return LF(r),new $F(e.firestore,null,r)}function zF(e,t,...n){if(e=$d(e),DF("doc","path",t=1===arguments.length?HR.R():t),e instanceof VF){var r=ix.fromString(t,...n);return MF(r),new BF(e,null,new wx(r))}if(!(e instanceof BF||e instanceof $F))throw new FR(LR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ix.fromString(t,...n));return MF(r),new BF(e.firestore,e instanceof $F?e.converter:null,new wx(r))}function GF(e,t){return e=$d(e),t=$d(t),(e instanceof BF||e instanceof $F)&&(t instanceof BF||t instanceof $F)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function HF(e,t){return e=$d(e),t=$d(t),e instanceof KF&&t instanceof KF&&e.firestore===t.firestore&&xP(e._query,t._query)&&e.converter===t.converter}class QF{constructor(){this.Fa=Promise.resolve(),this.$a=[],this.Ba=!1,this.La=[],this.Ua=null,this.qa=!1,this.Ka=!1,this.Ga=[],this.No=new eL(this,"async_queue_retry"),this.Qa=()=>{var e=XM();e&&RR("AsyncQueue","Visibility state changed to "+e.visibilityState),this.No.bo()};const e=XM();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Qa)}get isShuttingDown(){return this.Ba}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ja(),this.Wa(e)}enterRestrictedMode(e){if(!this.Ba){this.Ba=!0,this.Ka=e||!1;const t=XM();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Qa)}}enqueue(e){if(this.ja(),this.Ba)return new Promise(()=>{});const t=new UR;return this.Wa(()=>this.Ba&&this.Ka?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.$a.push(e),this.za()))}async za(){if(0!==this.$a.length){try{await this.$a[0](),this.$a.shift(),this.No.reset()}catch(e){if(!F1(e))throw e;RR("AsyncQueue","Operation failed with retryable error: "+e)}0<this.$a.length&&this.No.Ro(()=>this.za())}}Wa(e){var t=this.Fa.then(()=>(this.qa=!0,e().catch(e=>{throw this.Ua=e,this.qa=!1,xR("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.qa=!1,e))));return this.Fa=t}enqueueAfterDelay(e,t,n){this.ja(),-1<this.Ga.indexOf(e)&&(t=0);var r=kL.createAndSchedule(this,e,t,n,e=>this.Ha(e));return this.La.push(r),r}ja(){this.Ua&&OR()}verifyOperationInProgress(){}async Ja(){for(var e;await(e=this.Fa),e!==this.Fa;);}Ya(e){for(const t of this.La)if(t.timerId===e)return!0;return!1}Xa(t){return this.Ja().then(()=>{this.La.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.La)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Ja()})}Za(e){this.Ga.push(e)}Ha(e){var t=this.La.indexOf(e);this.La.splice(t,1)}}function YF(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class JF{constructor(){this._progressObserver={},this._taskCompletionResolver=new UR,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var XF,ZF,eU,tU;class nU extends VF{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new QF,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||iU(this),this._firestoreClient.terminate()}}function rU(e){return e._firestoreClient||iU(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function iU(e){var t,n,r,i,s,o=e._freezeSettings(),o=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",i=e._persistenceKey,s=o,new gx(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new _F(e._authCredentials,e._appCheckCredentials,e._queue,o)}function sU(e,n,r){const i=new UR;return e.asyncQueue.enqueue(async()=>{try{await wF(e,r),await bF(e,n),i.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===LR.FAILED_PRECONDITION||t.code===LR.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw e;console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+e),i.reject(e)}var t}).then(()=>i.promise)}function oU(e){return function(e){const t=new UR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;gL(n.remoteStore)||RR("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.Bs.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.la.get(e)||[];r.push(t),n.la.set(e,r)}catch(e){const n=CL(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await CF(e),t)),t.promise}(rU(e=UF(e,nU)))}function aU(e){return(n=rU(e=UF(e,nU))).asyncQueue.enqueue(async()=>{const e=await EF(n),t=await kF(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.wu.delete(0),aL(e)}()});var n}function cU(e){return(n=rU(e=UF(e,nU))).asyncQueue.enqueue(async()=>{const e=await EF(n),t=await kF(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.wu.add(0),await cL(e),e.yu.set("Offline")}()});var n}function lU(t,e){return n=rU(t=UF(t,nU)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n._s.getNamedQuery(e,t))}(await SF(n),r)).then(e=>e?new KF(t,null,e.query):null);var n,r}function uU(e){if(e._initialized||e._terminated)throw new FR(LR.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class hU{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new FR(LR.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new ox(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class dU{constructor(e){this._byteString=e}static fromBase64String(e){try{return new dU(cx.fromBase64String(e))}catch(e){throw new FR(LR.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new dU(cx.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class fU{constructor(e){this._methodName=e}}class pU{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new FR(LR.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new FR(LR.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return QR(this._lat,e._lat)||QR(this._long,e._long)}}const gU=/^__.*__$/;class mU{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new oD(e,this.data,this.fieldMask,t,this.fieldTransforms):new sD(e,this.data,t,this.fieldTransforms)}}class vU{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new oD(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function yU(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw OR()}}class _U{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.M=n,this.ignoreUndefinedProperties=r,void 0===i&&this.tc(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get ec(){return this.settings.ec}nc(e){return new _U(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.M,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}sc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.nc({path:n,ic:!1});return r.rc(e),r}oc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.nc({path:n,ic:!1});return r.tc(),r}uc(e){return this.nc({path:void 0,ic:!0})}ac(e){return qU(e,this.settings.methodName,this.settings.cc||!1,this.path,this.settings.hc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}tc(){if(this.path)for(let e=0;e<this.path.length;e++)this.rc(this.path.get(e))}rc(e){if(0===e.length)throw this.ac("Document fields must not be empty");if(yU(this.ec)&&gU.test(e))throw this.ac('Document fields cannot begin and end with "__"')}}class wU{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.M=n||ZM(e)}lc(e,t,n,r=!1){return new _U({ec:e,methodName:t,hc:n,path:ox.emptyPath(),ic:!1,cc:r},this.databaseId,this.M,this.ignoreUndefinedProperties)}}function bU(e){var t=e._freezeSettings(),n=ZM(e._databaseId);return new wU(e._databaseId,!!t.ignoreUndefinedProperties,n)}function IU(e,t,n,r,i,s={}){const o=e.lc(s.merge||s.mergeFields?2:0,t,n,i);MU("Data must be an object, but it was:",o,r);var a=DU(r,o);let c,l;if(s.merge)c=new ax(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=LU(t,r,n);if(!o.contains(i))throw new FR(LR.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);jU(e,i)||e.push(i)}c=new ax(e),l=o.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=o.fieldTransforms;return new mU(new qx(a),c,l)}class TU extends fU{_toFieldTransform(e){if(2!==e.ec)throw 1===e.ec?e.ac(`${this._methodName}() can only appear at the top level of your update data`):e.ac(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof TU}}function EU(e,t,n){return new _U({ec:3,hc:t.settings.hc,methodName:e._methodName,ic:n},t.databaseId,t.M,t.ignoreUndefinedProperties)}class SU extends fU{_toFieldTransform(e){return new YP(e.path,new BP)}isEqual(e){return e instanceof SU}}class kU extends fU{constructor(e,t){super(e),this.fc=t}_toFieldTransform(e){const t=EU(this,e,!0),n=this.fc.map(e=>PU(e,t)),r=new KP(n);return new YP(e.path,r)}isEqual(e){return this===e}}class CU extends fU{constructor(e,t){super(e),this.fc=t}_toFieldTransform(e){const t=EU(this,e,!0),n=this.fc.map(e=>PU(e,t)),r=new WP(n);return new YP(e.path,r)}isEqual(e){return this===e}}class AU extends fU{constructor(e,t){super(e),this.dc=t}_toFieldTransform(e){var t=new GP(e.M,qP(e.M,this.dc));return new YP(e.path,t)}isEqual(e){return this===e}}function NU(e,i,s,t){const o=e.lc(1,i,s);MU("Data must be an object, but it was:",o,t);const a=[],c=qx.empty();tx(t,(e,t)=>{var n=UU(i,e,s);t=$d(t);var r=o.oc(n);if(t instanceof TU)a.push(n);else{const e=PU(t,r);null!=e&&(a.push(n),c.set(n,e))}});var n=new ax(a);return new vU(c,n,o.fieldTransforms)}function RU(e,t,n,r,i,s){const o=e.lc(1,t,n),a=[LU(t,r,n)],c=[i];if(s.length%2!=0)throw new FR(LR.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)a.push(LU(t,s[f])),c.push(s[f+1]);const l=[],u=qx.empty();for(let p=a.length-1;0<=p;--p)if(!jU(l,a[p])){const t=a[p];var h=$d(h=c[p]);const r=o.oc(t);if(h instanceof TU)l.push(t);else{const e=PU(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new ax(l);return new vU(u,d,o.fieldTransforms)}function xU(e,t,n,r=!1){return PU(n,e.lc(r?4:3,t))}function PU(s,e){if(OU(s=$d(s)))return MU("Unsupported field value:",e,s),DU(s,e);if(s instanceof fU)return function(e,t){if(!yU(t.ec))throw t.ac(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ac(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(s,e),null;if(void 0===s&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),s instanceof Array){if(e.settings.ic&&4!==e.ec)throw e.ac("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=PU(i,t.uc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=$d(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return qP(t.M,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=XR.fromDate(e);return{timestampValue:LD(t.M,n)}}if(e instanceof XR){n=new XR(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:LD(t.M,n)}}if(e instanceof pU)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof dU)return{bytesValue:FD(t.M,e._byteString)};if(e instanceof BF){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.ac(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:qD(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ac(`Unsupported field value: ${FF(e)}`)}(0,e)}function DU(e,r){const i={};return nx(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):tx(e,(e,t)=>{var n=PU(t,r.sc(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function OU(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof XR||e instanceof pU||e instanceof dU||e instanceof BF||e instanceof fU)}function MU(e,t,n){if(!OU(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=FF(n);throw"an object"===r?t.ac(e+" a custom object"):t.ac(e+" "+r)}var i}function LU(e,t,n){if((t=$d(t))instanceof hU)return t._internalPath;if("string"==typeof t)return UU(e,t);throw qU("Field path arguments must be of type string or ",e,!1,void 0,n)}const FU=new RegExp("[~\\*/\\[\\]]");function UU(t,n,r){if(0<=n.search(FU))throw qU(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new hU(...n.split("."))._internalPath}catch(e){throw qU(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function qU(e,t,n,r,i){var s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new FR(LR.INVALID_ARGUMENT,a+e+c)}function jU(e,t){return e.some(e=>e.isEqual(t))}class VU{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new BF(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new BU(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(KU("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class BU extends VU{data(){return super.data()}}function KU(e,t){return"string"==typeof t?UU(e,t):(t instanceof hU?t:t._delegate)._internalPath}class $U{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class WU extends VU{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new zU(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(KU("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class zU extends WU{data(e={}){return super.data(e)}}class GU{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new $U(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new zU(this._firestore,this._userDataWriter,e.key,e,new $U(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new FR(LR.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let t=0;return s._snapshot.docChanges.map(e=>({type:"added",doc:new zU(s._firestore,s._userDataWriter,e.doc.key,e.doc,new $U(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter),oldIndex:-1,newIndex:t++}))}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new zU(s._firestore,s._userDataWriter,e.doc.key,e.doc,new $U(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return OR()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function HU(e,t){return e instanceof WU&&t instanceof WU?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof GU&&t instanceof GU&&e._firestore===t._firestore&&HF(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function QU(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new FR(LR.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class YU{}function JU(e,...t){for(const n of t)e=n._apply(e);return e}class XU extends YU{constructor(e,t,n){super(),this._c=e,this.wc=t,this.mc=n,this.type="where"}_apply(e){var t=bU(e.firestore),t=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new FR(LR.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){sq(o,s);const t=[];for(const n of o)t.push(iq(r,e,n));a={arrayValue:{values:t}}}else a=iq(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||sq(o,s),a=xU(n,t,o,"in"===s||"not-in"===s);var c=lP.create(i,s,a);return function(e,t){if(t.S()){const r=kP(e);if(null!==r&&!r.isEqual(t.field))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${t.field.toString()}'`);var n=SP(e);null!==n&&oq(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new FR(LR.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new FR(LR.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,c),c}(e._query,"where",t,e.firestore._databaseId,this._c,this.wc,this.mc);return new KF(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new IP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class ZU extends YU{constructor(e,t){super(),this._c=e,this.gc=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new FR(LR.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new FR(LR.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new _P(t,n);return n=i,null!==SP(e=e)||null!==(r=kP(e))&&oq(0,r,n.field),i}(e._query,this._c,this.gc);return new KF(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new IP(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class eq extends YU{constructor(e,t,n){super(),this.type=e,this.yc=t,this.Ic=n}_apply(e){return new KF(e.firestore,e.converter,RP(e._query,this.yc,this.Ic))}}class tq extends YU{constructor(e,t,n){super(),this.type=e,this.Tc=t,this.Ec=n}_apply(e){var t,n=rq(e,this.type,this.Tc,this.Ec);return new KF(e.firestore,e.converter,(t=e._query,e=n,new IP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class nq extends YU{constructor(e,t,n){super(),this.type=e,this.Tc=t,this.Ec=n}_apply(e){var t,n=rq(e,this.type,this.Tc,this.Ec);return new KF(e.firestore,e.converter,(t=e._query,e=n,new IP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function rq(e,t,n,r){if(n[0]=$d(n[0]),n[0]instanceof VU)return function(e,t,n,r,i){if(!r)throw new FR(LR.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of AP(e))if(n.field.isKeyField())s.push(Nx(t,r.key));else{const e=r.data.field(n.field);if(fx(e))throw new FR(LR.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new FR(LR.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new yP(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=bU(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new FR(LR.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let c=0;c<i.length;c++){const l=i[c];if(o[c].field.isKeyField()){if("string"!=typeof l)throw new FR(LR.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!CP(e)&&-1!==l.indexOf("/"))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(ix.fromString(l));if(!wx.isDocumentKey(n))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new wx(n);a.push(Nx(t,i))}else{const e=xU(n,r,l);a.push(e)}}return new yP(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function iq(e,t,n){if("string"==typeof(n=$d(n))){if(""===n)throw new FR(LR.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!CP(t)&&-1!==n.indexOf("/"))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(ix.fromString(n));if(!wx.isDocumentKey(r))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Nx(e,new wx(r))}if(n instanceof BF)return Nx(e,n._key);throw new FR(LR.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${FF(n)}.`)}function sq(e,t){if(!Array.isArray(e)||0===e.length)throw new FR(LR.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new FR(LR.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function oq(e,t,n){if(!n.isEqual(t))throw new FR(LR.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class aq{convertValue(e,t="none"){switch(Tx(e)){case 0:return null;case 1:return e.booleanValue;case 2:return hx(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(dx(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw OR()}}convertObject(e,n){const r={};return tx(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new pU(hx(e.latitude),hx(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return fx(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(px(e));default:return null}}convertTimestamp(e){var t=ux(e);return new XR(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=ix.fromString(e);MR(i1(n));const r=new mx(n.get(1),n.get(3)),i=new wx(n.popFirst(5));return r.isEqual(t)||xR(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function cq(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class lq extends aq{constructor(e){super(),this.firestore=e}convertBytes(e){return new dU(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new BF(this.firestore,null,t)}}class uq{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=bU(e)}set(e,t,n){this._verifyNotCommitted();const r=hq(e,this._firestore),i=cq(r.converter,t,n),s=IU(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,XP.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=hq(e,this._firestore);let s;return s="string"==typeof(t=$d(t))||t instanceof hU?RU(this._dataReader,"WriteBatch.update",i._key,t,n,r):NU(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,XP.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=hq(e,this._firestore);return this._mutations=this._mutations.concat(new uD(t._key,XP.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FR(LR.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function hq(e,t){if((e=$d(e)).firestore!==t)throw new FR(LR.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class dq extends aq{constructor(e){super(),this.firestore=e}convertBytes(e){return new dU(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new BF(this.firestore,null,t)}}function fq(t){t=UF(t,BF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return function(e,t){const n=new UR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.fi.Ls(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new FR(LR.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=CL(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await SF(e),t,n)),n.promise}(e,t._key).then(e=>new WU(n,r,t._key,e,new $U(null!==e&&e.hasLocalMutations,!0),t.converter))}function pq(t){t=UF(t,KF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return function(e,t){const n=new UR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await bM(e,t,!0),s=new KL(t,i._i),o=s.Wu(i.documents),a=s.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=CL(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await SF(e),t,n)),n.promise}(e,t._query).then(e=>new GU(n,r,t,e))}function gq(e,t,n){e=UF(e,BF);var r=UF(e.firestore,nU),i=cq(e.converter,t,n);return _q(r,[IU(bU(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,XP.none())])}function mq(e,t,n,...r){e=UF(e,BF);var i=UF(e.firestore,nU),s=bU(i);let o;return o="string"==typeof(t=$d(t))||t instanceof hU?RU(s,"updateDoc",e._key,t,n,r):NU(s,"updateDoc",e._key,t),_q(i,[o.toMutation(e._key,XP.exists(!0))])}function vq(t,...n){var e;t=$d(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||YF(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(YF(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let o,a,c;if(t instanceof BF)a=UF(t.firestore,nU),c=EP(t._key.path),o={next:e=>{n[i]&&n[i](wq(a,t,e))},error:n[i+1],complete:n[i+2]};else{const l=UF(t,KF);a=UF(l.firestore,nU),c=l._query;const u=new dq(a);o={next:e=>{n[i]&&n[i](new GU(a,u,l,e))},error:n[i+1],complete:n[i+2]},QU(t._query)}return function(e,t,n,r){const i=new gF(r),s=new LL(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>DL(await AF(e),s)),()=>{i.Aa(),e.asyncQueue.enqueueAndForget(async()=>OL(await AF(e),s))}}(rU(a),c,s,o)}function yq(e,t){return function(e,t){const n=new gF(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Pu.add(t),t.next()}(await AF(e),n)),()=>{n.Aa(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Pu.delete(t)}(await AF(e),n))}}(rU(e=UF(e,nU)),YF(t)?t:{next:t})}function _q(e,t){return function(e,t){const n=new UR;return e.asyncQueue.enqueueAndForget(async()=>HL(await CF(e),t,n)),n.promise}(rU(e),t)}function wq(e,t,n){var r=n.docs.get(t._key),i=new dq(e);return new WU(e,i,t._key,r,new $U(n.hasPendingWrites,n.fromCache),t.converter)}class bq extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=bU(e)}get(e){const n=hq(e,this._firestore),r=new lq(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return OR();const t=e[0];if(t.isFoundDocument())return new VU(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new VU(this._firestore,r,n._key,null,n.converter);throw OR()})}set(e,t,n){var r=hq(e,this._firestore),i=cq(r.converter,t,n),i=IU(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=hq(e,this._firestore),s="string"==typeof(t=$d(t))||t instanceof hU?RU(this._dataReader,"Transaction.update",i._key,t,n,r):NU(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=hq(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=hq(e,this._firestore),n=new dq(this._firestore);return super.get(e).then(e=>new WU(this._firestore,n,t._key,e._document,new $U(!1,!1),t.converter))}}function Iq(t,n){return function(t,n){const r=new UR;return t.asyncQueue.enqueueAndForget(async()=>{var e=await TF(t).then(e=>e.datastore);new yF(t.asyncQueue,e,n,r).run()}),r.promise}(rU(t=UF(t,nU)),e=>n(new bq(t,e)))}z=Tf,CR=z,_f(new Xd("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new nU(n,new BR(e.getProvider("auth-internal")),new zR(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),Cf(SR,"3.4.8",void 0),Cf(SR,"3.4.8","esm2017");function Tq(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new FR("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Eq(){if("undefined"==typeof Uint8Array)throw new FR("unimplemented","Uint8Arrays are not available in this environment.")}function Sq(){if("undefined"==typeof atob)throw new FR("unimplemented","Blobs are unavailable in Firestore in this environment.")}class kq{constructor(e){this._delegate=e}static fromBase64String(e){return Sq(),new kq(dU.fromBase64String(e))}static fromUint8Array(e){return Eq(),new kq(dU.fromUint8Array(e))}toBase64(){return Sq(),this._delegate.toBase64()}toUint8Array(){return Eq(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Cq(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class Aq{enableIndexedDbPersistence(e,t){return function(e,t){uU(e=UF(e,nU));var n=rU(e),r=e._freezeSettings(),i=new fF;return sU(n,i,new hF(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){uU(e=UF(e,nU));var t=rU(e),n=e._freezeSettings(),r=new fF;return sU(t,r,new dF(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new FR(LR.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new UR;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!O1.vt())return Promise.resolve();var t=e+"main";await O1.delete(t)}(lM(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Nq{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof mx||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||PR("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=UF(n,VF))._getSettings();if("firestore.googleapis.com"!==s.host&&s.host!==e&&PR("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},s),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=kR.MOCK_USER;else{e=id(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new FR(LR.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new kR(s)}n._authCredentials=new VR(new qR(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return aU(this._delegate)}disableNetwork(){return cU(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,OF("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return oU(this._delegate)}onSnapshotsInSync(e){return yq(this._delegate,e)}get app(){if(!this._appCompat)throw new FR("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Kq(this,WF(this._delegate,e))}catch(e){throw Mq(e,"collection()","Firestore.collection()")}}doc(e){try{return new Oq(this,zF(this._delegate,e))}catch(e){throw Mq(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new jq(this,function(e,t){if(e=UF(e,VF),DF("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new FR(LR.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new KF(e,null,(t=t,new IP(ix.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Mq(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Iq(this._delegate,e=>t(new xq(this,e)))}batch(){return rU(this._delegate),new Pq(new uq(this._delegate,e=>_q(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=rU(t=UF(t,nU)),r=new JF,xF(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return lU(this._delegate,e).then(e=>e?new jq(this,e):null)}}class Rq extends aq{constructor(e){super(),this.firestore=e}convertBytes(e){return new kq(new dU(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Oq.forKey(t,this.firestore,null)}}class xq{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Rq(e)}get(e){const t=$q(e);return this._delegate.get(t).then(e=>new Uq(this._firestore,new WU(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=$q(e);return n?(Tq("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=$q(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=$q(e);return this._delegate.delete(t),this}}class Pq{constructor(e){this._delegate=e}set(e,t,n){var r=$q(e);return n?(Tq("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=$q(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=$q(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Dq{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new zU(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new qq(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=Dq.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Dq(e,new Rq(e),t),r.set(t,i)),i}}Dq.INSTANCES=new WeakMap;class Oq{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Rq(e)}static forPath(e,t,n){if(e.length%2!=0)throw new FR("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Oq(t,new BF(t._delegate,n,new wx(e)))}static forKey(e,t,n){return new Oq(t,new BF(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Kq(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Kq(this.firestore,WF(this._delegate,e))}catch(e){throw Mq(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=$d(e))instanceof BF&&GF(this._delegate,e)}set(e,t){t=Tq("DocumentReference.set",t);try{return t?gq(this._delegate,e,t):gq(this._delegate,e)}catch(e){throw Mq(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?mq(this._delegate,e):mq(this._delegate,e,t,...n)}catch(e){throw Mq(e,"updateDoc()","DocumentReference.update()")}}delete(){return _q(UF((e=this._delegate).firestore,nU),[new uD(e._key,XP.none())]);var e}onSnapshot(...e){var t=Lq(e),n=Fq(e,e=>new Uq(this.firestore,new WU(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return vq(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?fq:"server"===(null==e?void 0:e.source)?function(t){t=UF(t,BF);const n=UF(t.firestore,nU);return NF(rU(n),t._key,{source:"server"}).then(e=>wq(n,t,e))}:function(t){t=UF(t,BF);const n=UF(t.firestore,nU);return NF(rU(n),t._key).then(e=>wq(n,t,e))})(this._delegate),t.then(e=>new Uq(this.firestore,new WU(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Oq(this.firestore,e?this._delegate.withConverter(Dq.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Mq(e,t,n){return e.message=e.message.replace(t,n),e}function Lq(e){for(const t of e)if("object"==typeof t&&!Cq(t))return t;return{}}function Fq(e,t){var n;let r;return r=Cq(e[0])?e[0]:Cq(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class Uq{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Oq(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return HU(this._delegate,e._delegate)}}class qq extends Uq{data(e){var t=this._delegate.data(e);return void 0!==t||OR(),t}}class jq{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Rq(e)}where(e,t,n){try{return new jq(this.firestore,JU(this._delegate,(r=n,i=t,s=KU("where",e),new XU(s,i,r))))}catch(e){throw Mq(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new jq(this.firestore,JU(this._delegate,([n,r="asc"]=[e,t],i=r,s=KU("orderBy",n),new ZU(s,i))))}catch(e){throw Mq(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new jq(this.firestore,JU(this._delegate,(qF("limit",t=e),new eq("limit",t,"F"))))}catch(e){throw Mq(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new jq(this.firestore,JU(this._delegate,(qF("limitToLast",t=e),new eq("limitToLast",t,"L"))))}catch(e){throw Mq(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new tq("startAt",e,!0)}(...e)))}catch(e){throw Mq(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new tq("startAfter",e,!1)}(...e)))}catch(e){throw Mq(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new nq("endBefore",e,!1)}(...e)))}catch(e){throw Mq(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new jq(this.firestore,JU(this._delegate,function(...e){return new nq("endAt",e,!0)}(...e)))}catch(e){throw Mq(e,"endAt()","Query.endAt()")}}isEqual(e){return HF(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?pq:"server"===(null==e?void 0:e.source)?function(t){t=UF(t,KF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return RF(e,t._query,{source:"server"}).then(e=>new GU(n,r,t,e))}:function(t){t=UF(t,KF);const n=UF(t.firestore,nU),e=rU(n),r=new dq(n);return QU(t._query),RF(e,t._query).then(e=>new GU(n,r,t,e))})(this._delegate),t.then(e=>new Bq(this.firestore,new GU(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Lq(e),n=Fq(e,e=>new Bq(this.firestore,new GU(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return vq(this._delegate,t,n)}withConverter(e){return new jq(this.firestore,e?this._delegate.withConverter(Dq.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Vq{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new qq(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Bq{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new jq(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new qq(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Vq(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new qq(this._firestore,e))})}isEqual(e){return HU(this._delegate,e._delegate)}}class Kq extends jq{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new Oq(this.firestore,e):null}doc(e){try{return void 0===e?new Oq(this.firestore,zF(this._delegate)):new Oq(this.firestore,zF(this._delegate,e))}catch(e){throw Mq(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=UF(e.firestore,nU),r=zF(e),i=cq(e.converter,t);return _q(n,[IU(bU(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,XP.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Oq(this.firestore,e))}isEqual(e){return GF(this._delegate,e._delegate)}withConverter(e){return new Kq(this.firestore,e?this._delegate.withConverter(Dq.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function $q(e){return UF(e,BF)}const Wq={Firestore:Nq,GeoPoint:pU,Timestamp:XR,Blob:kq,Transaction:xq,WriteBatch:Pq,DocumentReference:Oq,DocumentSnapshot:Uq,Query:jq,QueryDocumentSnapshot:qq,QuerySnapshot:Bq,CollectionReference:Kq,FieldPath:class GK{constructor(...e){this._delegate=new hU(...e)}static documentId(){return new GK(ox.keyField().canonicalString())}isEqual(e){return(e=$d(e))instanceof hU&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class HK{constructor(e){this._delegate=e}static serverTimestamp(){const e=new SU("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new HK(e)}static delete(){const e=new TU("deleteField");return e._methodName="FieldValue.delete",new HK(e)}static arrayUnion(...e){const t=function(...e){return new kU("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new HK(t)}static arrayRemove(...e){const t=function(...e){return new CU("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new HK(t)}static increment(e){const t=new AU("increment",e);return t._methodName="FieldValue.increment",new HK(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,AR.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};XF=zf,ZF=(e,t)=>new Nq(e,t,new Aq),XF.INTERNAL.registerComponent(new Xd("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return ZF(t,n)},"PUBLIC").setServiceProps(Object.assign({},Wq))),XF.registerVersion("@firebase/firestore-compat","0.1.17");const zq="type.googleapis.com/google.protobuf.Int64Value",Gq="type.googleapis.com/google.protobuf.UInt64Value";function Hq(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function Qq(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case zq:case Gq:var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>Qq(e)):"function"==typeof e||"object"==typeof e?Hq(e,e=>Qq(e)):e}const Yq="functions",Jq={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class Xq extends gd{constructor(e,t,n){super(`${Yq}/${e}`,t||""),this.details=n}}function Zq(e,t){let n=function(e){if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!Jq[e])return new Xq("internal","internal");n=Jq[e],r=e}var o=s.message;"string"==typeof o&&(r=o),i=s.details,void 0!==i&&(i=Qq(i))}}catch(e){}return"ok"===n?null:new Xq(n,r,i)}class ej{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){var e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const tj="us-central1";class nj{constructor(e,t,n,r,i=tj,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ej(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var o=new URL(i);this.customDomain=o.origin,this.region=tj}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function rj(i,s,o){return e=>{return t=e,n=o||{},r=(e=i)._url(s),ij(e,r,t,n);var t,n,r}}async function ij(e,t,n,r){var i={data:n=function t(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>t(e));if("function"==typeof e||"object"==typeof e)return Hq(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)};const s={};var o=await e.contextProvider.getContext();o.authToken&&(s.Authorization="Bearer "+o.authToken),o.messagingToken&&(s["Firebase-Instance-ID-Token"]=o.messagingToken),null!==o.appCheckToken&&(s["X-Firebase-AppCheck"]=o.appCheckToken);const a=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new Xq("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(r.timeout||7e4);o=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}(t,i,s,e.fetchImpl),a.promise,e.cancelAllRequests]);if(a.cancel(),!o)throw new Xq("cancelled","Firebase Functions instance was deleted.");i=Zq(o.status,o.json);if(i)throw i;if(!o.json)throw new Xq("internal","Response is not valid JSON object.");let c=o.json.data;if(void 0===c&&(c=o.json.result),void 0===c)throw new Xq("internal","Response is missing data field.");return{data:Qq(c)}}const sj="@firebase/functions";function oj(e,t,n){$d(e).emulatorOrigin=`http://${t}:${n}`}function aj(e,t,n){return r=$d(e),i=t,s=n,e=>ij(r,i,e,s||{});var r,i,s}eU=fetch.bind(self),_f(new Xd(Yq,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new nj(n,r,i,s,t,eU)},"PUBLIC").setMultipleInstances(!0)),Cf(sj,"0.8.0",tU),Cf(sj,"0.8.0","esm2017");var cj,lj,uj,hj;class dj{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return rj($d(this._delegate),e,t)}httpsCallableFromURL(e,t){return aj(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new gd("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new gd("functions","Port missing in origin provided to useFunctionsEmulator()");return oj(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return oj(this._delegate,e,t)}}const fj="us-central1",pj=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:fj});return new dj(n,r)};cj={Functions:dj},zf.INTERNAL.registerComponent(new Xd("functions-compat",pj,"PUBLIC").setServiceProps(cj).setMultipleInstances(!0)),zf.registerVersion("@firebase/functions-compat","0.2.0");const gj="/firebase-messaging-sw.js",mj="/firebase-cloud-messaging-push-scope",vj="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",yj="https://fcmregistrations.googleapis.com/v1",_j="google.c.a.c_id",wj="google.c.a.e";function bj(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=N2=N2||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(yt=lj=lj||{}).PUSH_RECEIVED="push-received",yt.NOTIFICATION_CLICKED="notification-clicked";const Ij="fcm_token_details_db",Tj="fcm_token_object_Store";async function Ej(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(Ij))return null}let l=null;const e=await Yd(Ij,5,async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(Tj)){const a=r.objectStore(Tj);var s,o=await a.index("fcmSenderId").get(c);await a.clear(),o&&(2===t?(s=o).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:bj(s.vapidKey)}}):3===t?(s=o,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:bj(s.auth),p256dh:bj(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:bj(s.vapidKey)}}):4===t&&(o=o,l={token:o.fcmToken,createTime:o.createTime,subscriptionOptions:{auth:bj(o.auth),p256dh:bj(o.p256dh),endpoint:o.endpoint,swScope:o.swScope,vapidKey:bj(o.vapidKey)}}))}});return e.close(),await Jd(Ij),await Jd("fcm_vapid_details_db"),await Jd("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const Sj="firebase-messaging-database",kj=1,Cj="firebase-messaging-store";let Aj=null;function Nj(){return Aj=Aj||Yd(Sj,kj,(e,t)=>{0===t&&e.createObjectStore(Cj)}),Aj}async function Rj(e){var t=Pj(e);const n=await Nj();t=await n.transaction(Cj).objectStore(Cj).get(t);if(t)return t;t=await Ej(e.appConfig.senderId);return t?(await xj(e,t),t):void 0}async function xj(e,t){var n=Pj(e);const r=await Nj(),i=r.transaction(Cj,"readwrite");return await i.objectStore(Cj).put(t,n),await i.complete,t}function Pj({appConfig:e}){return e.appId}const Dj=new md("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function Oj(e,t){var n={method:"DELETE",headers:await Lj(e)};try{const s=await fetch(`${Mj(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw Dj.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw Dj.create("token-unsubscribe-failed",{errorInfo:e})}}function Mj({projectId:e}){return`${yj}/projects/${e}/registrations`}async function Lj({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function Fj({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==vj&&(i.web.applicationPubKey=r),i}const Uj=6048e5;async function qj(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,o,a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:bj(t.getKey("auth")),p256dh:bj(t.getKey("p256dh"))},c=await Rj(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=a.vapidKey===n.vapidKey,i=a.endpoint===n.endpoint,s=a.auth===n.auth,o=a.p256dh===n.p256dh,r&&i&&s&&o)return Date.now()>=c.createTime+Uj?async function(t,e){try{var n=await async function(e,t){var n=await Lj(e),r=Fj(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${Mj(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw Dj.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Dj.create("token-update-failed",{errorInfo:r})}if(!i.token)throw Dj.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await xj(t.firebaseDependencies,r),n}catch(e){throw await jj(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Oj(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Vj(e.firebaseDependencies,a)}return Vj(e.firebaseDependencies,a)}async function jj(e){var t=await Rj(e.firebaseDependencies);t&&(await Oj(e.firebaseDependencies,t.token),await async function(e){var t=Pj(e);const n=await Nj(),r=n.transaction(Cj,"readwrite");await r.objectStore(Cj).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Vj(e,t){var n={token:await async function(e,t){var n=await Lj(e),r=Fj(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(Mj(e.appConfig),r);i=await s.json()}catch(e){throw Dj.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Dj.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw Dj.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await xj(e,n),n.token}function Bj(e){var t,n,r,i={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return n=i,(t=e).notification&&(n.notification={},(r=t.notification.title)&&(n.notification.title=r),(r=t.notification.body)&&(n.notification.body=r),(r=t.notification.image)&&(n.notification.image=r)),t=i,(n=e).data&&(t.data=n.data),n=i,(e=e).fcmOptions&&(n.fcmOptions={},(r=e.fcmOptions.link)&&(n.fcmOptions.link=r),(r=e.fcmOptions.analytics_label)&&(n.fcmOptions.analyticsLabel=r)),i}function Kj(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function $j(e){return Dj.create("missing-app-config-values",{valueName:e})}Kj("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Kj("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Wj{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw $j("App Configuration Object");if(!e.name)throw $j("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw $j(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function zj(e){try{e.swRegistration=await navigator.serviceWorker.register(gj,{scope:mj}),e.swRegistration.update().catch(()=>{})}catch(e){throw Dj.create("failed-service-worker-registration",{browserErrorMessage:e.message})}}async function Gj(e,t){if(!navigator)throw Dj.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw Dj.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=vj)),await async function(e,t){if(t||e.swRegistration||await zj(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw Dj.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),qj(e)}async function Hj(e,t,n){var r=function(e){switch(e){case lj.NOTIFICATION_CLICKED:return"notification_open";case lj.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[_j],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function Qj(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===lj.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Bj(r)):e.onMessageHandler.next(Bj(r))),n=r.data,"object"==typeof(t=n)&&t&&_j in t&&"1"===n[wj]&&await Hj(e,r.messageType,n))}const Yj="@firebase/messaging",Jj=e=>{const t=new Wj(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>Qj(t,e)),t},Xj=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>Gj(t,e)}};function Zj(e){return async function(e){if(!navigator)throw Dj.create("only-available-in-window");return e.swRegistration||await zj(e),jj(e)}(e=$d(e))}function eV(e,t){return function(e,t){if(!navigator)throw Dj.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=$d(e),t)}_f(new Xd("messaging",Jj,"PUBLIC")),_f(new Xd("messaging-internal",Xj,"PRIVATE")),Cf(Yj,"0.9.12"),Cf(Yj,"0.9.12","esm2017");const tV="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",nV="https://fcmregistrations.googleapis.com/v1",rV="FCM_MSG",iV="google.c.a.c_id",sV=3,oV=1;function aV(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=uj=uj||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(c=hj=hj||{}).PUSH_RECEIVED="push-received",c.NOTIFICATION_CLICKED="notification-clicked";const cV="fcm_token_details_db",lV="fcm_token_object_Store";async function uV(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(cV))return null}let l=null;const e=await Yd(cV,5,async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(lV)){const a=r.objectStore(lV);var s,o=await a.index("fcmSenderId").get(c);await a.clear(),o&&(2===t?(s=o).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:aV(s.vapidKey)}}):3===t?(s=o,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:aV(s.auth),p256dh:aV(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:aV(s.vapidKey)}}):4===t&&(o=o,l={token:o.fcmToken,createTime:o.createTime,subscriptionOptions:{auth:aV(o.auth),p256dh:aV(o.p256dh),endpoint:o.endpoint,swScope:o.swScope,vapidKey:aV(o.vapidKey)}}))}});return e.close(),await Jd(cV),await Jd("fcm_vapid_details_db"),await Jd("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const hV="firebase-messaging-database",dV=1,fV="firebase-messaging-store";let pV=null;function gV(){return pV=pV||Yd(hV,dV,(e,t)=>{0===t&&e.createObjectStore(fV)}),pV}async function mV(e){var t=yV(e);const n=await gV();t=await n.transaction(fV).objectStore(fV).get(t);if(t)return t;t=await uV(e.appConfig.senderId);return t?(await vV(e,t),t):void 0}async function vV(e,t){var n=yV(e);const r=await gV(),i=r.transaction(fV,"readwrite");return await i.objectStore(fV).put(t,n),await i.complete,t}function yV({appConfig:e}){return e.appId}const _V=new md("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function wV(e,t){var n={method:"DELETE",headers:await IV(e)};try{const s=await fetch(`${bV(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw _V.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw _V.create("token-unsubscribe-failed",{errorInfo:e})}}function bV({projectId:e}){return`${nV}/projects/${e}/registrations`}async function IV({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function TV({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==tV&&(i.web.applicationPubKey=r),i}async function EV(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,o,a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:aV(t.getKey("auth")),p256dh:aV(t.getKey("p256dh"))},c=await mV(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=a.vapidKey===n.vapidKey,i=a.endpoint===n.endpoint,s=a.auth===n.auth,o=a.p256dh===n.p256dh,r&&i&&s&&o)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await IV(e),r=TV(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${bV(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw _V.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw _V.create("token-update-failed",{errorInfo:r})}if(!i.token)throw _V.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await vV(t.firebaseDependencies,r),n}catch(e){throw await SV(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await wV(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return kV(e.firebaseDependencies,a)}return kV(e.firebaseDependencies,a)}async function SV(e){var t=await mV(e.firebaseDependencies);t&&(await wV(e.firebaseDependencies,t.token),await async function(e){var t=yV(e);const n=await gV(),r=n.transaction(fV,"readwrite");await r.objectStore(fV).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function kV(e,t){var n={token:await async function(e,t){var n=await IV(e),r=TV(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(bV(e.appConfig),r);i=await s.json()}catch(e){throw _V.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw _V.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw _V.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await vV(e,n),n.token}async function CV(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=uj.DISPLAY_NOTIFICATION.toString():r.message_type=uj.DATA_MESSAGE.toString();r.sdk_platform=sV.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=oV.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function AV(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function NV(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await CV(t,n);var r,i,s=await xV();if(s.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=hj.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(s,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[rV]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(s={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},n=s,(e=r).notification&&(n.notification={},(i=e.notification.title)&&(n.notification.title=i),(i=e.notification.body)&&(n.notification.body=i),(i=e.notification.image)&&(n.notification.image=i)),e=s,(n=r).data&&(e.data=n.data),n=s,(r=r).fcmOptions&&(n.fcmOptions={},(i=r.fcmOptions.link)&&(n.fcmOptions.link=i),(i=r.fcmOptions.analytics_label)&&(n.fcmOptions.analyticsLabel=i)),s=s,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(s):t.onBackgroundMessageHandler.next(s))}}async function RV(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[rV];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&iV in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await xV();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=hj.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function xV(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function PV(e){return _V.create("missing-app-config-values",{valueName:e})}AV("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),AV("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class DV{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw PV("App Configuration Object");if(!e.name)throw PV("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw PV(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const OV=e=>{const t=new DV(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(NV(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await mV(t.firebaseDependencies),await SV(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:tV,await EV(t)):await SV(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(RV(e))}),t};function MV(e,t){return function(e,t){if(void 0!==self.document)throw _V.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=$d(e),t)}_f(new Xd("messaging-sw",OV,"PUBLIC"));var LV,FV,UV;class qV{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return Gj(e=$d(e),t)}(this._delegate,e)}async deleteToken(){return Zj(this._delegate)}onMessage(e){return eV(this._delegate,e)}onBackgroundMessage(e){return MV(this._delegate,e)}}const jV=e=>self&&"ServiceWorkerGlobalScope"in self?new qV(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new qV(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),VV={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?dd()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&dd()&&pd()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};zf.INTERNAL.registerComponent(new Xd("messaging-compat",jV,"PUBLIC").setServiceProps(VV)),zf.registerVersion("@firebase/messaging-compat","0.1.12");const BV="firebasestorage.googleapis.com",KV="storageBucket";class $V extends gd{constructor(e,t){super(WV(e),`Firebase Storage: ${t} (${WV(e)})`),this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,$V.prototype)}_codeEquals(e){return WV(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function WV(e){return"storage/"+e}function zV(){return new $V("unknown","An unknown error occurred, please check the error payload for server response.")}function GV(){return new $V("canceled","User canceled the upload/download.")}function HV(){return new $V("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function QV(e){return new $V("invalid-argument",e)}function YV(){return new $V("app-deleted","The Firebase app was deleted.")}function JV(e){return new $V("invalid-root-operation","The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function XV(e,t){return new $V("invalid-format","String does not match format '"+e+"': "+t)}function ZV(e){throw new $V("internal-error","Internal error: "+e)}class eB{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=eB.makeFromUrl(t,e)}catch(e){return new eB(t,"")}if(""===n.path)return n;throw t=t,new $V("invalid-default-bucket","Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var o=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${o}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),o=t===BV?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${o}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new eB(u,e),d.postModify(n);break}}if(null==n)throw t=e,new $V("invalid-url","Invalid URL '"+t+"'.");return n}}class tB{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function nB(e){return"string"==typeof e||e instanceof String}function rB(e){return iB()&&e instanceof Blob}function iB(){return"undefined"!=typeof Blob}function sB(e,t,n,r){if(r<t)throw QV(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw QV(`Invalid value for '${e}'. Expected ${n} or less.`)}function oB(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function aB(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}(c=LV=LV||{})[c.NO_ERROR=0]="NO_ERROR",c[c.NETWORK_ERROR=1]="NETWORK_ERROR",c[c.ABORT=2]="ABORT";class cB{constructor(e,t,n,r,i,s,o,a,c,l,u){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=o,this.errorCallback_=a,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(r,e)=>{if(e)r(!1,new lB(!1,null,!0));else{const i=this.connectionFactory_();this.pendingConnection_=i;const s=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&i.addUploadProgressListener(s),i.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&i.removeUploadProgressListener(s),this.pendingConnection_=null;var e,t=i.getErrorCode()===LV.NO_ERROR,n=i.getStatus();t&&!this.isRetryStatusCode_(n)?(e=-1!==this.successCodes_.indexOf(n),r(!0,new lB(e,i))):(e=i.getErrorCode()===LV.ABORT,r(!1,new lB(!1,null,e)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const a=zV();a.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,a)):r(a)}else{var o;t.canceled?(o=(this.appDelete_?YV:GV)(),r(o)):(o=new $V("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),r(o))}};this.canceled_?t(0,new lB(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,o=!1,a=0;function c(){return 2===a}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(f,c())},e)}function d(){s&&clearTimeout(s)}function f(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||o)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===a?(a=2,0):1e3*(r+Math.random()),h(e)}}let p=!1;function g(e){p||(p=!0,d(),l||(null!==i?(e||(a=2),clearTimeout(i),h(0)):e||(a=1)))}return h(0),s=setTimeout(()=>{g(o=!0)},e),g}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}isRetryStatusCode_(e){var t=500<=e&&e<600,n=-1!==[408,429].indexOf(e),r=-1!==this.additionalRetryCodes_.indexOf(e);return t||n||r}}class lB{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function uB(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(iB())return new Blob(t);throw new $V("unsupported-environment","This browser doesn't seem to support creating Blobs")}const hB={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class dB{constructor(e,t){this.data=e,this.contentType=t||null}}function fB(e,t){switch(e){case hB.RAW:return new dB(pB(t));case hB.BASE64:case hB.BASE64URL:return new dB(gB(e,t));case hB.DATA_URL:return new dB((n=t,(r=new mB(n)).base64?gB(hB.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw XV(hB.DATA_URL,"Malformed data URL.")}return pB(t)}(r.rest)),(n=t,new mB(n).contentType))}var n,r;throw zV()}function pB(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function gB(t,e){switch(t){case hB.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw XV(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case hB.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw XV(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw XV(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let o=0;o<i.length;o++)s[o]=i.charCodeAt(o);return s}class mB{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw XV(hB.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class vB{constructor(e,t){let n=0,r="";rB(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(rB(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new vB(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new vB(n,!0)}static getBlob(...e){if(iB()){var t=e.map(e=>e instanceof vB?e.data_:e);return new vB(uB.apply(null,t))}{const r=e.map(e=>nB(e)?fB(hB.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new vB(i,!0)}}uploadData(){return this.data_}}function yB(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function _B(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function wB(e,t){return t}class bB{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||wB}}let IB=null;function TB(){if(IB)return IB;const e=[];e.push(new bB("bucket")),e.push(new bB("generation")),e.push(new bB("metageneration")),e.push(new bB("name","fullPath",!0));const t=new bB("name");t.xform=function(e,t){return!nB(t=t)||t.length<2?t:_B(t)},e.push(t);const n=new bB("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new bB("timeCreated")),e.push(new bB("updated")),e.push(new bB("md5Hash",null,!0)),e.push(new bB("cacheControl",null,!0)),e.push(new bB("contentDisposition",null,!0)),e.push(new bB("contentEncoding",null,!0)),e.push(new bB("contentLanguage",null,!0)),e.push(new bB("contentType",null,!0)),e.push(new bB("metadata","customMetadata",!0)),IB=e,IB}function EB(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new eB(e,t);return r._makeStorageReference(t)}})}function SB(e,t,n){var r=yB(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const o=n[s];r[o.local]=o.xform(r,t[o.server])}return EB(r,e),r}(e,r,n)}function kB(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}function CB(e,t,n){var r=yB(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n.prefixes)for(const o of n.prefixes){var i=o.replace(/\/$/,""),i=e._makeStorageReference(new eB(t,i));r.prefixes.push(i)}if(n.items)for(const a of n.items){var s=e._makeStorageReference(new eB(t,a.name));r.items.push(s)}return r}(e,t,r)}class AB{constructor(e,t,n,r){this.url=e,this.method=t,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 NB(e){if(!e)throw zV()}function RB(r,i){return function(e,t){var n=SB(r,t,i);return NB(null!==n),n}}function xB(r,i){return function(e,t){var n=CB(r,i,t);return NB(null!==n),n}}function PB(r,i){return function(e,t){var n=SB(r,t,i);return NB(null!==n),function(r,e,i,s){var t=yB(e);if(null===t)return null;if(!nB(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const o=encodeURIComponent,a=n.split(",");return a.map(e=>{var t=r.bucket,n=r.fullPath;return oB("/b/"+o(t)+"/o/"+o(n),i,s)+aB({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function DB(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new $V("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new $V("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new $V("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(e=i.path,new $V("unauthorized","User does not have permission to access '"+e+"'.")):t,n.serverResponse=t.serverResponse,n}}function OB(r){const i=DB(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new $V("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function MB(e,t,n){var r=oB(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new AB(r,"GET",RB(e,n),i);return s.errorHandler=OB(t),s}function LB(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function FB(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const o={"X-Goog-Upload-Protocol":"multipart"};var a=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();o["Content-Type"]="multipart/related; boundary="+a;var c=LB(t,r,i),l="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+kB(c,n)+"\r\n--"+a+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",a="\r\n--"+a+"--";const u=vB.getBlob(l,r,a);if(null===u)throw HV();a={name:c.fullPath},c=oB(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new AB(c,"POST",RB(e,n),s);return h.urlParams=a,h.headers=o,h.body=u.uploadData(),h.errorHandler=DB(t),h}class UB{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function qB(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){NB(!1)}const r=t||["active"];return NB(!!n&&-1!==r.indexOf(n)),n}function jB(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),o=LB(t,r,i),a={name:o.fullPath},c=oB(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":o.contentType,"Content-Type":"application/json; charset=utf-8"},s=kB(o,n),o=e.maxUploadRetryTime;const u=new AB(c,"POST",function(e){qB(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){NB(!1)}return NB(nB(t)),t},o);return u.urlParams=a,u.headers=l,u.body=s,u.errorHandler=DB(t),u}function VB(e,t,n,i){var r=e.maxUploadRetryTime;const s=new AB(n,"POST",function(e){var t=qB(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){NB(!1)}n||NB(!1);var r=Number(n);return NB(!isNaN(r)),new UB(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=DB(t),s}function BB(e,o,t,a,n,c,r,i){const l=new UB(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=a.size()),a.size()!==l.total)throw new $V("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u,s={"X-Goog-Upload-Command":u===s?"upload, finalize":"upload","X-Goog-Upload-Offset":`${l.current}`};const f=a.slice(h,d);if(null===f)throw HV();d=o.maxUploadRetryTime;const p=new AB(t,"POST",function(e,t){var n=qB(e,["active","final"]),r=l.current+u,i=a.size();let s;return s="final"===n?RB(o,c)(e,t):null,new UB(r,i,"final"===n,s)},d);return p.headers=s,p.body=f.uploadData(),p.progressCallback=i||null,p.errorHandler=DB(e),p}const KB={STATE_CHANGED:"state_changed"},$B={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function WB(e){switch(e){case"running":case"pausing":case"canceling":return $B.RUNNING;case"paused":return $B.PAUSED;case"success":return $B.SUCCESS;case"canceled":return $B.CANCELED;default:return $B.ERROR}}class zB{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function GB(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class HB extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=LV.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=LV.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=LV.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw ZV("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw ZV("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw ZV("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw ZV("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw ZV("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function QB(){return new HB}class YB{constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=TB(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{this._request=void 0,this._chunkMultiplier=1,e._codeEquals("canceled")?(this._needToFetchStatus=!0,this.completeTransitions_()):(this._error=e,this._transition("error"))},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals("canceled")?this.completeTransitions_():(this._error=e,this._transition("error"))},this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){const t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this._continueUpload():this._oneShotUpload())}_resolveToken(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=jB(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,QB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=VB(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,QB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const i=262144*this._chunkMultiplier,s=new UB(this._transferred,this._blob.size()),o=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=BB(this._ref._location,this._ref.storage,o,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const r=this._ref.storage._makeRequest(n,QB,e,t);this._request=r,r.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){262144*this._chunkMultiplier<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var n=MB(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,QB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=FB(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,QB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request&&this._request.cancel();break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=GV(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=WB(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new zB(t||void 0,n||void 0,r||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(WB(this._state)){case $B.SUCCESS:GB(this._resolve.bind(null,this.snapshot))();break;case $B.CANCELED:case $B.ERROR:const t=this._reject;GB(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(WB(this._state)){case $B.RUNNING:case $B.PAUSED:e.next&&GB(e.next.bind(e,this.snapshot))();break;case $B.SUCCESS:e.complete&&GB(e.complete.bind(e))();break;case $B.CANCELED:case $B.ERROR:default:e.error&&GB(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class JB{constructor(e,t){this._service=e,t instanceof eB?this._location=t:this._location=eB.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new JB(e,t)}get root(){var e=new eB(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return _B(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new eB(this._location.bucket,e);return new JB(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw JV(e)}}function XB(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await ZB(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function ZB(e,t){null!=t&&"number"==typeof t.maxResults&&sB("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var o=oB(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime;const c=new AB(o,"GET",xB(e,t.bucket),a);return c.urlParams=s,c.errorHandler=DB(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,QB)}function e2(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=oB(t.fullServerUrl(),e.host,e._protocol),s=kB(n,r),o=e.maxOperationRetryTime;const a=new AB(i,"PATCH",RB(e,r),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=OB(t),a}(e.storage,e._location,t,TB());return e.storage.makeRequestWithTokens(n,QB)}function t2(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=oB(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new AB(r,"GET",PB(e,n),i);return s.errorHandler=OB(t),s}(e.storage,e._location,TB());return e.storage.makeRequestWithTokens(t,QB).then(e=>{if(null===e)throw new $V("no-download-url","The given file does not have any download URLs.");return e})}function n2(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=oB(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new AB(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=OB(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,QB)}function r2(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new eB(e._location.bucket,r);return new JB(e.storage,r)}function i2(e,t){if(e instanceof a2){var n=e;if(null==n._bucket)throw new $V("no-default-bucket","No default bucket found. Did you set the '"+KV+"' property when initializing the app?");n=new JB(n,n._bucket);return null!=t?i2(n,t):n}return void 0!==t?r2(e,t):e}function s2(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof a2)return n=e,r=t,new JB(n,r);throw QV("To use ref(service, url), the first argument must be a Storage instance.")}return i2(e,t);var n,r}function o2(e,t){var n=null==t?void 0:t[KV];return null==n?null:eB.makeFromBucketSpec(n,e)}class a2{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=BV,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?eB.makeFromBucketSpec(r,this._host):o2(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=eB.makeFromBucketSpec(this._url,e):this._bucket=o2(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){sB("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){sB("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new JB(this,e)}_makeRequest(e,t,n,r){if(this._deleted)return new tB(YV());{const l=(i=e,s=this._appId,o=n,e=r,n=t,r=this._firebaseVersion,a=aB(i.urlParams),c=i.url+a,a=Object.assign({},i.headers),t=a,(s=s)&&(t["X-Firebase-GMPID"]=s),s=a,null!==(o=o)&&0<o.length&&(s.Authorization="Firebase "+o),r=r,a["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=a,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new cB(c,i.method,a,i.body,i.successCodes,i.additionalRetryCodes,i.handler,i.errorHandler,i.timeout,i.progressCallback,n));return this._requests.add(l),l.getPromise().then(()=>this._requests.delete(l),()=>this._requests.delete(l)),l}var i,s,o,a,c}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const c2="@firebase/storage";function l2(e,t,n){return e=$d(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new YB(e,new vB(t),n)}function u2(e){return function(e){e._throwIfRoot("getMetadata");var t=MB(e.storage,e._location,TB());return e.storage.makeRequestWithTokens(t,QB)}(e=$d(e))}function h2(e,t){return s2(e=$d(e),t)}function d2(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:id(i,e.app.options.projectId))}(e,t,n,r)}function f2(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new a2(n,r,i,t,Tf)}_f(new Xd("storage",f2,"PUBLIC").setMultipleInstances(!0)),Cf(c2,"0.9.5",""),Cf(c2,"0.9.5","esm2017");class p2{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class g2{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new p2(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new p2(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new p2(e,this,this._ref)):{next:t.next?e=>t.next(new p2(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class m2{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new v2(e,this._service))}get items(){return this._delegate.items.map(e=>new v2(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class v2{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=r2(this._delegate,e);return new v2(t,this.storage)}get root(){return new v2(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new v2(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new g2(l2(this._delegate,e,t),this)}putString(e,t=hB.RAW,n){this._throwIfRoot("putString");var r=fB(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new g2(new YB(this._delegate,new vB(r.data,!0),i),this)}listAll(){return XB($d(this._delegate)).then(e=>new m2(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,ZB(t=$d(t),e).then(e=>new m2(e,this.storage));var t}getMetadata(){return u2(this._delegate)}updateMetadata(e){return e2($d(this._delegate),e)}getDownloadURL(){return t2($d(this._delegate))}delete(){return this._throwIfRoot("delete"),n2($d(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw JV(e)}}class y2{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(_2(e))throw QV("ref() expected a child path but got a URL, use refFromURL instead.");return new v2(h2(this._delegate,e),this)}refFromURL(e){if(!_2(e))throw QV("refFromURL() expected a full URL but got a child path, use ref() instead.");try{eB.makeFromUrl(e,this._delegate.host)}catch(e){throw QV("refFromUrl() expected a valid full URL but got an invalid one.")}return new v2(h2(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){d2(this._delegate,e,t,n)}}function _2(e){return/^[A-Za-z]+:\/\//.test(e)}function w2(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new y2(n,r)}FV=zf,UV={TaskState:$B,TaskEvent:KB,StringFormat:hB,Storage:y2,Reference:v2},FV.INTERNAL.registerComponent(new Xd("storage-compat",w2,"PUBLIC").setServiceProps(UV).setMultipleInstances(!0)),FV.registerVersion("@firebase/storage-compat","0.1.13");const b2="@firebase/performance",I2="0.5.8",T2="FB-PERF-TRACE-MEASURE",E2="@firebase/performance/config",S2="@firebase/performance/configexpire";var k2,C2,A2,N2="Performance";const R2=new md("performance",N2,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),x2=new cf(N2);x2.logLevel=$h.INFO;let P2,D2;class O2{constructor(e){if(!(this.window=e))throw R2.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&pd()?!!dd()||(x2.info("IndexedDB is not supported by current browswer"),!1):(x2.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===P2&&(P2=new O2(D2)),P2}}let M2;function L2(e,t){var n=e.length-t.length;if(n<0||1<n)throw R2.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let F2;class U2{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=L2("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=L2("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===F2&&(F2=new U2),F2}}(c=k2=k2||{})[c.UNKNOWN=0]="UNKNOWN",c[c.VISIBLE=1]="VISIBLE",c[c.HIDDEN=2]="HIDDEN";const q2=["firebase_","google_","ga_"],j2=new RegExp("^[a-zA-Z]\\w*$");function V2(){switch(O2.getInstance().document.visibilityState){case"visible":return k2.VISIBLE;case"hidden":return k2.HIDDEN;default:return k2.UNKNOWN}}function B2(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw R2.create("no app id");return t}const K2="0.0.1",$2={loggingEnabled:!0},W2="FIREBASE_INSTALLATIONS_AUTH";function z2(e,t){var r,i,n=function(){const e=O2.getInstance().localStorage;if(e){var t=e.getItem(S2);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(E2);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(H2(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw R2.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw R2.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${W2} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:B2(r.app),app_version:I2,sdk_version:K2})});return fetch(n).then(e=>{if(e.ok)return e.json();throw R2.create("RC response not ok")})}).catch(()=>{x2.info(G2)}).then(H2).then(e=>function(e){const t=O2.getInstance().localStorage;e&&t&&(t.setItem(E2,JSON.stringify(e)),t.setItem(S2,String(Date.now()+60*U2.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const G2="Could not fetch config, will use default configs";function H2(e){if(!e)return e;const t=U2.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=$2.loggingEnabled,n.fpr_log_source&&(t.logSource=Number(n.fpr_log_source)),n.fpr_log_endpoint_url&&(t.logEndPointUrl=n.fpr_log_endpoint_url),n.fpr_log_transport_key&&(t.transportKey=n.fpr_log_transport_key),void 0!==n.fpr_vc_network_request_sampling_rate&&(t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate)),void 0!==n.fpr_vc_trace_sampling_rate&&(t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate)),t.logTraceAfterSampling=Q2(t.tracesSamplingRate),t.logNetworkAfterSampling=Q2(t.networkRequestsSamplingRate),e}function Q2(e){return Math.random()<=e}let Y2=1,J2;function X2(e){var t;return Y2=2,J2=J2||(t=e,function(){const n=O2.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{M2=e}),t}(t.installations)).then(e=>z2(t,e)).then(()=>Z2(),()=>Z2())),J2}function Z2(){Y2=3}const eK=1e4,tK=3,nK=1e3;let rK=tK,iK=[],sK=!1;function oK(e){setTimeout(()=>{if(0!==rK)return iK.length?void function(){const e=iK.splice(0,nK),t=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:U2.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=U2.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||x2.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=eK;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(iK=[...r,...iK],x2.info("Retry transport request later.")),rK=tK,oK(n)})}(n,e).catch(()=>{iK=[...e,...iK],rK--,x2.info(`Tries left: ${rK}.`),oK(eK)})}():oK(eK)},e)}function aK(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw R2.create("invalid cc log");iK=[...iK,e]}({message:t(...e),eventTime:Date.now()})}}let cK;function lK(e,t){cK=cK||aK(dK),cK(e,t)}function uK(e){var t=U2.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&O2.getInstance().requiredApisAvailable()&&(e.isAuto&&V2()!==k2.VISIBLE||(3===Y2?hK(e):X2(e.performanceController).then(()=>hK(e),()=>hK(e))))}function hK(e){var t;!M2||(t=U2.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>lK(e,1),0)}function dK(e,t){return 0===t?(n={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},n={application_info:fK(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:fK(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function fK(e){return{google_app_id:B2(e),app_instance_id:M2,web_app_info:{sdk_version:I2,page_url:O2.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=O2.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:V2(),effective_connection_type:function(){var e=O2.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}()},application_process_state:0};var t}const pK=["_fp","_fcp","_fid"];class gK{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=O2.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`${T2}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw R2.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw R2.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),uK(this)}record(e,t,n){if(e<=0)throw R2.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw R2.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));uK(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<pK.indexOf(r))&&r.startsWith("_"))throw R2.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&x2.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!q2.some(e=>n.startsWith(e))&&!!n.match(j2)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw R2.create("invalid attribute name",{attributeName:e});if(!s)throw R2.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,n,r){var i=O2.getInstance().getUrl();if(i){const s=new gK(e,"_wt_"+i,!0);i=Math.floor(1e3*O2.getInstance().getTimeOrigin());s.setStartTime(i),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),uK(s)}}static createUserTimingTrace(e,t){uK(new gK(e,t,!1,t))}}function mK(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=O2.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=U2.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>lK(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const vK=5e3;function yK(e){M2&&(setTimeout(()=>function(n){const e=O2.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{gK.createOobTrace(n,r,i),t=void 0},vK);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),gK.createOobTrace(n,r,i,e))})}else gK.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=O2.getInstance(),n=e.getEntriesByType("resource");for(const r of n)mK(t,r);e.setupObserver("resource",e=>mK(t,e))}(e),0),setTimeout(()=>function(t){const e=O2.getInstance(),n=e.getEntriesByType("measure");for(const r of n)_K(t,r);e.setupObserver("measure",e=>_K(t,e))}(e),0))}function _K(e,t){const n=t.name;n.substring(0,T2.length)!==T2&&gK.createUserTimingTrace(e,n)}class wK{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),O2.getInstance().requiredApisAvailable()?fd().then(e=>{e&&(sK||(oK(5500),sK=!0),X2(this).then(()=>yK(this),()=>yK(this)),this.initialized=!0)}).catch(e=>{x2.info(`Environment doesn't support IndexedDB: ${e}`)}):x2.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){U2.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return U2.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){U2.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return U2.getInstance().dataCollectionEnabled}}const bK="[DEFAULT]";const IK=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==bK)throw R2.create("FB not default");if("undefined"==typeof window)throw R2.create("no window");e=window,D2=e;const i=new wK(n,r);return i._init(t),i};_f(new Xd("performance",IK,"PUBLIC")),Cf(b2,"0.5.8"),Cf(b2,"0.5.8","esm2017");class TK{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=$d(t),new gK(t,e);var t}}function EK(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new TK(t,n)}(C2=zf).INTERNAL.registerComponent(new Xd("performance-compat",EK,"PUBLIC")),C2.registerVersion("@firebase/performance-compat","0.1.8");const SK="@firebase/remote-config";class kK{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const CK=new md("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser"});const AK=["1","true","t","yes","y","on"];class NK{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=AK.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function RK(e){const t=$d(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function xK(e){const t=$d(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function PK(t){const n=$d(t),e=new kK;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof gd&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function DK(n){const e=$d(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=OK(n,t),e),{});var t,r}function OK(e,t){const n=$d(e);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new NK("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new NK("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new NK("static"))}class MK{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class LK{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let o;try{await Promise.race([i,r]),o=await i}catch(e){let t="fetch-client-network";throw"AbortError"===e.name&&(t="fetch-timeout"),CK.create(t,{originalErrorMessage:e.message})}let a=o.status;i=o.headers.get("ETag")||void 0;let c,l;if(200===o.status){let e;try{e=await o.json()}catch(e){throw CK.create("fetch-client-parse",{originalErrorMessage:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?a=500:"NO_CHANGE"===l?a=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==a&&200!==a)throw CK.create("fetch-status",{httpStatus:a});return{status:a,eTag:i,config:c}}}class FK{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(CK.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof gd&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+Kd(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class UK{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function qK(e,t){var n=e.target.error||void 0;return CK.create(t,{originalErrorMessage:n&&n.message})}const jK="app_namespace_store";class VK{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(qK(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(jK,{keyPath:"compositeKey"})}}catch(e){n(CK.create("storage-open",{originalErrorMessage:e}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(o){const a=await this.openDbPromise;return new Promise((n,t)=>{const e=a.transaction([jK],"readonly"),r=e.objectStore(jK);var i=this.createCompositeKey(o);try{const s=r.get(i);s.onerror=e=>{t(qK(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(CK.create("storage-get",{originalErrorMessage:e&&e.message}))}})}async set(o,a){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([jK],"readwrite"),r=n.objectStore(jK);var i=this.createCompositeKey(o);try{const s=r.put({compositeKey:i,value:a});s.onerror=e=>{t(qK(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(CK.create("storage-set",{originalErrorMessage:e&&e.message}))}})}async delete(o){const a=await this.openDbPromise;return new Promise((e,t)=>{const n=a.transaction([jK],"readwrite"),r=n.objectStore(jK);var i=this.createCompositeKey(o);try{const s=r.delete(i);s.onerror=e=>{t(qK(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(CK.create("storage-delete",{originalErrorMessage:e&&e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class BK{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}}async function KK(){if(!dd())return!1;try{return await fd()}catch(e){return!1}}_f(new Xd("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw CK.create("registration-window");if(!dd())throw CK.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:o}=n.options;if(!i)throw CK.create("registration-project-id");if(!s)throw CK.create("registration-api-key");if(!o)throw CK.create("registration-app-id");t=t||"firebase";const a=new VK(o,n.name,t),c=new BK(a),l=new cf(SK);l.logLevel=$h.ERROR;o=new LK(r,Tf,t,i,s,o),o=new FK(o,a),o=new MK(o,a,c,l),o=new UK(n,o,c,a,l);return xK(o),o},"PUBLIC").setMultipleInstances(!0)),Cf(SK,"0.3.7"),Cf(SK,"0.3.7","esm2017");class $K{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return RK(this._delegate)}ensureInitialized(){return xK(this._delegate)}fetch(){return PK(this._delegate)}fetchAndActivate(){return async function(e){return await PK(e=$d(e)),RK(e)}(this._delegate)}getAll(){return DK(this._delegate)}getBoolean(e){return OK($d(this._delegate),e).asBoolean()}getNumber(e){return OK($d(this._delegate),e).asNumber()}getString(e){return OK($d(this._delegate),e).asString()}getValue(e){return OK(this._delegate,e)}setLogLevel(e){!function(e,t){const n=$d(e);switch(t){case"debug":n._logger.logLevel=$h.DEBUG;break;case"silent":n._logger.logLevel=$h.SILENT;break;default:n._logger.logLevel=$h.ERROR}}(this._delegate,e)}}function WK(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new $K(n,r)}return(A2=zf).INTERNAL.registerComponent(new Xd("remoteConfig-compat",WK,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:KK})),A2.registerVersion("@firebase/remote-config-compat","0.1.8"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),zf.registerVersion("firebase","9.7.0","compat-cdn"),zf});
10
10
  //# sourceMappingURL=firebase-compat.js.map