vg-coder-cli 2.0.9 → 2.0.11

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 (73) hide show
  1. package/DEVELOPMENT.md +95 -0
  2. package/README.md +19 -0
  3. package/SYSTEM_PROMPT.md +157 -0
  4. package/coverage/base.css +224 -0
  5. package/coverage/block-navigation.js +87 -0
  6. package/coverage/favicon.png +0 -0
  7. package/coverage/index.html +206 -0
  8. package/coverage/lcov-report/base.css +224 -0
  9. package/coverage/lcov-report/block-navigation.js +87 -0
  10. package/coverage/lcov-report/favicon.png +0 -0
  11. package/coverage/lcov-report/index.html +206 -0
  12. package/coverage/lcov-report/prettify.css +1 -0
  13. package/coverage/lcov-report/prettify.js +2 -0
  14. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  15. package/coverage/lcov-report/sorter.js +210 -0
  16. package/coverage/lcov-report/src/detectors/index.html +116 -0
  17. package/coverage/lcov-report/src/detectors/project-detector.js.html +1084 -0
  18. package/coverage/lcov-report/src/exporter/html-exporter.js.html +2839 -0
  19. package/coverage/lcov-report/src/exporter/index.html +116 -0
  20. package/coverage/lcov-report/src/ignore/ignore-manager.js.html +979 -0
  21. package/coverage/lcov-report/src/ignore/index.html +116 -0
  22. package/coverage/lcov-report/src/index.html +116 -0
  23. package/coverage/lcov-report/src/index.js.html +928 -0
  24. package/coverage/lcov-report/src/scanner/file-scanner.js.html +1903 -0
  25. package/coverage/lcov-report/src/scanner/index.html +116 -0
  26. package/coverage/lcov-report/src/tokenizer/index.html +116 -0
  27. package/coverage/lcov-report/src/tokenizer/token-manager.js.html +1252 -0
  28. package/coverage/lcov-report/src/utils/helpers.js.html +469 -0
  29. package/coverage/lcov-report/src/utils/index.html +116 -0
  30. package/coverage/lcov.info +1396 -0
  31. package/coverage/prettify.css +1 -0
  32. package/coverage/prettify.js +2 -0
  33. package/coverage/sort-arrow-sprite.png +0 -0
  34. package/coverage/sorter.js +210 -0
  35. package/coverage/src/detectors/index.html +116 -0
  36. package/coverage/src/detectors/project-detector.js.html +1084 -0
  37. package/coverage/src/exporter/html-exporter.js.html +2839 -0
  38. package/coverage/src/exporter/index.html +116 -0
  39. package/coverage/src/ignore/ignore-manager.js.html +979 -0
  40. package/coverage/src/ignore/index.html +116 -0
  41. package/coverage/src/index.html +116 -0
  42. package/coverage/src/index.js.html +928 -0
  43. package/coverage/src/scanner/file-scanner.js.html +1903 -0
  44. package/coverage/src/scanner/index.html +116 -0
  45. package/coverage/src/tokenizer/index.html +116 -0
  46. package/coverage/src/tokenizer/token-manager.js.html +1252 -0
  47. package/coverage/src/utils/helpers.js.html +469 -0
  48. package/coverage/src/utils/index.html +116 -0
  49. package/jest.config.js +16 -0
  50. package/package.json +5 -3
  51. package/scripts/build.js +40 -0
  52. package/src/server/api-server.js +15 -0
  53. package/src/server/views/css/iframe.css +84 -0
  54. package/src/server/views/css/structure.css +63 -37
  55. package/src/server/views/dashboard.css +127 -310
  56. package/src/server/views/dashboard.html +165 -119
  57. package/src/server/views/js/features/iframe-manager.js +56 -0
  58. package/src/server/views/js/main.js +64 -0
  59. package/src/server/views/vg-coder/assets/icon128.png +0 -0
  60. package/src/server/views/vg-coder/assets/icon16.png +0 -0
  61. package/src/server/views/vg-coder/assets/icon48.png +0 -0
  62. package/src/server/views/vg-coder/background.js +2 -0
  63. package/src/server/views/vg-coder/background.js.LICENSE.txt +118 -0
  64. package/src/server/views/vg-coder/controller.js +1 -0
  65. package/src/server/views/vg-coder/manifest.json +58 -0
  66. package/src/server/views/vg-coder/options.css +164 -0
  67. package/src/server/views/vg-coder/options.html +48 -0
  68. package/src/server/views/vg-coder/options.js +1 -0
  69. package/src/server/views/vg-coder/rules.json +23 -0
  70. package/vg-coder-cli-2.0.11.tgz +0 -0
  71. package/vg-coder.zip +0 -0
  72. package/vg-coder-cli-2.0.8.tgz +0 -0
  73. package/vg-coder-cli-2.0.9.tgz +0 -0
@@ -0,0 +1,2 @@
1
+ /*! For license information please see background.js.LICENSE.txt */
2
+ (()=>{var e={2:(e,t,n)=>{var r=n(2199),i=n(4664),s=n(5950);e.exports=function(e){return r(e,s,i)}},79:(e,t,n)=>{var r=n(3702),i=n(80),s=n(4739),o=n(8655),a=n(1175);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=i,c.prototype.get=s,c.prototype.has=o,c.prototype.set=a,e.exports=c},80:(e,t,n)=>{var r=n(6025),i=Array.prototype.splice;e.exports=function(e){var t=this.__data__,n=r(t,e);return!(n<0||(n==t.length-1?t.pop():i.call(t,n,1),--this.size,0))}},181:e=>{e.exports=function(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}},289:(e,t,n)=>{var r=n(2651);e.exports=function(e){return r(this,e).get(e)}},294:e=>{e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}},346:e=>{e.exports=function(e){return null!=e&&"object"==typeof e}},361:e=>{var t=/^(?:0|[1-9]\d*)$/;e.exports=function(e,n){var r=typeof e;return!!(n=null==n?9007199254740991:n)&&("number"==r||"symbol"!=r&&t.test(e))&&e>-1&&e%1==0&&e<n}},392:e=>{e.exports=function(e,t){return null==e?void 0:e[t]}},659:(e,t,n)=>{var r=n(1873),i=Object.prototype,s=i.hasOwnProperty,o=i.toString,a=r?r.toStringTag:void 0;e.exports=function(e){var t=s.call(e,a),n=e[a];try{e[a]=void 0;var r=!0}catch(e){}var i=o.call(e);return r&&(t?e[a]=n:delete e[a]),i}},695:(e,t,n)=>{var r=n(8096),i=n(2428),s=n(6449),o=n(3656),a=n(361),c=n(7167),u=Object.prototype.hasOwnProperty;e.exports=function(e,t){var n=s(e),l=!n&&i(e),h=!n&&!l&&o(e),d=!n&&!l&&!h&&c(e),f=n||l||h||d,p=f?r(e.length,String):[],g=p.length;for(var m in e)!t&&!u.call(e,m)||f&&("length"==m||h&&("offset"==m||"parent"==m)||d&&("buffer"==m||"byteLength"==m||"byteOffset"==m)||a(m,g))||p.push(m);return p}},938:e=>{e.exports=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}},945:(e,t,n)=>{var r=n(79),i=n(8223),s=n(3661);e.exports=function(e,t){var n=this.__data__;if(n instanceof r){var o=n.__data__;if(!i||o.length<199)return o.push([e,t]),this.size=++n.size,this;n=this.__data__=new s(o)}return n.set(e,t),this.size=n.size,this}},1042:(e,t,n)=>{var r=n(6110)(Object,"create");e.exports=r},1175:(e,t,n)=>{var r=n(6025);e.exports=function(e,t){var n=this.__data__,i=r(n,e);return i<0?(++this.size,n.push([e,t])):n[i][1]=t,this}},1420:(e,t,n)=>{var r=n(79);e.exports=function(){this.__data__=new r,this.size=0}},1549:(e,t,n)=>{var r=n(2032),i=n(3862),s=n(6721),o=n(2749),a=n(5749);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=i,c.prototype.get=s,c.prototype.has=o,c.prototype.set=a,e.exports=c},1791:(e,t,n)=>{var r=n(6547),i=n(3360);e.exports=function(e,t,n,s){var o=!n;n||(n={});for(var a=-1,c=t.length;++a<c;){var u=t[a],l=s?s(n[u],e[u],u,n,e):void 0;void 0===l&&(l=e[u]),o?i(n,u,l):r(n,u,l)}return n}},1873:(e,t,n)=>{var r=n(9325).Symbol;e.exports=r},1882:(e,t,n)=>{var r=n(2552),i=n(3805);e.exports=function(e){if(!i(e))return!1;var t=r(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}},1961:(e,t,n)=>{var r=n(9653);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}},2032:(e,t,n)=>{var r=n(1042);e.exports=function(){this.__data__=r?r(null):{},this.size=0}},2199:(e,t,n)=>{var r=n(4528),i=n(6449);e.exports=function(e,t,n){var s=t(e);return i(e)?s:r(s,n(e))}},2271:(e,t,n)=>{var r=n(1791),i=n(4664);e.exports=function(e,t){return r(e,i(e),t)}},2428:(e,t,n)=>{var r=n(7534),i=n(346),s=Object.prototype,o=s.hasOwnProperty,a=s.propertyIsEnumerable,c=r(function(){return arguments}())?r:function(e){return i(e)&&o.call(e,"callee")&&!a.call(e,"callee")};e.exports=c},2552:(e,t,n)=>{var r=n(1873),i=n(659),s=n(9350),o=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":o&&o in Object(e)?i(e):s(e)}},2651:(e,t,n)=>{var r=n(4218);e.exports=function(e,t){var n=e.__data__;return r(t)?n["string"==typeof t?"string":"hash"]:n.map}},2749:(e,t,n)=>{var r=n(1042),i=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return r?void 0!==t[e]:i.call(t,e)}},2804:(e,t,n)=>{var r=n(6110)(n(9325),"Promise");e.exports=r},2903:(e,t,n)=>{var r=n(3805),i=n(5527),s=n(181),o=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return s(e);var t=i(e),n=[];for(var a in e)("constructor"!=a||!t&&o.call(e,a))&&n.push(a);return n}},2949:(e,t,n)=>{var r=n(2651);e.exports=function(e,t){var n=r(this,e),i=n.size;return n.set(e,t),this.size+=n.size==i?0:1,this}},3007:e=>{e.exports=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}},3040:(e,t,n)=>{var r=n(1549),i=n(79),s=n(8223);e.exports=function(){this.size=0,this.__data__={hash:new r,map:new(s||i),string:new r}}},3201:e=>{var t=/\w*$/;e.exports=function(e){var n=new e.constructor(e.source,t.exec(e));return n.lastIndex=e.lastIndex,n}},3243:(e,t,n)=>{var r=n(6110),i=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=i},3290:(e,t,n)=>{e=n.nmd(e);var r=n(9325),i=t&&!t.nodeType&&t,s=i&&e&&!e.nodeType&&e,o=s&&s.exports===i?r.Buffer:void 0,a=o?o.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var n=e.length,r=a?a(n):new e.constructor(n);return e.copy(r),r}},3345:e=>{e.exports=function(){return[]}},3349:(e,t,n)=>{var r=n(2199),i=n(6375),s=n(7241);e.exports=function(e){return r(e,s,i)}},3360:(e,t,n)=>{var r=n(3243);e.exports=function(e,t,n){"__proto__"==t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}},3605:e=>{e.exports=function(e){return this.__data__.get(e)}},3650:(e,t,n)=>{var r=n(4335)(Object.keys,Object);e.exports=r},3656:(e,t,n)=>{e=n.nmd(e);var r=n(9325),i=n(9935),s=t&&!t.nodeType&&t,o=s&&e&&!e.nodeType&&e,a=o&&o.exports===s?r.Buffer:void 0,c=(a?a.isBuffer:void 0)||i;e.exports=c},3661:(e,t,n)=>{var r=n(3040),i=n(7670),s=n(289),o=n(4509),a=n(2949);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=i,c.prototype.get=s,c.prototype.has=o,c.prototype.set=a,e.exports=c},3702:e=>{e.exports=function(){this.__data__=[],this.size=0}},3729:e=>{e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&!1!==t(e[n],n,e););return e}},3736:(e,t,n)=>{var r=n(1873),i=r?r.prototype:void 0,s=i?i.valueOf:void 0;e.exports=function(e){return s?Object(s.call(e)):{}}},3805:e=>{e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},3838:(e,t,n)=>{var r=n(1791),i=n(7241);e.exports=function(e,t){return e&&r(t,i(t),e)}},3862:e=>{e.exports=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}},4218:e=>{e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},4335:e=>{e.exports=function(e,t){return function(n){return e(t(n))}}},4509:(e,t,n)=>{var r=n(2651);e.exports=function(e){return r(this,e).has(e)}},4528:e=>{e.exports=function(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}},4664:(e,t,n)=>{var r=n(9770),i=n(3345),s=Object.prototype.propertyIsEnumerable,o=Object.getOwnPropertySymbols,a=o?function(e){return null==e?[]:(e=Object(e),r(o(e),function(t){return s.call(e,t)}))}:i;e.exports=a},4733:(e,t,n)=>{var r=n(1791),i=n(5950);e.exports=function(e,t){return e&&r(t,i(t),e)}},4739:(e,t,n)=>{var r=n(6025);e.exports=function(e){var t=this.__data__,n=r(t,e);return n<0?void 0:t[n][1]}},4840:(e,t,n)=>{var r="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;e.exports=r},4894:(e,t,n)=>{var r=n(1882),i=n(294);e.exports=function(e){return null!=e&&i(e.length)&&!r(e)}},4901:(e,t,n)=>{var r=n(2552),i=n(294),s=n(346),o={};o["[object Float32Array]"]=o["[object Float64Array]"]=o["[object Int8Array]"]=o["[object Int16Array]"]=o["[object Int32Array]"]=o["[object Uint8Array]"]=o["[object Uint8ClampedArray]"]=o["[object Uint16Array]"]=o["[object Uint32Array]"]=!0,o["[object Arguments]"]=o["[object Array]"]=o["[object ArrayBuffer]"]=o["[object Boolean]"]=o["[object DataView]"]=o["[object Date]"]=o["[object Error]"]=o["[object Function]"]=o["[object Map]"]=o["[object Number]"]=o["[object Object]"]=o["[object RegExp]"]=o["[object Set]"]=o["[object String]"]=o["[object WeakMap]"]=!1,e.exports=function(e){return s(e)&&i(e.length)&&!!o[r(e)]}},5083:(e,t,n)=>{var r=n(1882),i=n(7296),s=n(3805),o=n(7473),a=/^\[object .+?Constructor\]$/,c=Function.prototype,u=Object.prototype,l=c.toString,h=u.hasOwnProperty,d=RegExp("^"+l.call(h).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!s(e)||i(e))&&(r(e)?d:a).test(o(e))}},5288:e=>{e.exports=function(e,t){return e===t||e!=e&&t!=t}},5481:(e,t,n)=>{var r=n(9325)["__core-js_shared__"];e.exports=r},5527:e=>{var t=Object.prototype;e.exports=function(e){var n=e&&e.constructor;return e===("function"==typeof n&&n.prototype||t)}},5529:(e,t,n)=>{var r=n(9344),i=n(8879),s=n(5527);e.exports=function(e){return"function"!=typeof e.constructor||s(e)?{}:r(i(e))}},5580:(e,t,n)=>{var r=n(6110)(n(9325),"DataView");e.exports=r},5749:(e,t,n)=>{var r=n(1042);e.exports=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=r&&void 0===t?"__lodash_hash_undefined__":t,this}},5861:(e,t,n)=>{var r=n(5580),i=n(8223),s=n(2804),o=n(6545),a=n(8303),c=n(2552),u=n(7473),l="[object Map]",h="[object Promise]",d="[object Set]",f="[object WeakMap]",p="[object DataView]",g=u(r),m=u(i),y=u(s),_=u(o),v=u(a),w=c;(r&&w(new r(new ArrayBuffer(1)))!=p||i&&w(new i)!=l||s&&w(s.resolve())!=h||o&&w(new o)!=d||a&&w(new a)!=f)&&(w=function(e){var t=c(e),n="[object Object]"==t?e.constructor:void 0,r=n?u(n):"";if(r)switch(r){case g:return p;case m:return l;case y:return h;case _:return d;case v:return f}return t}),e.exports=w},5950:(e,t,n)=>{var r=n(695),i=n(8984),s=n(4894);e.exports=function(e){return s(e)?r(e):i(e)}},6009:(e,t,n)=>{e=n.nmd(e);var r=n(4840),i=t&&!t.nodeType&&t,s=i&&e&&!e.nodeType&&e,o=s&&s.exports===i&&r.process,a=function(){try{return s&&s.require&&s.require("util").types||o&&o.binding&&o.binding("util")}catch(e){}}();e.exports=a},6025:(e,t,n)=>{var r=n(5288);e.exports=function(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}},6038:(e,t,n)=>{var r=n(5861),i=n(346);e.exports=function(e){return i(e)&&"[object Set]"==r(e)}},6110:(e,t,n)=>{var r=n(5083),i=n(392);e.exports=function(e,t){var n=i(e,t);return r(n)?n:void 0}},6169:(e,t,n)=>{var r=n(9653);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}},6189:e=>{var t=Object.prototype.hasOwnProperty;e.exports=function(e){var n=e.length,r=new e.constructor(n);return n&&"string"==typeof e[0]&&t.call(e,"index")&&(r.index=e.index,r.input=e.input),r}},6375:(e,t,n)=>{var r=n(4528),i=n(8879),s=n(4664),o=n(3345),a=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)r(t,s(e)),e=i(e);return t}:o;e.exports=a},6449:e=>{var t=Array.isArray;e.exports=t},6545:(e,t,n)=>{var r=n(6110)(n(9325),"Set");e.exports=r},6547:(e,t,n)=>{var r=n(3360),i=n(5288),s=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var o=e[t];s.call(e,t)&&i(o,n)&&(void 0!==n||t in e)||r(e,t,n)}},6721:(e,t,n)=>{var r=n(1042),i=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;if(r){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return i.call(t,e)?t[e]:void 0}},7167:(e,t,n)=>{var r=n(4901),i=n(7301),s=n(6009),o=s&&s.isTypedArray,a=o?i(o):r;e.exports=a},7199:(e,t,n)=>{var r=n(9653),i=n(6169),s=n(3201),o=n(3736),a=n(1961);e.exports=function(e,t,n){var c=e.constructor;switch(t){case"[object ArrayBuffer]":return r(e);case"[object Boolean]":case"[object Date]":return new c(+e);case"[object DataView]":return i(e,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return a(e,n);case"[object Map]":case"[object Set]":return new c;case"[object Number]":case"[object String]":return new c(e);case"[object RegExp]":return s(e);case"[object Symbol]":return o(e)}}},7217:(e,t,n)=>{var r=n(79),i=n(1420),s=n(938),o=n(3605),a=n(9817),c=n(945);function u(e){var t=this.__data__=new r(e);this.size=t.size}u.prototype.clear=i,u.prototype.delete=s,u.prototype.get=o,u.prototype.has=a,u.prototype.set=c,e.exports=u},7241:(e,t,n)=>{var r=n(695),i=n(2903),s=n(4894);e.exports=function(e){return s(e)?r(e,!0):i(e)}},7296:(e,t,n)=>{var r,i=n(5481),s=(r=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";e.exports=function(e){return!!s&&s in e}},7301:e=>{e.exports=function(e){return function(t){return e(t)}}},7473:e=>{var t=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return t.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},7534:(e,t,n)=>{var r=n(2552),i=n(346);e.exports=function(e){return i(e)&&"[object Arguments]"==r(e)}},7670:(e,t,n)=>{var r=n(2651);e.exports=function(e){var t=r(this,e).delete(e);return this.size-=t?1:0,t}},7730:(e,t,n)=>{var r=n(9172),i=n(7301),s=n(6009),o=s&&s.isMap,a=o?i(o):r;e.exports=a},7828:(e,t,n)=>{var r=n(9325).Uint8Array;e.exports=r},8055:(e,t,n)=>{var r=n(9999);e.exports=function(e){return r(e,5)}},8096:e=>{e.exports=function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}},8223:(e,t,n)=>{var r=n(6110)(n(9325),"Map");e.exports=r},8303:(e,t,n)=>{var r=n(6110)(n(9325),"WeakMap");e.exports=r},8440:(e,t,n)=>{var r=n(6038),i=n(7301),s=n(6009),o=s&&s.isSet,a=o?i(o):r;e.exports=a},8655:(e,t,n)=>{var r=n(6025);e.exports=function(e){return r(this.__data__,e)>-1}},8879:(e,t,n)=>{var r=n(4335)(Object.getPrototypeOf,Object);e.exports=r},8948:(e,t,n)=>{var r=n(1791),i=n(6375);e.exports=function(e,t){return r(e,i(e),t)}},8984:(e,t,n)=>{var r=n(5527),i=n(3650),s=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return i(e);var t=[];for(var n in Object(e))s.call(e,n)&&"constructor"!=n&&t.push(n);return t}},9172:(e,t,n)=>{var r=n(5861),i=n(346);e.exports=function(e){return i(e)&&"[object Map]"==r(e)}},9325:(e,t,n)=>{var r=n(4840),i="object"==typeof self&&self&&self.Object===Object&&self,s=r||i||Function("return this")();e.exports=s},9344:(e,t,n)=>{var r=n(3805),i=Object.create,s=function(){function e(){}return function(t){if(!r(t))return{};if(i)return i(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();e.exports=s},9350:e=>{var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},9653:(e,t,n)=>{var r=n(7828);e.exports=function(e){var t=new e.constructor(e.byteLength);return new r(t).set(new r(e)),t}},9770:e=>{e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,i=0,s=[];++n<r;){var o=e[n];t(o,n,e)&&(s[i++]=o)}return s}},9817:e=>{e.exports=function(e){return this.__data__.has(e)}},9935:e=>{e.exports=function(){return!1}},9999:(e,t,n)=>{var r=n(7217),i=n(3729),s=n(6547),o=n(4733),a=n(3838),c=n(3290),u=n(3007),l=n(2271),h=n(8948),d=n(2),f=n(3349),p=n(5861),g=n(6189),m=n(7199),y=n(5529),_=n(6449),v=n(3656),w=n(7730),b=n(3805),I=n(8440),E=n(5950),C=n(7241),T="[object Arguments]",S="[object Function]",x="[object Object]",k={};k[T]=k["[object Array]"]=k["[object ArrayBuffer]"]=k["[object DataView]"]=k["[object Boolean]"]=k["[object Date]"]=k["[object Float32Array]"]=k["[object Float64Array]"]=k["[object Int8Array]"]=k["[object Int16Array]"]=k["[object Int32Array]"]=k["[object Map]"]=k["[object Number]"]=k[x]=k["[object RegExp]"]=k["[object Set]"]=k["[object String]"]=k["[object Symbol]"]=k["[object Uint8Array]"]=k["[object Uint8ClampedArray]"]=k["[object Uint16Array]"]=k["[object Uint32Array]"]=!0,k["[object Error]"]=k[S]=k["[object WeakMap]"]=!1,e.exports=function e(t,n,N,D,A,P){var R,O=1&n,M=2&n,F=4&n;if(N&&(R=A?N(t,D,A,P):N(t)),void 0!==R)return R;if(!b(t))return t;var L=_(t);if(L){if(R=g(t),!O)return u(t,R)}else{var q=p(t),V=q==S||"[object GeneratorFunction]"==q;if(v(t))return c(t,O);if(q==x||q==T||V&&!A){if(R=M||V?{}:y(t),!O)return M?h(t,a(R,t)):l(t,o(R,t))}else{if(!k[q])return A?t:{};R=m(t,q,O)}}P||(P=new r);var j=P.get(t);if(j)return j;P.set(t,R),I(t)?t.forEach(function(r){R.add(e(r,n,N,r,t,P))}):w(t)&&t.forEach(function(r,i){R.set(i,e(r,n,N,i,t,P))});var B=L?void 0:(F?M?f:d:M?C:E)(t);return i(B||t,function(r,i){B&&(r=t[i=r]),s(R,i,e(r,n,N,i,t,P))}),R}}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={id:r,loaded:!1,exports:{}};return e[r](s,s.exports,n),s.loaded=!0,s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{"use strict";var e={};n.r(e),n.d(e,{FirebaseError:()=>v,SDK_VERSION:()=>et,_DEFAULT_ENTRY_NAME:()=>Ue,_addComponent:()=>Ke,_addOrOverwriteComponent:()=>We,_apps:()=>$e,_clearComponents:()=>Xe,_components:()=>Ge,_getProvider:()=>He,_registerComponent:()=>Qe,_removeServiceInstance:()=>Ye,deleteApp:()=>it,getApp:()=>nt,getApps:()=>rt,initializeApp:()=>tt,onLog:()=>ot,registerVersion:()=>st,setLogLevel:()=>at});const t=function(e,t){if(!e)throw r(t)},r=function(e){return new Error("Firebase Database (${JSCORE_VERSION}) INTERNAL ASSERT FAILED: "+e)},i=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},s={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(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=i>>2,l=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(i(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;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<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))}else{const s=e[n++],o=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const a=t<e.length?n[e.charAt(t)]:64;++t;const c=t<e.length?n[e.charAt(t)]:64;if(++t,null==i||null==s||null==a||null==c)throw new o;const u=i<<2|s>>4;if(r.push(u),64!==a){const e=s<<4&240|a>>2;if(r.push(e),64!==c){const e=a<<6&192|c;r.push(e)}}}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)}}};class o extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const a=function(e){const t=i(e);return s.encodeByteArray(t,!0)},c=function(e){return a(e).replace(/\./g,"")},u=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function l(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&h(n)&&(e[n]=l(e[n],t[n]));return e}function h(e){return"__proto__"!==e}const d=()=>{try{return function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&u(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},f=()=>{var e;return null===(e=d())||void 0===e?void 0:e.config};class p{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch(()=>{}),1===e.length?e(t):e(t,n))}}}function g(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.');const 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!");const s=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[c(JSON.stringify({alg:"none",type:"JWT"})),c(JSON.stringify(s)),""].join(".")}function m(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function y(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(m())}function _(){try{return"object"==typeof indexedDB}catch(e){return!1}}class v extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,v.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,w.prototype.create)}}class w{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],s=i?function(e,t){return e.replace(b,(e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`})}(i,n):"Error",o=`${this.serviceName}: ${s} (${r}).`;return new v(r,o,n)}}const b=/\{\$([^}]+)}/g;function I(e){return JSON.parse(e)}function E(e){return JSON.stringify(e)}const C=function(e){let t={},n={},r={},i="";try{const s=e.split(".");t=I(u(s[0])||""),n=I(u(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function S(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function x(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function k(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 N(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],s=t[i];if(D(n)&&D(s)){if(!N(n,s))return!1}else if(n!==s)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function D(e){return null!==e&&"object"==typeof e}class A{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_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let r,i,s=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],u=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=c^o&(a^c),i=1518500249):(r=o^a^c,i=1859775393):e<60?(r=o&a|c&(o|a),i=2400959708):(r=o^a^c,i=3395469782);const t=(s<<5|s>>>27)+r+u+i+n[e]&4294967295;u=c,c=a,a=4294967295&(o<<30|o>>>2),o=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+u&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const i=this.buf_;let s=this.inbuf_;for(;r<t;){if(0===s)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[s]=e.charCodeAt(r),++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}else for(;r<t;)if(i[s]=e[r],++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}this.inbuf_=s,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let r=24;r>=0;r-=8)e[n]=this.chain_[t]>>r&255,++n;return e}}function P(e,t){const n=new R(e,t);return n.subscribe.bind(n)}class R{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(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}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){if("object"!=typeof e||null===e)return!1;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}(e)?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=O),void 0===r.error&&(r.error=O),void 0===r.complete&&(r.complete=O);const 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-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}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 O(){}const M=function(e,t,n,r){let i;if(r<t?i="at least "+t:r>n&&(i=0===n?"none":"no more than "+n),i)throw new Error(e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")};function F(e,t){return`${e} failed: ${t} argument `}function L(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(F(e,t)+"must be a valid function.")}function q(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(F(e,t)+"must be a valid context object.")}const V=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t};function j(e){return e&&e._delegate?e._delegate:e}class B{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 U="[DEFAULT]";class z{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){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new p;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)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(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:U})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=U){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=U){return this.instances.has(e)}getOptions(e=U){return this.instancesOptions.get(e)||{}}initialize(e={}){const{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`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(r);return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const 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,r===U?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=U){return this.component?this.component.multipleInstances?e:U:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class ${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){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new z(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const G=[];var K;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(K||(K={}));const W={debug:K.DEBUG,verbose:K.VERBOSE,info:K.INFO,warn:K.WARN,error:K.ERROR,silent:K.SILENT},Q=K.INFO,H={[K.DEBUG]:"log",[K.VERBOSE]:"log",[K.INFO]:"info",[K.WARN]:"warn",[K.ERROR]:"error"},Y=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=H[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};class X{constructor(e){this.name=e,this._logLevel=Q,this._logHandler=Y,this._userLogHandler=null,G.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in K))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?W[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,K.DEBUG,...e),this._logHandler(this,K.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,K.VERBOSE,...e),this._logHandler(this,K.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,K.INFO,...e),this._logHandler(this,K.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,K.WARN,...e),this._logHandler(this,K.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,K.ERROR,...e),this._logHandler(this,K.ERROR,...e)}}let J,Z;const ee=new WeakMap,te=new WeakMap,ne=new WeakMap,re=new WeakMap,ie=new WeakMap;let se={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return te.get(e);if("objectStoreNames"===t)return e.objectStoreNames||ne.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ae(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function oe(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Z||(Z=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(ce(this),e),ae(ee.get(this))}:function(...e){return ae(t.apply(ce(this),e))}:function(e,...n){const r=t.call(ce(this),e,...n);return ne.set(r,e.sort?e.sort():[e]),ae(r)}:(e instanceof IDBTransaction&&function(e){if(te.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});te.set(e,t)}(e),n=e,(J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(e=>n instanceof e)?new Proxy(e,se):e);var t,n}function ae(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(ae(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)});return t.then(t=>{t instanceof IDBCursor&&ee.set(t,e)}).catch(()=>{}),ie.set(t,e),t}(e);if(re.has(e))return re.get(e);const t=oe(e);return t!==e&&(re.set(e,t),ie.set(t,e)),t}const ce=e=>ie.get(e),ue=["get","getKey","getAll","getAllKeys","count"],le=["put","add","delete","clear"],he=new Map;function de(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(he.get(t))return he.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=le.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!ue.includes(n))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&s.done]))[0]};return he.set(t,s),s}var fe;fe=se,se={...fe,get:(e,t,n)=>de(e,t)||fe.get(e,t,n),has:(e,t)=>!!de(e,t)||fe.has(e,t)};class pe{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null}).filter(e=>e).join(" ")}}const ge="@firebase/app",me="0.9.13",ye=new X("@firebase/app"),_e="@firebase/app-compat",ve="@firebase/analytics-compat",we="@firebase/analytics",be="@firebase/app-check-compat",Ie="@firebase/app-check",Ee="@firebase/auth",Ce="@firebase/auth-compat",Te="@firebase/database",Se="@firebase/database-compat",xe="@firebase/functions",ke="@firebase/functions-compat",Ne="@firebase/installations",De="@firebase/installations-compat",Ae="@firebase/messaging",Pe="@firebase/messaging-compat",Re="@firebase/performance",Oe="@firebase/performance-compat",Me="@firebase/remote-config",Fe="@firebase/remote-config-compat",Le="@firebase/storage",qe="@firebase/storage-compat",Ve="@firebase/firestore",je="@firebase/firestore-compat",Be="firebase",Ue="[DEFAULT]",ze={[ge]:"fire-core",[_e]:"fire-core-compat",[we]:"fire-analytics",[ve]:"fire-analytics-compat",[Ie]:"fire-app-check",[be]:"fire-app-check-compat",[Ee]:"fire-auth",[Ce]:"fire-auth-compat",[Te]:"fire-rtdb",[Se]:"fire-rtdb-compat",[xe]:"fire-fn",[ke]:"fire-fn-compat",[Ne]:"fire-iid",[De]:"fire-iid-compat",[Ae]:"fire-fcm",[Pe]:"fire-fcm-compat",[Re]:"fire-perf",[Oe]:"fire-perf-compat",[Me]:"fire-rc",[Fe]:"fire-rc-compat",[Le]:"fire-gcs",[qe]:"fire-gcs-compat",[Ve]:"fire-fst",[je]:"fire-fst-compat","fire-js":"fire-js",[Be]:"fire-js-all"},$e=new Map,Ge=new Map;function Ke(e,t){try{e.container.addComponent(t)}catch(n){ye.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function We(e,t){e.container.addOrOverwriteComponent(t)}function Qe(e){const t=e.name;if(Ge.has(t))return ye.debug(`There were multiple attempts to register component ${t}.`),!1;Ge.set(t,e);for(const t of $e.values())Ke(t,e);return!0}function He(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function Ye(e,t,n=Ue){He(e,t).clearInstance(n)}function Xe(){Ge.clear()}const Je=new w("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","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","no-options":"Need to provide options, when not being deployed to hosting via source.","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.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."});class Ze{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 B("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 Je.create("app-deleted",{appName:this._name})}}const et="9.23.0";function tt(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});const r=Object.assign({name:Ue,automaticDataCollectionEnabled:!1},t),i=r.name;if("string"!=typeof i||!i)throw Je.create("bad-app-name",{appName:String(i)});if(n||(n=f()),!n)throw Je.create("no-options");const s=$e.get(i);if(s){if(N(n,s.options)&&N(r,s.config))return s;throw Je.create("duplicate-app",{appName:i})}const o=new $(i);for(const e of Ge.values())o.addComponent(e);const a=new Ze(n,r,o);return $e.set(i,a),a}function nt(e=Ue){const t=$e.get(e);if(!t&&e===Ue&&f())return tt();if(!t)throw Je.create("no-app",{appName:e});return t}function rt(){return Array.from($e.values())}async function it(e){const t=e.name;$e.has(t)&&($e.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function st(e,t,n){var r;let i=null!==(r=ze[e])&&void 0!==r?r:e;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${t}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void ye.warn(e.join(" "))}Qe(new B(`${i}-version`,()=>({library:i,version:t}),"VERSION"))}function ot(e,t){if(null!==e&&"function"!=typeof e)throw Je.create("invalid-log-argument");!function(e,t){for(const n of G){let r=null;t&&t.level&&(r=W[t.level]),n.userLogHandler=null===e?null:(t,n,...i)=>{const s=i.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(" ");n>=(null!=r?r:t.logLevel)&&e({level:K[n].toLowerCase(),message:s,args:i,type:t.name})}}}(e,t)}function at(e){var t;t=e,G.forEach(e=>{e.setLogLevel(t)})}const ct="firebase-heartbeat-store";let ut=null;function lt(){return ut||(ut=function(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=ae(o);return r&&o.addEventListener("upgradeneeded",e=>{r(ae(o.result),e.oldVersion,e.newVersion,ae(o.transaction),e)}),n&&o.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}("firebase-heartbeat-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(ct)}}).catch(e=>{throw Je.create("idb-open",{originalErrorMessage:e.message})})),ut}async function ht(e,t){try{const n=(await lt()).transaction(ct,"readwrite"),r=n.objectStore(ct);await r.put(t,dt(e)),await n.done}catch(e){if(e instanceof v)ye.warn(e.message);else{const t=Je.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});ye.warn(t.message)}}}function dt(e){return`${e.name}!${e.options.appId}`}class ft{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new gt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=pt();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:e}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{const 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"";const e=pt(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const e=n.find(e=>e.agent===i.agent);if(e){if(e.dates.push(i.date),mt(n)>t){e.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),mt(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),r=c(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,n.length>0?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}}function pt(){return(new Date).toISOString().substring(0,10)}class gt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!_()&&new Promise((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}).then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=await lt();return await t.transaction(ct).objectStore(ct).get(dt(e))}catch(e){if(e instanceof v)ye.warn(e.message);else{const t=Je.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});ye.warn(t.message)}}}(this.app);return e||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return ht(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){const n=await this.read();return ht(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function mt(e){return c(JSON.stringify({version:2,heartbeats:e})).length}Qe(new B("platform-logger",e=>new pe(e),"PRIVATE")),Qe(new B("heartbeat",e=>new ft(e),"PRIVATE")),st(ge,me,""),st(ge,me,"esm2017"),st("fire-js","");class yt{constructor(e,t){this._delegate=e,this.firebase=t,Ke(e,new B("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),it(this._delegate)))}_getService(e,t=Ue){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=Ue){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Ke(this._delegate,e)}_addOrOverwriteComponent(e){We(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const _t=new w("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."}),vt=function t(){const n=function(t){const n={},r={__esModule:!0,initializeApp:function(e,i={}){const s=tt(e,i);if(T(n,s.name))return n[s.name];const o=new t(s,r);return n[s.name]=o,o},app:i,registerVersion:st,setLogLevel:at,onLog:ot,apps:null,SDK_VERSION:et,INTERNAL:{registerComponent:function(e){const n=e.name,s=n.replace("-compat","");if(Qe(e)&&"PUBLIC"===e.type){const o=(e=i())=>{if("function"!=typeof e[s])throw _t.create("invalid-app-argument",{appName:n});return e[s]()};void 0!==e.serviceProps&&l(o,e.serviceProps),r[s]=o,t.prototype[s]=function(...t){return this._getService.bind(this,n).apply(this,e.multipleInstances?t:[])}}return"PUBLIC"===e.type?r[s]:null},removeApp:function(e){delete n[e]},useAsService:function(e,t){return"serverAuth"===t?null:t},modularAPIs:e}};function i(e){if(!T(n,e=e||Ue))throw _t.create("no-app",{appName:e});return n[e]}return r.default=r,Object.defineProperty(r,"apps",{get:function(){return Object.keys(n).map(e=>n[e])}}),i.App=t,r}(yt);return n.INTERNAL=Object.assign(Object.assign({},n.INTERNAL),{createFirebaseNamespace:t,extendNamespace:function(e){l(n,e)},createSubscribe:P,ErrorFactory:w,deepExtend:l}),n}(),wt=new X("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){wt.warn("\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n ");const e=self.firebase.SDK_VERSION;e&&e.indexOf("LITE")>=0&&wt.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n ")}const bt=vt;st("@firebase/app-compat","0.2.13",void 0),bt.registerVersion("firebase","9.23.0","app-compat");var It,Et="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{},Ct={},Tt=Tt||{},St=Et||self;function xt(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 kt(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Nt="closure_uid_"+(1e9*Math.random()>>>0),Dt=0;function At(e,t,n){return e.call.apply(e.bind,arguments)}function Pt(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function Rt(e,t,n){return(Rt=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?At:Pt).apply(null,arguments)}function Ot(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function Mt(e,t){function n(){}n.prototype=t.prototype,e.$=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.ac=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}function Ft(){this.s=this.s,this.o=this.o}Ft.prototype.s=!1,Ft.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,Nt)&&e[Nt]||(e[Nt]=++Dt))},Ft.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Lt=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};function qt(e){const t=e.length;if(0<t){const n=Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}return[]}function Vt(e,t){for(let t=1;t<arguments.length;t++){const n=arguments[t];if(xt(n)){const t=e.length||0,r=n.length||0;e.length=t+r;for(let i=0;i<r;i++)e[t+i]=n[i]}else e.push(n)}}function jt(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}jt.prototype.h=function(){this.defaultPrevented=!0};var Bt=function(){if(!St.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{St.addEventListener("test",()=>{},t),St.removeEventListener("test",()=>{},t)}catch(e){}return e}();function Ut(e){return/^[\s\xa0]*$/.test(e)}function zt(){var e=St.navigator;return e&&(e=e.userAgent)?e:""}function $t(e){return-1!=zt().indexOf(e)}function Gt(e){return Gt[" "](e),e}Gt[" "]=function(){};var Kt,Wt,Qt,Ht=$t("Opera"),Yt=$t("Trident")||$t("MSIE"),Xt=$t("Edge"),Jt=Xt||Yt,Zt=$t("Gecko")&&!(-1!=zt().toLowerCase().indexOf("webkit")&&!$t("Edge"))&&!($t("Trident")||$t("MSIE"))&&!$t("Edge"),en=-1!=zt().toLowerCase().indexOf("webkit")&&!$t("Edge");function tn(){var e=St.document;return e?e.documentMode:void 0}e:{var nn="",rn=(Wt=zt(),Zt?/rv:([^\);]+)(\)|;)/.exec(Wt):Xt?/Edge\/([\d\.]+)/.exec(Wt):Yt?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Wt):en?/WebKit\/(\S+)/.exec(Wt):Ht?/(?:Version)[ \/]?(\S+)/.exec(Wt):void 0);if(rn&&(nn=rn?rn[1]:""),Yt){var sn=tn();if(null!=sn&&sn>parseFloat(nn)){Kt=String(sn);break e}}Kt=nn}St.document&&Yt?Qt=tn()||parseInt(Kt,10)||void 0:Qt=void 0;var on=Qt;function an(e,t){if(jt.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(Zt){e:{try{Gt(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:cn[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&an.$.h.call(this)}}Mt(an,jt);var cn={2:"touch",3:"pen",4:"mouse"};an.prototype.h=function(){an.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var un="closure_listenable_"+(1e6*Math.random()|0),ln=0;function hn(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++ln,this.fa=this.ia=!1}function dn(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function fn(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function pn(e){const t={};for(const n in e)t[n]=e[n];return t}const gn="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function mn(e,t){let n,r;for(let t=1;t<arguments.length;t++){for(n in r=arguments[t],r)e[n]=r[n];for(let t=0;t<gn.length;t++)n=gn[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function yn(e){this.src=e,this.g={},this.h=0}function _n(e,t){var n=t.type;if(n in e.g){var r,i=e.g[n],s=Lt(i,t);(r=0<=s)&&Array.prototype.splice.call(i,s,1),r&&(dn(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function vn(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}yn.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=vn(e,t,r,i);return-1<o?(t=e[o],n||(t.ia=!1)):((t=new hn(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var wn="closure_lm_"+(1e6*Math.random()|0),bn={};function In(e,t,n,r,i){if(r&&r.once)return Cn(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)In(e,t[s],n,r,i);return null}return n=An(n),e&&e[un]?e.O(t,n,kt(r)?!!r.capture:!!r,i):En(e,t,n,!1,r,i)}function En(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o=kt(i)?!!i.capture:!!i,a=Nn(e);if(a||(e[wn]=a=new yn(e)),(n=a.add(t,n,r,o,s)).proxy)return n;if(r=function(){const e=kn;return function t(n){return e.call(t.src,t.listener,n)}}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)Bt||(i=o),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(xn(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Cn(e,t,n,r,i){if(Array.isArray(t)){for(var s=0;s<t.length;s++)Cn(e,t[s],n,r,i);return null}return n=An(n),e&&e[un]?e.P(t,n,kt(r)?!!r.capture:!!r,i):En(e,t,n,!0,r,i)}function Tn(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)Tn(e,t[s],n,r,i);else r=kt(r)?!!r.capture:!!r,n=An(n),e&&e[un]?(e=e.i,(t=String(t).toString())in e.g&&-1<(n=vn(s=e.g[t],n,r,i))&&(dn(s[n]),Array.prototype.splice.call(s,n,1),0==s.length&&(delete e.g[t],e.h--))):e&&(e=Nn(e))&&(t=e.g[t.toString()],e=-1,t&&(e=vn(t,n,r,i)),(n=-1<e?t[e]:null)&&Sn(n))}function Sn(e){if("number"!=typeof e&&e&&!e.fa){var t=e.src;if(t&&t[un])_n(t.i,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(xn(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Nn(t))?(_n(n,e),0==n.h&&(n.src=null,t[wn]=null)):dn(e)}}}function xn(e){return e in bn?bn[e]:bn[e]="on"+e}function kn(e,t){if(e.fa)e=!0;else{t=new an(t,this);var n=e.listener,r=e.la||e.src;e.ia&&Sn(e),e=n.call(r,t)}return e}function Nn(e){return(e=e[wn])instanceof yn?e:null}var Dn="__closure_events_fn_"+(1e9*Math.random()>>>0);function An(e){return"function"==typeof e?e:(e[Dn]||(e[Dn]=function(t){return e.handleEvent(t)}),e[Dn])}function Pn(){Ft.call(this),this.i=new yn(this),this.S=this,this.J=null}function Rn(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t)t=new jt(t,e);else if(t instanceof jt)t.target=t.target||e;else{var i=t;mn(t=new jt(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var o=t.g=n[s];i=On(o,r,!0,t)&&i}if(i=On(o=t.g=e,r,!0,t)&&i,i=On(o,r,!1,t)&&i,n)for(s=0;s<n.length;s++)i=On(o=t.g=n[s],r,!1,t)&&i}function On(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=t[s];if(o&&!o.fa&&o.capture==n){var a=o.listener,c=o.la||o.src;o.ia&&_n(e.i,o),i=!1!==a.call(c,r)&&i}}return i&&!r.defaultPrevented}Mt(Pn,Ft),Pn.prototype[un]=!0,Pn.prototype.removeEventListener=function(e,t,n,r){Tn(this,e,t,n,r)},Pn.prototype.N=function(){if(Pn.$.N.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++)dn(n[r]);delete t.g[e],t.h--}}this.J=null},Pn.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Pn.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Mn=St.JSON.stringify;function Fn(){var e=zn;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}var Ln=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 qn,e=>e.reset());class qn{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 Vn(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}function jn(e){St.setTimeout(()=>{throw e},0)}let Bn,Un=!1,zn=new class{constructor(){this.h=this.g=null}add(e,t){const n=Ln.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},$n=()=>{const e=St.Promise.resolve(void 0);Bn=()=>{e.then(Gn)}};var Gn=()=>{for(var e;e=Fn();){try{e.h.call(e.g)}catch(e){jn(e)}var t=Ln;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}Un=!1};function Kn(e,t){Pn.call(this),this.h=e||1,this.g=t||St,this.j=Rt(this.qb,this),this.l=Date.now()}function Wn(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Qn(e,t,n){if("function"==typeof e)n&&(e=Rt(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Rt(e.handleEvent,e)}return 2147483647<Number(t)?-1:St.setTimeout(e,t||0)}function Hn(e){e.g=Qn(()=>{e.g=null,e.i&&(e.i=!1,Hn(e))},e.j);const t=e.h;e.h=null,e.m.apply(null,t)}Mt(Kn,Pn),(It=Kn.prototype).ga=!1,It.T=null,It.qb=function(){if(this.ga){var e=Date.now()-this.l;0<e&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),Rn(this,"tick"),this.ga&&(Wn(this),this.start()))}},It.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},It.N=function(){Kn.$.N.call(this),Wn(this),delete this.g};class Yn extends Ft{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:Hn(this)}N(){super.N(),this.g&&(St.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Xn(e){Ft.call(this),this.h=e,this.g={}}Mt(Xn,Ft);var Jn=[];function Zn(e,t,n,r){Array.isArray(n)||(n&&(Jn[0]=n.toString()),n=Jn);for(var i=0;i<n.length;i++){var s=In(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function er(e){fn(e.g,function(e,t){this.g.hasOwnProperty(t)&&Sn(e)},e),e.g={}}function tr(){this.g=!0}function nr(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(!(2>r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return Mn(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Xn.prototype.N=function(){Xn.$.N.call(this),er(this)},Xn.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},tr.prototype.Ea=function(){this.g=!1},tr.prototype.info=function(){};var rr={},ir=null;function sr(){return ir=ir||new Pn}function or(e){jt.call(this,rr.Ta,e)}function ar(e){const t=sr();Rn(t,new or(t))}function cr(e,t){jt.call(this,rr.STAT_EVENT,e),this.stat=t}function ur(e){const t=sr();Rn(t,new cr(t,e))}function lr(e,t){jt.call(this,rr.Ua,e),this.size=t}function hr(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return St.setTimeout(function(){e()},t)}rr.Ta="serverreachability",Mt(or,jt),rr.STAT_EVENT="statevent",Mt(cr,jt),rr.Ua="timingevent",Mt(lr,jt);var dr={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},fr={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function pr(){}function gr(e){return e.h||(e.h=e.i())}function mr(){}pr.prototype.h=null;var yr,_r={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function vr(){jt.call(this,"d")}function wr(){jt.call(this,"c")}function br(){}function Ir(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new Xn(this),this.P=Cr,e=Jt?125:void 0,this.V=new Kn(e),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new Er}function Er(){this.i=null,this.g="",this.h=!1}Mt(vr,jt),Mt(wr,jt),Mt(br,pr),br.prototype.g=function(){return new XMLHttpRequest},br.prototype.i=function(){return{}},yr=new br;var Cr=45e3,Tr={},Sr={};function xr(e,t,n){e.L=1,e.v=Kr(Br(t)),e.s=n,e.S=!0,kr(e,null)}function kr(e,t){e.G=Date.now(),Pr(e),e.A=Br(e.v);var n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),si(n.i,"t",r),e.C=0,n=e.l.J,e.h=new Er,e.g=ss(e.l,n?t:null,!e.s),0<e.O&&(e.M=new Yn(Rt(e.Pa,e,e.g),e.O)),Zn(e.U,e.g,"readystatechange",e.nb),t=e.I?pn(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),ar(),function(e,t,n,r,i,s){e.info(function(){if(e.g)if(s)for(var o="",a=s.split("&"),c=0;c<a.length;c++){var u=a[c].split("=");if(1<u.length){var l=u[0];u=u[1];var h=l.split("_");o=2<=h.length&&"type"==h[1]?o+(l+"=")+u+"&":o+(l+"=redacted&")}}else o=null;else o=s;return"XMLHTTP REQ ("+r+") [attempt "+i+"]: "+t+"\n"+n+"\n"+o})}(e.j,e.u,e.A,e.m,e.W,e.s)}function Nr(e){return!!e.g&&"GET"==e.u&&2!=e.L&&e.l.Ha}function Dr(e,t,n){let r,i=!0;for(;!e.J&&e.C<n.length;){if(r=Ar(e,n),r==Sr){4==t&&(e.o=4,ur(14),i=!1),nr(e.j,e.m,null,"[Incomplete Response]");break}if(r==Tr){e.o=4,ur(15),nr(e.j,e.m,n,"[Invalid Chunk]"),i=!1;break}nr(e.j,e.m,r,null),Lr(e,r)}Nr(e)&&r!=Sr&&r!=Tr&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,ur(16),i=!1),e.i=e.i&&i,i?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),Xi(t),t.M=!0,ur(11))):(nr(e.j,e.m,n,"[Invalid Chunked Response]"),Fr(e),Mr(e))}function Ar(e,t){var n=e.C,r=t.indexOf("\n",n);return-1==r?Sr:(n=Number(t.substring(n,r)),isNaN(n)?Tr:(r+=1)+n>t.length?Sr:(t=t.slice(r,r+n),e.C=r+n,t))}function Pr(e){e.Y=Date.now()+e.P,Rr(e,e.P)}function Rr(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=hr(Rt(e.lb,e),t)}function Or(e){e.B&&(St.clearTimeout(e.B),e.B=null)}function Mr(e){0==e.l.H||e.J||es(e.l,e)}function Fr(e){Or(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,Wn(e.V),er(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function Lr(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||di(n.i,e)))if(!e.K&&di(n.i,e)&&3==n.H){try{var r=n.Ja.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.G+3e3<e.G))break e;Zi(n),zi(n)}Yi(n),ur(18)}}else n.Fa=i[1],0<n.Fa-n.V&&37500>i[2]&&n.G&&0==n.A&&!n.v&&(n.v=hr(Rt(n.ib,n),6e3));if(1>=hi(n.i)&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else ns(n,11)}else if((e.K||n.g==e)&&Zi(n),!Ut(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){let u=i[t];if(n.V=u[0],u=u[1],2==n.H)if("c"==u[0]){n.K=u[1],n.pa=u[2];const t=u[3];null!=t&&(n.ra=t,n.l.info("VER="+n.ra));const i=u[4];null!=i&&(n.Ga=i,n.l.info("SVER="+n.Ga));const l=u[5];null!=l&&"number"==typeof l&&0<l&&(r=1.5*l,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const h=e.g;if(h){const e=h.g?h.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=r.i;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(fi(s,s.h),s.h=null))}if(r.F){const e=h.g?h.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.Da=e,Gr(r.I,r.F,e))}}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var o=e;if((r=n).wa=is(r,r.J?r.pa:null,r.Y),o.K){pi(r.i,o);var a=o,c=r.L;c&&a.setTimeout(c),a.B&&(Or(a),Pr(a)),r.g=o}else Hi(r);0<n.j.length&&Gi(n)}else"stop"!=u[0]&&"close"!=u[0]||ns(n,7);else 3==n.H&&("stop"==u[0]||"close"==u[0]?"stop"==u[0]?ns(n,7):Ui(n):"noop"!=u[0]&&n.h&&n.h.Aa(u),n.A=0)}ar()}catch(e){}}function qr(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(xt(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(xt(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(xt(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),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(It=Ir.prototype).setTimeout=function(e){this.P=e},It.nb=function(e){e=e.target;const t=this.M;t&&3==Fi(e)?t.l():this.Pa(e)},It.Pa=function(e){try{if(e==this.g)e:{const l=Fi(this.g);var t=this.g.Ia();if(this.g.da(),!(3>l)&&(3!=l||Jt||this.g&&(this.h.h||this.g.ja()||Li(this.g)))){this.J||4!=l||7==t||ar(),Or(this);var n=this.g.da();this.ca=n;t:if(Nr(this)){var r=Li(this.g);e="";var i=r.length,s=4==Fi(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Fr(this),Mr(this);var o="";break t}this.h.i=new St.TextDecoder}for(t=0;t<i;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:s&&t==i-1});r.splice(0,i),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ja();if(this.i=200==n,function(e,t,n,r,i,s,o){e.info(function(){return"XMLHTTP RESP ("+r+") [ attempt "+i+"]: "+t+"\n"+n+"\n"+s+" "+o})}(this.j,this.u,this.A,this.m,this.W,l,n),this.i){if(this.aa&&!this.K){t:{if(this.g){var a,c=this.g;if((a=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!Ut(a)){var u=a;break t}}u=null}if(!(n=u)){this.i=!1,this.o=3,ur(12),Fr(this),Mr(this);break e}nr(this.j,this.m,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Lr(this,n)}this.S?(Dr(this,l,o),Jt&&this.i&&3==l&&(Zn(this.U,this.V,"tick",this.mb),this.V.start())):(nr(this.j,this.m,o,null),Lr(this,o)),4==l&&Fr(this),this.i&&!this.J&&(4==l?es(this.l,this):(this.i=!1,Pr(this)))}else(function(e){const t={};e=(e.g&&2<=Fi(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(Ut(e[r]))continue;var n=Vn(e[r]);const i=n[0];if("string"!=typeof(n=n[1]))continue;n=n.trim();const s=t[i]||[];t[i]=s,s.push(n)}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==n&&0<o.indexOf("Unknown SID")?(this.o=3,ur(12)):(this.o=0,ur(13)),Fr(this),Mr(this)}}}catch(e){}},It.mb=function(){if(this.g){var e=Fi(this.g),t=this.g.ja();this.C<t.length&&(Or(this),Dr(this,e,t),this.i&&4!=e&&Pr(this))}},It.cancel=function(){this.J=!0,Fr(this)},It.lb=function(){this.B=null;const e=Date.now();0<=e-this.Y?(function(e,t){e.info(function(){return"TIMEOUT: "+t})}(this.j,this.A),2!=this.L&&(ar(),ur(17)),Fr(this),this.o=2,Mr(this)):Rr(this,this.Y-e)};var Vr=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function jr(e){if(this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof jr){this.h=e.h,Ur(this,e.j),this.s=e.s,this.g=e.g,zr(this,e.m),this.l=e.l;var t=e.i,n=new ti;n.i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),$r(this,n),this.o=e.o}else e&&(t=String(e).match(Vr))?(this.h=!1,Ur(this,t[1]||"",!0),this.s=Wr(t[2]||""),this.g=Wr(t[3]||"",!0),zr(this,t[4]),this.l=Wr(t[5]||"",!0),$r(this,t[6]||"",!0),this.o=Wr(t[7]||"")):(this.h=!1,this.i=new ti(null,this.h))}function Br(e){return new jr(e)}function Ur(e,t,n){e.j=n?Wr(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function zr(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.m=t}else e.m=null}function $r(e,t,n){t instanceof ti?(e.i=t,function(e,t){t&&!e.j&&(ni(e),e.i=null,e.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(ri(this,t),si(this,n,e))},e)),e.j=t}(e.i,e.h)):(n||(t=Qr(t,Zr)),e.i=new ti(t,e.h))}function Gr(e,t,n){e.i.set(t,n)}function Kr(e){return Gr(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Wr(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Qr(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Hr),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function Hr(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}jr.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Qr(t,Yr,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.s)&&e.push(Qr(t,Yr,!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.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Qr(n,"/"==n.charAt(0)?Jr:Xr,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Qr(n,ei)),e.join("")};var Yr=/[#\/\?@]/g,Xr=/[#\?:]/g,Jr=/[#\?]/g,Zr=/[#\?@]/g,ei=/#/g;function ti(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function ni(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var s=e[n].substring(0,r);i=e[n].substring(r+1)}else s=e[n];t(s,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.i,function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)}))}function ri(e,t){ni(e),t=oi(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function ii(e,t){return ni(e),t=oi(e,t),e.g.has(t)}function si(e,t,n){ri(e,t),0<n.length&&(e.i=null,e.g.set(oi(e,t),qt(n)),e.h+=n.length)}function oi(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}(It=ti.prototype).add=function(e,t){ni(this),this.i=null,e=oi(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},It.forEach=function(e,t){ni(this),this.g.forEach(function(n,r){n.forEach(function(n){e.call(t,n,r,this)},this)},this)},It.ta=function(){ni(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const i=e[r];for(let e=0;e<i.length;e++)n.push(t[r])}return n},It.Z=function(e){ni(this);let t=[];if("string"==typeof e)ii(this,e)&&(t=t.concat(this.g.get(oi(this,e))));else{e=Array.from(this.g.values());for(let n=0;n<e.length;n++)t=t.concat(e[n])}return t},It.set=function(e,t){return ni(this),this.i=null,ii(this,e=oi(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},It.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},It.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++){var r=t[n];const s=encodeURIComponent(String(r)),o=this.Z(r);for(r=0;r<o.length;r++){var i=s;""!==o[r]&&(i+="="+encodeURIComponent(String(o[r]))),e.push(i)}}return this.i=e.join("&")};var ai=class{constructor(e,t){this.g=e,this.map=t}};function ci(e){this.l=e||ui,e=St.PerformanceNavigationTiming?0<(e=St.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(St.g&&St.g.Ka&&St.g.Ka()&&St.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var ui=10;function li(e){return!!e.h||!!e.g&&e.g.size>=e.j}function hi(e){return e.h?1:e.g?e.g.size:0}function di(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function fi(e,t){e.g?e.g.add(t):e.h=t}function pi(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function gi(e){if(null!=e.h)return e.i.concat(e.h.F);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.F);return t}return qt(e.i)}ci.prototype.cancel=function(){if(this.i=gi(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()}};var mi=class{stringify(e){return St.JSON.stringify(e,void 0)}parse(e){return St.JSON.parse(e,void 0)}};function yi(){this.g=new mi}function _i(e,t,n){const r=n||"";try{qr(e,function(e,n){let i=e;kt(e)&&(i=Mn(e)),t.push(r+n+"="+encodeURIComponent(i))})}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function vi(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function wi(e){this.l=e.fc||null,this.j=e.ob||!1}function bi(e,t){Pn.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=Ii,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}Mt(wi,pr),wi.prototype.g=function(){return new bi(this.l,this.j)},wi.prototype.i=function(e){return function(){return e}}({}),Mt(bi,Pn);var Ii=0;function Ei(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function Ci(e){e.readyState=4,e.l=null,e.j=null,e.A=null,Ti(e)}function Ti(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(It=bi.prototype).open=function(e,t){if(this.readyState!=Ii)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,Ti(this)},It.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.F||St).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},It.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Ci(this)),this.readyState=Ii},It.$a=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,Ti(this)),this.g&&(this.readyState=3,Ti(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(void 0!==St.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;Ei(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},It.Xa=function(e){if(this.g){if(this.u&&e.value)this.response.push(e.value);else if(!this.u){var t=e.value?e.value:new Uint8Array(0);(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?Ci(this):Ti(this),3==this.readyState&&Ei(this)}},It.Za=function(e){this.g&&(this.response=this.responseText=e,Ci(this))},It.Ya=function(e){this.g&&(this.response=e,Ci(this))},It.ka=function(){this.g&&Ci(this)},It.setRequestHeader=function(e,t){this.v.append(e,t)},It.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},It.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(bi.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var Si=St.JSON.parse;function xi(e){Pn.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=ki,this.L=this.M=!1}Mt(xi,Pn);var ki="",Ni=/^https?$/i,Di=["POST","PUT"];function Ai(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Pi(e),Oi(e)}function Pi(e){e.F||(e.F=!0,Rn(e,"complete"),Rn(e,"error"))}function Ri(e){if(e.h&&void 0!==Tt&&(!e.C[1]||4!=Fi(e)||2!=e.da()))if(e.v&&4==Fi(e))Qn(e.La,0,e);else if(Rn(e,"readystatechange"),4==Fi(e)){e.h=!1;try{const o=e.da();e:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===o){var i=String(e.I).match(Vr)[1]||null;!i&&St.self&&St.self.location&&(i=St.self.location.protocol.slice(0,-1)),r=!Ni.test(i?i.toLowerCase():"")}n=r}if(n)Rn(e,"complete"),Rn(e,"success");else{e.m=6;try{var s=2<Fi(e)?e.g.statusText:""}catch(e){s=""}e.j=s+" ["+e.da()+"]",Pi(e)}}finally{Oi(e)}}}function Oi(e,t){if(e.g){Mi(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||Rn(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Mi(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(St.clearTimeout(e.A),e.A=null)}function Fi(e){return e.g?e.g.readyState:0}function Li(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case ki:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function qi(e){let t="";return fn(e,function(e,n){t+=n,t+=":",t+=e,t+="\r\n"}),t}function Vi(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=qi(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Gr(e,t,n))}function ji(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Bi(e){this.Ga=0,this.j=[],this.l=new tr,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=ji("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=ji("baseRetryDelayMs",5e3,e),this.hb=ji("retryDelaySeedMs",1e4,e),this.eb=ji("forwardChannelMaxRetries",2,e),this.xa=ji("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new ci(e&&e.concurrentRequestLimit),this.Ja=new yi,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function Ui(e){if($i(e),3==e.H){var t=e.W++,n=Br(e.I);if(Gr(n,"SID",e.K),Gr(n,"RID",t),Gr(n,"TYPE","terminate"),Wi(e,n),(t=new Ir(e,e.l,t)).L=2,t.v=Kr(Br(n)),n=!1,St.navigator&&St.navigator.sendBeacon)try{n=St.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&St.Image&&((new Image).src=t.v,n=!0),n||(t.g=ss(t.l,null),t.g.ha(t.v)),t.G=Date.now(),Pr(t)}rs(e)}function zi(e){e.g&&(Xi(e),e.g.cancel(),e.g=null)}function $i(e){zi(e),e.u&&(St.clearTimeout(e.u),e.u=null),Zi(e),e.i.cancel(),e.m&&("number"==typeof e.m&&St.clearTimeout(e.m),e.m=null)}function Gi(e){if(!li(e.i)&&!e.m){e.m=!0;var t=e.Na;Bn||$n(),Un||(Bn(),Un=!0),zn.add(t,e),e.C=0}}function Ki(e,t){var n;n=t?t.m:e.W++;const r=Br(e.I);Gr(r,"SID",e.K),Gr(r,"RID",n),Gr(r,"AID",e.V),Wi(e,r),e.o&&e.s&&Vi(r,e.o,e.s),n=new Ir(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=Qi(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),fi(e.i,n),xr(n,r,t)}function Wi(e,t){e.na&&fn(e.na,function(e,n){Gr(t,n,e)}),e.h&&qr({},function(e,n){Gr(t,n,e)})}function Qi(e,t,n){n=Math.min(e.j.length,n);var r=e.h?Rt(e.h.Va,e.h,e):null;e:{var i=e.j;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let s=!0;for(let o=0;o<n;o++){let n=i[o].g;const a=i[o].map;if(n-=t,0>n)t=Math.max(0,i[o].g-100),s=!1;else try{_i(a,e,"req"+n+"_")}catch(e){r&&r(a)}}if(s){r=e.join("&");break e}}}return e=e.j.splice(0,n),t.F=e,r}function Hi(e){if(!e.g&&!e.u){e.ba=1;var t=e.Ma;Bn||$n(),Un||(Bn(),Un=!0),zn.add(t,e),e.A=0}}function Yi(e){return!(e.g||e.u||3<=e.A||(e.ba++,e.u=hr(Rt(e.Ma,e),ts(e,e.A)),e.A++,0))}function Xi(e){null!=e.B&&(St.clearTimeout(e.B),e.B=null)}function Ji(e){e.g=new Ir(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=Br(e.wa);Gr(t,"RID","rpc"),Gr(t,"SID",e.K),Gr(t,"AID",e.V),Gr(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&Gr(t,"TO",e.qa),Gr(t,"TYPE","xmlhttp"),Wi(e,t),e.o&&e.s&&Vi(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Kr(Br(t)),n.s=null,n.S=!0,kr(n,e)}function Zi(e){null!=e.v&&(St.clearTimeout(e.v),e.v=null)}function es(e,t){var n=null;if(e.g==t){Zi(e),Xi(e),e.g=null;var r=2}else{if(!di(e.i,t))return;n=t.F,pi(e.i,t),r=1}if(0!=e.H)if(t.i)if(1==r){n=t.s?t.s.length:0,t=Date.now()-t.G;var i=e.C;Rn(r=sr(),new lr(r,n)),Gi(e)}else Hi(e);else if(3==(i=t.o)||0==i&&0<t.ca||!(1==r&&function(e,t){return!(hi(e.i)>=e.i.j-(e.m?1:0)||(e.m?(e.j=t.F.concat(e.j),0):1==e.H||2==e.H||e.C>=(e.cb?0:e.eb)||(e.m=hr(Rt(e.Na,e,t),ts(e,e.C)),e.C++,0)))}(e,t)||2==r&&Yi(e)))switch(n&&0<n.length&&(t=e.i,t.i=t.i.concat(n)),i){case 1:ns(e,5);break;case 4:ns(e,10);break;case 3:ns(e,6);break;default:ns(e,2)}}function ts(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function ns(e,t){if(e.l.info("Error code "+t),2==t){var n=null;e.h&&(n=null);var r=Rt(e.pb,e);n||(n=new jr("//www.google.com/images/cleardot.gif"),St.location&&"http"==St.location.protocol||Ur(n,"https"),Kr(n)),function(e,t){const n=new tr;if(St.Image){const r=new Image;r.onload=Ot(vi,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Ot(vi,n,r,"TestLoadImage: error",!1,t),r.onabort=Ot(vi,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Ot(vi,n,r,"TestLoadImage: timeout",!1,t),St.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)}else ur(2);e.H=0,e.h&&e.h.za(t),rs(e),$i(e)}function rs(e){if(e.H=0,e.ma=[],e.h){const t=gi(e.i);0==t.length&&0==e.j.length||(Vt(e.ma,t),Vt(e.ma,e.j),e.i.i.length=0,qt(e.j),e.j.length=0),e.h.ya()}}function is(e,t,n){var r=n instanceof jr?Br(n):new jr(n);if(""!=r.g)t&&(r.g=t+"."+r.g),zr(r,r.m);else{var i=St.location;r=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;var s=new jr(null);r&&Ur(s,r),t&&(s.g=t),i&&zr(s,i),n&&(s.l=n),r=s}return n=e.F,t=e.Da,n&&t&&Gr(r,n,t),Gr(r,"VER",e.ra),Wi(e,r),r}function ss(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new xi(new wi({ob:!0})):new xi(e.va)).Oa(e.J),t}function os(){}function as(){if(Yt&&!(10<=Number(on)))throw Error("Environmental error: no available transport.")}function cs(e,t){Pn.call(this),this.g=new Bi(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.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!Ut(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Ut(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&t in(e=this.h)&&delete e[t]),this.j=new hs(this)}function us(e){vr.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);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 ls(){wr.call(this),this.status=1}function hs(e){this.g=e}function ds(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function fs(e,t,n){n||(n=0);var r=Array(16);if("string"==typeof t)for(var i=0;16>i;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;16>i;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],i=e.g[2];var s=e.g[3],o=t+(s^n&(i^s))+r[0]+3614090360&4294967295;o=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+(o<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|o>>>10))+((o=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|o>>>12))+((o=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|o>>>9))+((o=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|o>>>11))+((s=(t=n+((o=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|o>>>22))^((i=s+((o=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|o>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(o<<21&4294967295|o>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function ps(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(It=xi.prototype).Oa=function(e){this.M=e},It.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=this.u?this.u.g():yr.g(),this.C=this.u?gr(this.u):gr(yr),this.g.onreadystatechange=Rt(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void Ai(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const e of r.keys())n.set(e,r.get(e))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=St.FormData&&e instanceof St.FormData,!(0<=Lt(Di,t))||r||i||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[e,t]of n)this.g.setRequestHeader(e,t);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{Mi(this),0<this.B&&((this.L=function(e){return Yt&&"number"==typeof e.timeout&&void 0!==e.ontimeout}(this.g))?(this.g.timeout=this.B,this.g.ontimeout=Rt(this.ua,this)):this.A=Qn(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){Ai(this,e)}},It.ua=function(){void 0!==Tt&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Rn(this,"timeout"),this.abort(8))},It.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Rn(this,"complete"),Rn(this,"abort"),Oi(this))},It.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),Oi(this,!0)),xi.$.N.call(this)},It.La=function(){this.s||(this.G||this.v||this.l?Ri(this):this.kb())},It.kb=function(){Ri(this)},It.isActive=function(){return!!this.g},It.da=function(){try{return 2<Fi(this)?this.g.status:-1}catch(e){return-1}},It.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},It.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Si(t)}},It.Ia=function(){return this.m},It.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(It=Bi.prototype).ra=8,It.H=1,It.Na=function(e){if(this.m)if(this.m=null,1==this.H){if(!e){this.W=Math.floor(1e5*Math.random()),e=this.W++;const i=new Ir(this,this.l,e);let s=this.s;if(this.U&&(s?(s=pn(s),mn(s,this.U)):s=this.U),null!==this.o||this.O||(i.I=s,s=null),this.P)e:{for(var t=0,n=0;n<this.j.length;n++){var r=this.j[n];if(void 0===(r="__data__"in r.map&&"string"==typeof(r=r.map.__data__)?r.length:void 0))break;if(4096<(t+=r)){t=n;break e}if(4096===t||n===this.j.length-1){t=n+1;break e}}t=1e3}else t=1e3;t=Qi(this,i,t),Gr(n=Br(this.I),"RID",e),Gr(n,"CVER",22),this.F&&Gr(n,"X-HTTP-Session-Id",this.F),Wi(this,n),s&&(this.O?t="headers="+encodeURIComponent(String(qi(s)))+"&"+t:this.o&&Vi(n,this.o,s)),fi(this.i,i),this.bb&&Gr(n,"TYPE","init"),this.P?(Gr(n,"$req",t),Gr(n,"SID","null"),i.aa=!0,xr(i,n,null)):xr(i,n,t),this.H=2}}else 3==this.H&&(e?Ki(this,e):0==this.j.length||li(this.i)||Ki(this))},It.Ma=function(){if(this.u=null,Ji(this),this.ca&&!(this.M||null==this.g||0>=this.S)){var e=2*this.S;this.l.info("BP detection timer enabled: "+e),this.B=hr(Rt(this.jb,this),e)}},It.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,ur(10),zi(this),Ji(this))},It.ib=function(){null!=this.v&&(this.v=null,zi(this),Yi(this),ur(19))},It.pb=function(e){e?(this.l.info("Successfully pinged google.com"),ur(2)):(this.l.info("Failed to ping google.com"),ur(1))},It.isActive=function(){return!!this.h&&this.h.isActive(this)},(It=os.prototype).Ba=function(){},It.Aa=function(){},It.za=function(){},It.ya=function(){},It.isActive=function(){return!0},It.Va=function(){},as.prototype.g=function(e,t){return new cs(e,t)},Mt(cs,Pn),cs.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;ur(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=is(e,null,e.Y),Gi(e)},cs.prototype.close=function(){Ui(this.g)},cs.prototype.u=function(e){var t=this.g;if("string"==typeof e){var n={};n.__data__=e,e=n}else this.v&&((n={}).__data__=Mn(e),e=n);t.j.push(new ai(t.fb++,e)),3==t.H&&Gi(t)},cs.prototype.N=function(){this.g.h=null,delete this.j,Ui(this.g),delete this.g,cs.$.N.call(this)},Mt(us,vr),Mt(ls,wr),Mt(hs,os),hs.prototype.Ba=function(){Rn(this.g,"a")},hs.prototype.Aa=function(e){Rn(this.g,new us(e))},hs.prototype.za=function(e){Rn(this.g,new ls)},hs.prototype.ya=function(){Rn(this.g,"b")},Mt(ds,function(){this.blockSize=-1}),ds.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},ds.prototype.j=function(e,t){void 0===t&&(t=e.length);for(var n=t-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)fs(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){fs(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){fs(this,r),i=0;break}}this.h=i,this.i+=t},ds.prototype.l=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;var n=8*this.i;for(t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;4>t;++t)for(var r=0;32>r;r+=8)e[n++]=this.g[t]>>>r&255;return e};var gs={};function ms(e){return-128<=e&&128>e?function(e){var t=gs;return Object.prototype.hasOwnProperty.call(t,e)?t[e]:t[e]=function(e){return new ps([0|e],0>e?-1:0)}(e)}(e):new ps([0|e],0>e?-1:0)}function ys(e){if(isNaN(e)||!isFinite(e))return vs;if(0>e)return Cs(ys(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=_s;return new ps(t,0)}var _s=4294967296,vs=ms(0),ws=ms(1),bs=ms(16777216);function Is(e){if(0!=e.h)return!1;for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function Es(e){return-1==e.h}function Cs(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new ps(n,~e.h).add(ws)}function Ts(e,t){return e.add(Cs(t))}function Ss(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function xs(e,t){this.g=e,this.h=t}function ks(e,t){if(Is(t))throw Error("division by zero");if(Is(e))return new xs(vs,vs);if(Es(e))return t=ks(Cs(e),t),new xs(Cs(t.g),Cs(t.h));if(Es(t))return t=ks(e,Cs(t)),new xs(Cs(t.g),t.h);if(30<e.g.length){if(Es(e)||Es(t))throw Error("slowDivide_ only works with positive integers.");for(var n=ws,r=t;0>=r.X(e);)n=Ns(n),r=Ns(r);var i=Ds(n,1),s=Ds(r,1);for(r=Ds(r,2),n=Ds(n,2);!Is(r);){var o=s.add(r);0>=o.X(e)&&(i=i.add(n),s=o),r=Ds(r,1),n=Ds(n,1)}return t=Ts(e,i.R(t)),new xs(i,t)}for(i=vs;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=48>=(r=Math.ceil(Math.log(n)/Math.LN2))?1:Math.pow(2,r-48),o=(s=ys(n)).R(t);Es(o)||0<o.X(e);)o=(s=ys(n-=r)).R(t);Is(s)&&(s=ws),i=i.add(s),e=Ts(e,o)}return new xs(i,e)}function Ns(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new ps(n,e.h)}function Ds(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new ps(i,e.h)}(It=ps.prototype).ea=function(){if(Es(this))return-Cs(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:_s+r)*t,t*=_s}return e},It.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(Is(this))return"0";if(Es(this))return"-"+Cs(this).toString(e);for(var t=ys(Math.pow(e,6)),n=this,r="";;){var i=ks(n,t).g,s=((0<(n=Ts(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(Is(n=i))return s+r;for(;6>s.length;)s="0"+s;r=s+r}},It.D=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},It.X=function(e){return Es(e=Ts(this,e))?-1:Is(e)?0:1},It.abs=function(){return Es(this)?Cs(this):this},It.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),o=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16);r=o>>>16,s&=65535,o&=65535,n[i]=o<<16|s}return new ps(n,-2147483648&n[n.length-1]?-1:0)},It.R=function(e){if(Is(this)||Is(e))return vs;if(Es(this))return Es(e)?Cs(this).R(Cs(e)):Cs(Cs(this).R(e));if(Es(e))return Cs(this.R(Cs(e)));if(0>this.X(bs)&&0>e.X(bs))return ys(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,o=65535&this.D(r),a=e.D(i)>>>16,c=65535&e.D(i);n[2*r+2*i]+=o*c,Ss(n,2*r+2*i),n[2*r+2*i+1]+=s*c,Ss(n,2*r+2*i+1),n[2*r+2*i+1]+=o*a,Ss(n,2*r+2*i+1),n[2*r+2*i+2]+=s*a,Ss(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new ps(n,0)},It.gb=function(e){return ks(this,e).h},It.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new ps(n,this.h&e.h)},It.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new ps(n,this.h|e.h)},It.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new ps(n,this.h^e.h)},as.prototype.createWebChannel=as.prototype.g,cs.prototype.send=cs.prototype.u,cs.prototype.open=cs.prototype.m,cs.prototype.close=cs.prototype.close,dr.NO_ERROR=0,dr.TIMEOUT=8,dr.HTTP_ERROR=6,fr.COMPLETE="complete",mr.EventType=_r,_r.OPEN="a",_r.CLOSE="b",_r.ERROR="c",_r.MESSAGE="d",Pn.prototype.listen=Pn.prototype.O,xi.prototype.listenOnce=xi.prototype.P,xi.prototype.getLastError=xi.prototype.Sa,xi.prototype.getLastErrorCode=xi.prototype.Ia,xi.prototype.getStatus=xi.prototype.da,xi.prototype.getResponseJson=xi.prototype.Wa,xi.prototype.getResponseText=xi.prototype.ja,xi.prototype.send=xi.prototype.ha,xi.prototype.setWithCredentials=xi.prototype.Oa,ds.prototype.digest=ds.prototype.l,ds.prototype.reset=ds.prototype.reset,ds.prototype.update=ds.prototype.j,ps.prototype.add=ps.prototype.add,ps.prototype.multiply=ps.prototype.R,ps.prototype.modulo=ps.prototype.gb,ps.prototype.compare=ps.prototype.X,ps.prototype.toNumber=ps.prototype.ea,ps.prototype.toString=ps.prototype.toString,ps.prototype.getBits=ps.prototype.D,ps.fromNumber=ys,ps.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if(2>(n=n||10)||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return Cs(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=ys(Math.pow(n,8)),i=vs,s=0;s<t.length;s+=8){var o=Math.min(8,t.length-s),a=parseInt(t.substring(s,s+o),n);8>o?(o=ys(Math.pow(n,o)),i=i.R(o).add(ys(a))):i=(i=i.R(r)).add(ys(a))}return i};var As=Ct.createWebChannelTransport=function(){return new as},Ps=Ct.getStatEventTarget=function(){return sr()},Rs=Ct.ErrorCode=dr,Os=Ct.EventType=fr,Ms=Ct.Event=rr,Fs=Ct.Stat={xb:0,Ab:1,Bb:2,Ub:3,Zb:4,Wb:5,Xb:6,Vb:7,Tb:8,Yb:9,PROXY:10,NOPROXY:11,Rb:12,Nb:13,Ob:14,Mb:15,Pb:16,Qb:17,tb:18,sb:19,ub:20},Ls=Ct.FetchXmlHttpFactory=wi,qs=Ct.WebChannel=mr,Vs=Ct.XhrIo=xi,js=Ct.Md5=ds,Bs=Ct.Integer=ps;const Us="@firebase/firestore";class zs{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}}zs.UNAUTHENTICATED=new zs(null),zs.GOOGLE_CREDENTIALS=new zs("google-credentials-uid"),zs.FIRST_PARTY=new zs("first-party-uid"),zs.MOCK_USER=new zs("mock-user");let $s="9.23.0";const Gs=new X("@firebase/firestore");function Ks(){return Gs.logLevel}function Ws(e,...t){if(Gs.logLevel<=K.DEBUG){const n=t.map(Ys);Gs.debug(`Firestore (${$s}): ${e}`,...n)}}function Qs(e,...t){if(Gs.logLevel<=K.ERROR){const n=t.map(Ys);Gs.error(`Firestore (${$s}): ${e}`,...n)}}function Hs(e,...t){if(Gs.logLevel<=K.WARN){const n=t.map(Ys);Gs.warn(`Firestore (${$s}): ${e}`,...n)}}function Ys(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}var t}function Xs(e="Unexpected state"){const t=`FIRESTORE (${$s}) INTERNAL ASSERTION FAILED: `+e;throw Qs(t),new Error(t)}function Js(e,t){e||Xs()}function Zs(e,t){return e}const eo={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 to extends v{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class no{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class ro{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class io{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(zs.UNAUTHENTICATED))}shutdown(){}}class so{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 oo{constructor(e){this.t=e,this.currentUser=zs.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new no;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new no,e.enqueueRetryable(()=>r(this.currentUser))};const s=()=>{const t=i;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},o=e=>{Ws("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),s()};this.t.onInit(e=>o(e)),setTimeout(()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(Ws("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new no)}},0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(Ws("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(Js("string"==typeof t.accessToken),new ro(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return Js(null===e||"string"==typeof e),new zs(e)}}class ao{constructor(e,t,n){this.h=e,this.l=t,this.m=n,this.type="FirstParty",this.user=zs.FIRST_PARTY,this.g=new Map}p(){return this.m?this.m():null}get headers(){this.g.set("X-Goog-AuthUser",this.h);const e=this.p();return e&&this.g.set("Authorization",e),this.l&&this.g.set("X-Goog-Iam-Authorization-Token",this.l),this.g}}class co{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new ao(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(zs.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class uo{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class lo{constructor(e){this.I=e,this.forceRefresh=!1,this.appCheck=null,this.T=null}start(e,t){const n=e=>{null!=e.error&&Ws("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.T;return this.T=e.token,Ws("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};const r=e=>{Ws("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.I.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){const e=this.I.getImmediate({optional:!0});e?r(e):Ws("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Js("string"==typeof e.token),this.T=e.token,new uo(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}function ho(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;t<e;t++)n[t]=Math.floor(256*Math.random());return n}class fo{static A(){const e=62*Math.floor(256/62);let t="";for(;t.length<20;){const n=ho(40);for(let r=0;r<n.length;++r)t.length<20&&n[r]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[r]%62))}return t}}function po(e,t){return e<t?-1:e>t?1:0}function go(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}function mo(e){return e+"\0"}class yo{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new to(eo.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new to(eo.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new to(eo.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new to(eo.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return yo.fromMillis(Date.now())}static fromDate(e){return yo.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new yo(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?po(this.nanoseconds,e.nanoseconds):po(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(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class _o{constructor(e){this.timestamp=e}static fromTimestamp(e){return new _o(e)}static min(){return new _o(new yo(0,0))}static max(){return new _o(new yo(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}}class vo{constructor(e,t,n){void 0===t?t=0:t>e.length&&Xs(),void 0===n?n=e.length-t:n>e.length-t&&Xs(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===vo.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof vo?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+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 wo extends vo{construct(e,t,n){return new wo(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new to(eo.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new wo(t)}static emptyPath(){return new wo([])}}const bo=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Io extends vo{construct(e,t,n){return new Io(e,t,n)}static isValidIdentifier(e){return bo.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Io.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Io(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new to(eo.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 to(eo.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new to(eo.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(s=!s,r++):"."!==t||s?(n+=t,r++):(i(),r++)}if(i(),s)throw new to(eo.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Io(t)}static emptyPath(){return new Io([])}}class Eo{constructor(e){this.path=e}static fromPath(e){return new Eo(wo.fromString(e))}static fromName(e){return new Eo(wo.fromString(e).popFirst(5))}static empty(){return new Eo(wo.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&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===wo.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return wo.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new Eo(new wo(e.slice()))}}class Co{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function To(e){return e.fields.find(e=>2===e.kind)}function So(e){return e.fields.filter(e=>2!==e.kind)}Co.UNKNOWN_ID=-1;class xo{constructor(e,t){this.fieldPath=e,this.kind=t}}class ko{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new ko(0,Ao.min())}}function No(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=_o.fromTimestamp(1e9===r?new yo(n+1,0):new yo(n,r));return new Ao(i,Eo.empty(),t)}function Do(e){return new Ao(e.readTime,e.key,-1)}class Ao{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Ao(_o.min(),Eo.empty(),-1)}static max(){return new Ao(_o.max(),Eo.empty(),-1)}}function Po(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=Eo.comparator(e.documentKey,t.documentKey),0!==n?n:po(e.largestBatchId,t.largestBatchId))}const Ro="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Oo{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Mo(e){if(e.code!==eo.FAILED_PRECONDITION||e.message!==Ro)throw e;Ws("LocalStore","Unexpectedly lost primary lease")}class Fo{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(e,t){return this.callbackAttached&&Xs(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new Fo((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{const t=e();return t instanceof Fo?t:Fo.resolve(t)}catch(e){return Fo.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):Fo.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):Fo.reject(t)}static resolve(e){return new Fo((t,n)=>{t(e)})}static reject(e){return new Fo((t,n)=>{n(e)})}static waitFor(e){return new Fo((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=Fo.resolve(!1);for(const n of e)t=t.next(e=>e?Fo.resolve(e):n());return t}static forEach(e,t){const n=[];return e.forEach((e,r)=>{n.push(t.call(this,e,r))}),this.waitFor(n)}static mapArray(e,t){return new Fo((n,r)=>{const i=e.length,s=new Array(i);let o=0;for(let a=0;a<i;a++){const c=a;t(e[c]).next(e=>{s[c]=e,++o,o===i&&n(s)},e=>r(e))}})}static doWhile(e,t){return new Fo((n,r)=>{const i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}class Lo{constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.v=new no,this.transaction.oncomplete=()=>{this.v.resolve()},this.transaction.onabort=()=>{t.error?this.v.reject(new jo(e,t.error)):this.v.resolve()},this.transaction.onerror=t=>{const n=Go(t.target.error);this.v.reject(new jo(e,n))}}static open(e,t,n,r){try{return new Lo(t,e.transaction(r,n))}catch(e){throw new jo(t,e)}}get R(){return this.v.promise}abort(e){e&&this.v.reject(e),this.aborted||(Ws("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}P(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){const t=this.transaction.objectStore(e);return new Uo(t)}}class qo{constructor(e,t,n){this.name=e,this.version=t,this.V=n,12.2===qo.S(m())&&Qs("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 Ws("SimpleDb","Removing database:",e),zo(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!_())return!1;if(qo.C())return!0;const e=m(),t=qo.S(e),n=0<t&&t<10,r=qo.N(e),i=0<r&&r<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||n||i)}static C(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.k)}static M(e,t){return e.store(t)}static S(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 N(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async $(e){return this.db||(Ws("SimpleDb","Opening database:",this.name),this.db=await new Promise((t,n)=>{const r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{const n=e.target.result;t(n)},r.onblocked=()=>{n(new jo(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{const r=t.target.error;"VersionError"===r.name?n(new to(eo.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"===r.name?n(new to(eo.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: "+r)):n(new jo(e,r))},r.onupgradeneeded=e=>{Ws("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);const t=e.target.result;this.V.O(t,r.transaction,e.oldVersion,this.version).next(()=>{Ws("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.F&&(this.db.onversionchange=e=>this.F(e)),this.db}B(e){this.F=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){const i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.$(e);const t=Lo.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.P(),e)).catch(e=>(t.abort(e),Fo.reject(e))).toPromise();return s.catch(()=>{}),await t.R,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Ws("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class Vo{constructor(e){this.L=e,this.q=!1,this.U=null}get isDone(){return this.q}get K(){return this.U}set cursor(e){this.L=e}done(){this.q=!0}G(e){this.U=e}delete(){return zo(this.L.delete())}}class jo extends to{constructor(e,t){super(eo.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Bo(e){return"IndexedDbTransactionError"===e.name}class Uo{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(Ws("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(Ws("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),zo(n)}add(e){return Ws("SimpleDb","ADD",this.store.name,e,e),zo(this.store.add(e))}get(e){return zo(this.store.get(e)).next(t=>(void 0===t&&(t=null),Ws("SimpleDb","GET",this.store.name,e,t),t))}delete(e){return Ws("SimpleDb","DELETE",this.store.name,e),zo(this.store.delete(e))}count(){return Ws("SimpleDb","COUNT",this.store.name),zo(this.store.count())}j(e,t){const n=this.options(e,t);if(n.index||"function"!=typeof this.store.getAll){const e=this.cursor(n),t=[];return this.W(e,(e,n)=>{t.push(n)}).next(()=>t)}{const e=this.store.getAll(n.range);return new Fo((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}H(e,t){const n=this.store.getAll(e,null===t?void 0:t);return new Fo((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}J(e,t){Ws("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;const r=this.cursor(n);return this.W(r,(e,t,n)=>n.delete())}X(e,t){let n;t?n=e:(n={},t=e);const r=this.cursor(n);return this.W(r,t)}Z(e){const t=this.cursor({});return new Fo((n,r)=>{t.onerror=e=>{const t=Go(e.target.error);r(t)},t.onsuccess=t=>{const r=t.target.result;r?e(r.primaryKey,r.value).next(e=>{e?r.continue():n()}):n()}})}W(e,t){const n=[];return new Fo((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{const i=e.target.result;if(!i)return void r();const s=new Vo(i),o=t(i.primaryKey,i.value,s);if(o instanceof Fo){const e=o.catch(e=>(s.done(),Fo.reject(e)));n.push(e)}s.isDone?r():null===s.K?i.continue():i.continue(s.K)}}).next(()=>Fo.waitFor(n))}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.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function zo(e){return new Fo((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=Go(e.target.error);n(t)}})}let $o=!1;function Go(e){const t=qo.S(m());if(t>=12.2&&t<13){const t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){const e=new to("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 $o||($o=!0,setTimeout(()=>{throw e},0)),e}}return e}class Ko{constructor(e,t){this.asyncQueue=e,this.tt=t,this.task=null}start(){this.et(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}et(e){Ws("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Ws("IndexBackiller",`Documents written: ${await this.tt.nt()}`)}catch(e){Bo(e)?Ws("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await Mo(e)}await this.et(6e4)})}}class Wo{constructor(e,t){this.localStore=e,this.persistence=t}async nt(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.st(t,e))}st(e,t){const n=new Set;let r=t,i=!0;return Fo.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!n.has(t))return Ws("IndexBackiller",`Processing collection: ${t}`),this.it(e,t,r).next(e=>{r-=e,n.add(t)});i=!1})).next(()=>t-r)}it(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next(n=>{const i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next(()=>this.rt(r,n)).next(n=>(Ws("IndexBackiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n))).next(()=>i.size)}))}rt(e,t){let n=e;return t.changes.forEach((e,t)=>{const r=Do(t);Po(r,n)>0&&(n=r)}),new Ao(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Qo{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ot(e),this.ut=e=>t.writeSequenceNumber(e))}ot(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.ut&&this.ut(e),e}}function Ho(e){return null==e}function Yo(e){return 0===e&&1/e==-1/0}function Xo(e){return"number"==typeof e&&Number.isInteger(e)&&!Yo(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Jo(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t=ea(t)),t=Zo(e.get(n),t);return ea(t)}function Zo(e,t){let n=t;const r=e.length;for(let t=0;t<r;t++){const r=e.charAt(t);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}function ea(e){return e+""}function ta(e){const t=e.length;if(Js(t>=2),2===t)return Js(""===e.charAt(0)&&""===e.charAt(1)),wo.emptyPath();const n=t-2,r=[];let i="";for(let s=0;s<t;){const t=e.indexOf("",s);switch((t<0||t>n)&&Xs(),e.charAt(t+1)){case"":const n=e.substring(s,t);let o;0===i.length?o=n:(i+=n,o=i,i=""),r.push(o);break;case"":i+=e.substring(s,t),i+="\0";break;case"":i+=e.substring(s,t+1);break;default:Xs()}s=t+2}return new wo(r)}Qo.ct=-1;const na=["userId","batchId"];function ra(e,t){return[e,Jo(t)]}function ia(e,t,n){return[e,Jo(t),n]}const sa={},oa=["prefixPath","collectionGroup","readTime","documentId"],aa=["prefixPath","collectionGroup","documentId"],ca=["collectionGroup","readTime","prefixPath","documentId"],ua=["canonicalId","targetId"],la=["targetId","path"],ha=["path","targetId"],da=["collectionId","parent"],fa=["indexId","uid"],pa=["uid","sequenceNumber"],ga=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],ma=["indexId","uid","orderedDocumentKey"],ya=["userId","collectionPath","documentId"],_a=["userId","collectionPath","largestBatchId"],va=["userId","collectionGroup","largestBatchId"],wa=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ba=[...wa,"documentOverlays"],Ia=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Ea=Ia,Ca=[...Ea,"indexConfiguration","indexState","indexEntries"];class Ta extends Oo{constructor(e,t){super(),this.ht=e,this.currentSequenceNumber=t}}function Sa(e,t){const n=Zs(e);return qo.M(n.ht,t)}function xa(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ka(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Na(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class Da{constructor(e,t){this.comparator=e,this.root=t||Pa.EMPTY}insert(e,t){return new Da(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Pa.BLACK,null,null))}remove(e){return new Da(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Pa.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=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(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){const e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new Aa(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Aa(this.root,e,this.comparator,!1)}getReverseIterator(){return new Aa(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Aa(this.root,e,this.comparator,!0)}}class Aa{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();const 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 this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class Pa{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Pa.RED,this.left=null!=r?r:Pa.EMPTY,this.right=null!=i?i:Pa.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new Pa(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;const 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 Pa.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 Pa.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(){const e=this.copy(null,null,Pa.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,Pa.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const 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(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Xs();if(this.right.isRed())throw Xs();const e=this.left.check();if(e!==this.right.check())throw Xs();return e+(this.isRed()?0:1)}}Pa.EMPTY=null,Pa.RED=!0,Pa.BLACK=!1,Pa.EMPTY=new class{constructor(){this.size=0}get key(){throw Xs()}get value(){throw Xs()}get color(){throw Xs()}get left(){throw Xs()}get right(){throw Xs()}copy(e,t,n,r,i){return this}insert(e,t,n){return new Pa(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 Ra{constructor(e){this.comparator=e,this.data=new Da(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(e){this.data.inorderTraversal((t,n)=>(e(t),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)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 Oa(this.data.getIterator())}getIteratorFrom(e){return new Oa(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 Ra))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 e=[];return this.forEach(t=>{e.push(t)}),e}toString(){const e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){const t=new Ra(this.comparator);return t.data=e,t}}class Oa{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function Ma(e){return e.hasNext()?e.getNext():void 0}class Fa{constructor(e){this.fields=e,e.sort(Io.comparator)}static empty(){return new Fa([])}unionWith(e){let t=new Ra(Io.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new Fa(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return go(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class La extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class qa{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new La("Invalid base64 string: "+e):e}}(e);return new qa(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new qa(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 po(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}qa.EMPTY_BYTE_STRING=new qa("");const Va=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ja(e){if(Js(!!e),"string"==typeof e){let t=0;const n=Va.exec(e);if(Js(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:Ba(e.seconds),nanos:Ba(e.nanos)}}function Ba(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ua(e){return"string"==typeof e?qa.fromBase64String(e):qa.fromUint8Array(e)}function za(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function $a(e){const t=e.mapValue.fields.__previous_value__;return za(t)?$a(t):t}function Ga(e){const t=ja(e.mapValue.fields.__local_write_time__.timestampValue);return new yo(t.seconds,t.nanos)}class Ka{constructor(e,t,n,r,i,s,o,a,c){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=c}}class Wa{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Wa("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Wa&&e.projectId===this.projectId&&e.database===this.database}}const Qa={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Ha={nullValue:"NULL_VALUE"};function Ya(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?za(e)?4:lc(e)?9007199254740991:10:Xs()}function Xa(e,t){if(e===t)return!0;const n=Ya(e);if(n!==Ya(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Ga(e).isEqual(Ga(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=ja(e.timestampValue),r=ja(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return Ua(e.bytesValue).isEqual(Ua(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return Ba(e.geoPointValue.latitude)===Ba(t.geoPointValue.latitude)&&Ba(e.geoPointValue.longitude)===Ba(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Ba(e.integerValue)===Ba(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=Ba(e.doubleValue),r=Ba(t.doubleValue);return n===r?Yo(n)===Yo(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return go(e.arrayValue.values||[],t.arrayValue.values||[],Xa);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(xa(n)!==xa(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Xa(n[e],r[e])))return!1;return!0}(e,t);default:return Xs()}}function Ja(e,t){return void 0!==(e.values||[]).find(e=>Xa(e,t))}function Za(e,t){if(e===t)return 0;const n=Ya(e),r=Ya(t);if(n!==r)return po(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return po(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=Ba(e.integerValue||e.doubleValue),r=Ba(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return ec(e.timestampValue,t.timestampValue);case 4:return ec(Ga(e),Ga(t));case 5:return po(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ua(e),r=Ua(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){const t=po(n[e],r[e]);if(0!==t)return t}return po(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=po(Ba(e.latitude),Ba(t.latitude));return 0!==n?n:po(Ba(e.longitude),Ba(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){const n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){const t=Za(n[e],r[e]);if(t)return t}return po(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Qa.mapValue&&t===Qa.mapValue)return 0;if(e===Qa.mapValue)return 1;if(t===Qa.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){const t=po(r[e],s[e]);if(0!==t)return t;const o=Za(n[r[e]],i[s[e]]);if(0!==o)return o}return po(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Xs()}}function ec(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return po(e,t);const n=ja(e),r=ja(t),i=po(n.seconds,r.seconds);return 0!==i?i:po(n.nanos,r.nanos)}function tc(e){return nc(e)}function nc(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=ja(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?Ua(e.bytesValue).toBase64():"referenceValue"in e?(n=e.referenceValue,Eo.fromName(n).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+=nc(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}:${nc(e.fields[i])}`;return n+"}"}(e.mapValue):Xs();var t,n}function rc(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function ic(e){return!!e&&"integerValue"in e}function sc(e){return!!e&&"arrayValue"in e}function oc(e){return!!e&&"nullValue"in e}function ac(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function cc(e){return!!e&&"mapValue"in e}function uc(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return ka(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=uc(n)),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=uc(e.arrayValue.values[n]);return t}return Object.assign({},e)}function lc(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function hc(e){return"nullValue"in e?Ha:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?rc(Wa.empty(),Eo.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?{mapValue:{}}:Xs()}function dc(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?rc(Wa.empty(),Eo.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?{mapValue:{}}:"mapValue"in e?Qa:Xs()}function fc(e,t){const n=Za(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function pc(e,t){const n=Za(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class gc{constructor(e){this.value=e}static empty(){return new gc({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!cc(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=uc(t)}setAll(e){let t=Io.emptyPath(),n={},r=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=uc(e):r.push(i.lastSegment())});const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());cc(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Xa(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];cc(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){ka(t,(t,n)=>e[t]=n);for(const t of n)delete e[t]}clone(){return new gc(uc(this.value))}}function mc(e){const t=[];return ka(e.fields,(e,n)=>{const r=new Io([e]);if(cc(n)){const e=mc(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)}),new Fa(t)}class yc{constructor(e,t,n,r,i,s,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=o}static newInvalidDocument(e){return new yc(e,0,_o.min(),_o.min(),_o.min(),gc.empty(),0)}static newFoundDocument(e,t,n,r){return new yc(e,1,t,_o.min(),n,r,0)}static newNoDocument(e,t){return new yc(e,2,t,_o.min(),_o.min(),gc.empty(),0)}static newUnknownDocument(e,t){return new yc(e,3,t,_o.min(),_o.min(),gc.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(_o.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=gc.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=gc.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=_o.min(),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 yc&&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 yc(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class _c{constructor(e,t){this.position=e,this.inclusive=t}}function vc(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()?Eo.comparator(Eo.fromName(o.referenceValue),n.key):Za(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function wc(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(!Xa(e.position[n],t.position[n]))return!1;return!0}class bc{constructor(e,t="asc"){this.field=e,this.dir=t}}function Ic(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class Ec{}class Cc extends Ec{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.createKeyFieldInFilter(e,t,n):new Oc(e,t,n):"array-contains"===t?new qc(e,n):"in"===t?new Vc(e,n):"not-in"===t?new jc(e,n):"array-contains-any"===t?new Bc(e,n):new Cc(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new Mc(e,n):new Fc(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Za(t,this.value)):null!==t&&Ya(this.value)===Ya(t)&&this.matchesComparison(Za(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return Xs()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class Tc extends Ec{constructor(e,t){super(),this.filters=e,this.op=t,this.lt=null}static create(e,t){return new Tc(e,t)}matches(e){return Sc(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.lt||(this.lt=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.lt}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){const e=this.ft(e=>e.isInequality());return null!==e?e.field:null}ft(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function Sc(e){return"and"===e.op}function xc(e){return"or"===e.op}function kc(e){return Nc(e)&&Sc(e)}function Nc(e){for(const t of e.filters)if(t instanceof Tc)return!1;return!0}function Dc(e){if(e instanceof Cc)return e.field.canonicalString()+e.op.toString()+tc(e.value);if(kc(e))return e.filters.map(e=>Dc(e)).join(",");{const t=e.filters.map(e=>Dc(e)).join(",");return`${e.op}(${t})`}}function Ac(e,t){return e instanceof Cc?function(e,t){return t instanceof Cc&&e.op===t.op&&e.field.isEqual(t.field)&&Xa(e.value,t.value)}(e,t):e instanceof Tc?function(e,t){return t instanceof Tc&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce((e,n,r)=>e&&Ac(n,t.filters[r]),!0)}(e,t):void Xs()}function Pc(e,t){const n=e.filters.concat(t);return Tc.create(n,e.op)}function Rc(e){return e instanceof Cc?function(e){return`${e.field.canonicalString()} ${e.op} ${tc(e.value)}`}(e):e instanceof Tc?function(e){return e.op.toString()+" {"+e.getFilters().map(Rc).join(" ,")+"}"}(e):"Filter"}class Oc extends Cc{constructor(e,t,n){super(e,t,n),this.key=Eo.fromName(n.referenceValue)}matches(e){const t=Eo.comparator(e.key,this.key);return this.matchesComparison(t)}}class Mc extends Cc{constructor(e,t){super(e,"in",t),this.keys=Lc(0,t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class Fc extends Cc{constructor(e,t){super(e,"not-in",t),this.keys=Lc(0,t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function Lc(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>Eo.fromName(e.referenceValue))}class qc extends Cc{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return sc(t)&&Ja(t.arrayValue,this.value)}}class Vc extends Cc{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Ja(this.value.arrayValue,t)}}class jc extends Cc{constructor(e,t){super(e,"not-in",t)}matches(e){if(Ja(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Ja(this.value.arrayValue,t)}}class Bc extends Cc{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!sc(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Ja(this.value.arrayValue,e))}}class Uc{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.dt=null}}function zc(e,t=null,n=[],r=[],i=null,s=null,o=null){return new Uc(e,t,n,r,i,s,o)}function $c(e){const t=Zs(e);if(null===t.dt){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>Dc(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),Ho(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>tc(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>tc(e)).join(",")),t.dt=e}return t.dt}function Gc(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!Ic(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!Ac(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!wc(e.startAt,t.startAt)&&wc(e.endAt,t.endAt)}function Kc(e){return Eo.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Wc(e,t){return e.filters.filter(e=>e instanceof Cc&&e.field.isEqual(t))}function Qc(e,t,n){let r=Ha,i=!0;for(const n of Wc(e,t)){let e=Ha,t=!0;switch(n.op){case"<":case"<=":e=hc(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=Ha}fc({value:r,inclusive:i},{value:e,inclusive:t})<0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];fc({value:r,inclusive:i},{value:e,inclusive:n.inclusive})<0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}function Hc(e,t,n){let r=Qa,i=!0;for(const n of Wc(e,t)){let e=Qa,t=!0;switch(n.op){case">=":case">":e=dc(n.value),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=Qa}pc({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];pc({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}class Yc{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.wt=null,this._t=null,this.startAt,this.endAt}}function Xc(e,t,n,r,i,s,o,a){return new Yc(e,t,n,r,i,s,o,a)}function Jc(e){return new Yc(e)}function Zc(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function eu(e){return e.explicitOrderBy.length>0?e.explicitOrderBy[0].field:null}function tu(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function nu(e){return null!==e.collectionGroup}function ru(e){const t=Zs(e);if(null===t.wt){t.wt=[];const e=tu(t),n=eu(t);if(null!==e&&null===n)e.isKeyField()||t.wt.push(new bc(e)),t.wt.push(new bc(Io.keyField(),"asc"));else{let e=!1;for(const n of t.explicitOrderBy)t.wt.push(n),n.field.isKeyField()&&(e=!0);if(!e){const e=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.wt.push(new bc(Io.keyField(),e))}}}return t.wt}function iu(e){const t=Zs(e);if(!t._t)if("F"===t.limitType)t._t=zc(t.path,t.collectionGroup,ru(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const n of ru(t)){const t="desc"===n.dir?"asc":"desc";e.push(new bc(n.field,t))}const n=t.endAt?new _c(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new _c(t.startAt.position,t.startAt.inclusive):null;t._t=zc(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t._t}function su(e,t){t.getFirstInequalityField(),tu(e);const n=e.filters.concat([t]);return new Yc(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function ou(e,t,n){return new Yc(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function au(e,t){return Gc(iu(e),iu(t))&&e.limitType===t.limitType}function cu(e){return`${$c(iu(e))}|lt:${e.limitType}`}function uu(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map(e=>Rc(e)).join(", ")}]`),Ho(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(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=>tc(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>tc(e)).join(",")),`Target(${t})`}(iu(e))}; limitType=${e.limitType})`}function lu(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):Eo.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of ru(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=vc(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,ru(e),t)||e.endAt&&!function(e,t,n){const r=vc(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,ru(e),t))}(e,t)}function hu(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function du(e){return(t,n)=>{let r=!1;for(const i of ru(e)){const e=fu(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function fu(e,t,n){const r=e.field.isKeyField()?Eo.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Za(r,i):Xs()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Xs()}}class pu{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 n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[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(e){ka(this.inner,(t,n)=>{for(const[t,r]of n)e(t,r)})}isEmpty(){return Na(this.inner)}size(){return this.innerSize}}const gu=new Da(Eo.comparator);function mu(){return gu}const yu=new Da(Eo.comparator);function _u(...e){let t=yu;for(const n of e)t=t.insert(n.key,n);return t}function vu(e){let t=yu;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function wu(){return Iu()}function bu(){return Iu()}function Iu(){return new pu(e=>e.toString(),(e,t)=>e.isEqual(t))}const Eu=new Da(Eo.comparator),Cu=new Ra(Eo.comparator);function Tu(...e){let t=Cu;for(const n of e)t=t.add(n);return t}const Su=new Ra(po);function xu(){return Su}function ku(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Yo(t)?"-0":t}}function Nu(e){return{integerValue:""+e}}function Du(e,t){return Xo(t)?Nu(t):ku(e,t)}class Au{constructor(){this._=void 0}}function Pu(e,t,n){return e instanceof Mu?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&za(t)&&(t=$a(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof Fu?Lu(e,t):e instanceof qu?Vu(e,t):function(e,t){const n=Ou(e,t),r=Bu(n)+Bu(e.gt);return ic(n)&&ic(e.gt)?Nu(r):ku(e.serializer,r)}(e,t)}function Ru(e,t,n){return e instanceof Fu?Lu(e,t):e instanceof qu?Vu(e,t):n}function Ou(e,t){return e instanceof ju?ic(n=t)||function(e){return!!e&&"doubleValue"in e}(n)?t:{integerValue:0}:null;var n}class Mu extends Au{}class Fu extends Au{constructor(e){super(),this.elements=e}}function Lu(e,t){const n=Uu(t);for(const t of e.elements)n.some(e=>Xa(e,t))||n.push(t);return{arrayValue:{values:n}}}class qu extends Au{constructor(e){super(),this.elements=e}}function Vu(e,t){let n=Uu(t);for(const t of e.elements)n=n.filter(e=>!Xa(e,t));return{arrayValue:{values:n}}}class ju extends Au{constructor(e,t){super(),this.serializer=e,this.gt=t}}function Bu(e){return Ba(e.integerValue||e.doubleValue)}function Uu(e){return sc(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class zu{constructor(e,t){this.field=e,this.transform=t}}class $u{constructor(e,t){this.version=e,this.transformResults=t}}class Gu{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Gu}static exists(e){return new Gu(void 0,e)}static updateTime(e){return new Gu(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 Ku(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Wu{}function Qu(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new il(e.key,Gu.none()):new Zu(e.key,e.data,Gu.none());{const n=e.data,r=gc.empty();let i=new Ra(Io.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new el(e.key,r,new Fa(i.toArray()),Gu.none())}}function Hu(e,t,n){e instanceof Zu?function(e,t,n){const r=e.value.clone(),i=nl(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof el?function(e,t,n){if(!Ku(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=nl(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(tl(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function Yu(e,t,n,r){return e instanceof Zu?function(e,t,n,r){if(!Ku(e.precondition,t))return n;const i=e.value.clone(),s=rl(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof el?function(e,t,n,r){if(!Ku(e.precondition,t))return n;const i=rl(e.fieldTransforms,r,t),s=t.data;return s.setAll(tl(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):function(e,t,n){return Ku(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function Xu(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=Ou(r.transform,e||null);null!=i&&(null===n&&(n=gc.empty()),n.set(r.field,i))}return n||null}function Ju(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&go(e,t,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof Fu&&t instanceof Fu||e instanceof qu&&t instanceof qu?go(e.elements,t.elements,Xa):e instanceof ju&&t instanceof ju?Xa(e.gt,t.gt):e instanceof Mu&&t instanceof Mu}(e.transform,t.transform)}(e,t))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class Zu extends Wu{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class el extends Wu{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}getFieldMask(){return this.fieldMask}}function tl(e){const t=new Map;return e.fieldMask.fields.forEach(n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}}),t}function nl(e,t,n){const r=new Map;Js(e.length===n.length);for(let i=0;i<n.length;i++){const s=e[i],o=s.transform,a=t.data.field(s.field);r.set(s.field,Ru(o,a,n[i]))}return r}function rl(e,t,n){const r=new Map;for(const i of e){const e=i.transform,s=n.data.field(i.field);r.set(i.field,Pu(e,s,t))}return r}class il extends Wu{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class sl extends Wu{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class ol{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){const r=this.mutations[t];r.key.isEqual(e.key)&&Hu(r,e,n[t])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=Yu(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=Yu(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=bu();return this.mutations.forEach(r=>{const i=e.get(r.key),s=i.overlayedDocument;let o=this.applyToLocalView(s,i.mutatedFields);o=t.has(r.key)?null:o;const a=Qu(s,o);null!==a&&n.set(r.key,a),s.isValidDocument()||s.convertToNoDocument(_o.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Tu())}isEqual(e){return this.batchId===e.batchId&&go(this.mutations,e.mutations,(e,t)=>Ju(e,t))&&go(this.baseMutations,e.baseMutations,(e,t)=>Ju(e,t))}}class al{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Js(e.mutations.length===n.length);let r=Eu;const i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new al(e,t,n,r)}}class cl{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 ul{constructor(e,t){this.count=e,this.unchangedNames=t}}var ll,hl;function dl(e){switch(e){default:return Xs();case eo.CANCELLED:case eo.UNKNOWN:case eo.DEADLINE_EXCEEDED:case eo.RESOURCE_EXHAUSTED:case eo.INTERNAL:case eo.UNAVAILABLE:case eo.UNAUTHENTICATED:return!1;case eo.INVALID_ARGUMENT:case eo.NOT_FOUND:case eo.ALREADY_EXISTS:case eo.PERMISSION_DENIED:case eo.FAILED_PRECONDITION:case eo.ABORTED:case eo.OUT_OF_RANGE:case eo.UNIMPLEMENTED:case eo.DATA_LOSS:return!0}}function fl(e){if(void 0===e)return Qs("GRPC error has no .code"),eo.UNKNOWN;switch(e){case ll.OK:return eo.OK;case ll.CANCELLED:return eo.CANCELLED;case ll.UNKNOWN:return eo.UNKNOWN;case ll.DEADLINE_EXCEEDED:return eo.DEADLINE_EXCEEDED;case ll.RESOURCE_EXHAUSTED:return eo.RESOURCE_EXHAUSTED;case ll.INTERNAL:return eo.INTERNAL;case ll.UNAVAILABLE:return eo.UNAVAILABLE;case ll.UNAUTHENTICATED:return eo.UNAUTHENTICATED;case ll.INVALID_ARGUMENT:return eo.INVALID_ARGUMENT;case ll.NOT_FOUND:return eo.NOT_FOUND;case ll.ALREADY_EXISTS:return eo.ALREADY_EXISTS;case ll.PERMISSION_DENIED:return eo.PERMISSION_DENIED;case ll.FAILED_PRECONDITION:return eo.FAILED_PRECONDITION;case ll.ABORTED:return eo.ABORTED;case ll.OUT_OF_RANGE:return eo.OUT_OF_RANGE;case ll.UNIMPLEMENTED:return eo.UNIMPLEMENTED;case ll.DATA_LOSS:return eo.DATA_LOSS;default:return Xs()}}(hl=ll||(ll={}))[hl.OK=0]="OK",hl[hl.CANCELLED=1]="CANCELLED",hl[hl.UNKNOWN=2]="UNKNOWN",hl[hl.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",hl[hl.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",hl[hl.NOT_FOUND=5]="NOT_FOUND",hl[hl.ALREADY_EXISTS=6]="ALREADY_EXISTS",hl[hl.PERMISSION_DENIED=7]="PERMISSION_DENIED",hl[hl.UNAUTHENTICATED=16]="UNAUTHENTICATED",hl[hl.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",hl[hl.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",hl[hl.ABORTED=10]="ABORTED",hl[hl.OUT_OF_RANGE=11]="OUT_OF_RANGE",hl[hl.UNIMPLEMENTED=12]="UNIMPLEMENTED",hl[hl.INTERNAL=13]="INTERNAL",hl[hl.UNAVAILABLE=14]="UNAVAILABLE",hl[hl.DATA_LOSS=15]="DATA_LOSS";class pl{constructor(){this.onExistenceFilterMismatchCallbacks=new Map}static get instance(){return gl}static getOrCreateInstance(){return null===gl&&(gl=new pl),gl}onExistenceFilterMismatch(e){const t=Symbol();return this.onExistenceFilterMismatchCallbacks.set(t,e),()=>this.onExistenceFilterMismatchCallbacks.delete(t)}notifyOnExistenceFilterMismatch(e){this.onExistenceFilterMismatchCallbacks.forEach(t=>t(e))}}let gl=null;function ml(){return new TextEncoder}const yl=new Bs([4294967295,4294967295],0);function _l(e){const t=ml().encode(e),n=new js;return n.update(t),new Uint8Array(n.digest())}function vl(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Bs([n,r],0),new Bs([i,s],0)]}class wl{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new bl(`Invalid padding: ${t}`);if(n<0)throw new bl(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new bl(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new bl(`Invalid padding when bitmap length is 0: ${t}`);this.It=8*e.length-t,this.Tt=Bs.fromNumber(this.It)}Et(e,t,n){let r=e.add(t.multiply(Bs.fromNumber(n)));return 1===r.compare(yl)&&(r=new Bs([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Tt).toNumber()}At(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}vt(e){if(0===this.It)return!1;const t=_l(e),[n,r]=vl(t);for(let e=0;e<this.hashCount;e++){const t=this.Et(n,r,e);if(!this.At(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new wl(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(e){if(0===this.It)return;const t=_l(e),[n,r]=vl(t);for(let e=0;e<this.hashCount;e++){const t=this.Et(n,r,e);this.Rt(t)}}Rt(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class bl extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Il{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,n){const r=new Map;return r.set(e,El.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Il(_o.min(),r,new Da(po),mu(),Tu())}}class El{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,n){return new El(n,t,Tu(),Tu(),Tu())}}class Cl{constructor(e,t,n,r){this.Pt=e,this.removedTargetIds=t,this.key=n,this.bt=r}}class Tl{constructor(e,t){this.targetId=e,this.Vt=t}}class Sl{constructor(e,t,n=qa.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class xl{constructor(){this.St=0,this.Dt=Dl(),this.Ct=qa.EMPTY_BYTE_STRING,this.xt=!1,this.Nt=!0}get current(){return this.xt}get resumeToken(){return this.Ct}get kt(){return 0!==this.St}get Mt(){return this.Nt}$t(e){e.approximateByteSize()>0&&(this.Nt=!0,this.Ct=e)}Ot(){let e=Tu(),t=Tu(),n=Tu();return this.Dt.forEach((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:Xs()}}),new El(this.Ct,this.xt,e,t,n)}Ft(){this.Nt=!1,this.Dt=Dl()}Bt(e,t){this.Nt=!0,this.Dt=this.Dt.insert(e,t)}Lt(e){this.Nt=!0,this.Dt=this.Dt.remove(e)}qt(){this.St+=1}Ut(){this.St-=1}Kt(){this.Nt=!0,this.xt=!0}}class kl{constructor(e){this.Gt=e,this.Qt=new Map,this.jt=mu(),this.zt=Nl(),this.Wt=new Da(po)}Ht(e){for(const t of e.Pt)e.bt&&e.bt.isFoundDocument()?this.Jt(t,e.bt):this.Yt(t,e.key,e.bt);for(const t of e.removedTargetIds)this.Yt(t,e.key,e.bt)}Xt(e){this.forEachTarget(e,t=>{const n=this.Zt(t);switch(e.state){case 0:this.te(t)&&n.$t(e.resumeToken);break;case 1:n.Ut(),n.kt||n.Ft(),n.$t(e.resumeToken);break;case 2:n.Ut(),n.kt||this.removeTarget(t);break;case 3:this.te(t)&&(n.Kt(),n.$t(e.resumeToken));break;case 4:this.te(t)&&(this.ee(t),n.$t(e.resumeToken));break;default:Xs()}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Qt.forEach((e,n)=>{this.te(n)&&t(n)})}ne(e){var t;const n=e.targetId,r=e.Vt.count,i=this.se(n);if(i){const s=i.target;if(Kc(s))if(0===r){const e=new Eo(s.path);this.Yt(n,e,yc.newNoDocument(e,_o.min()))}else Js(1===r);else{const i=this.ie(n);if(i!==r){const r=this.re(e,i);if(0!==r){this.ee(n);const e=2===r?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Wt=this.Wt.insert(n,e)}null===(t=pl.instance)||void 0===t||t.notifyOnExistenceFilterMismatch(function(e,t,n){var r,i,s,o,a,c;const u={localCacheCount:t,existenceFilterCount:n.count},l=n.unchangedNames;return l&&(u.bloomFilter={applied:0===e,hashCount:null!==(r=null==l?void 0:l.hashCount)&&void 0!==r?r:0,bitmapLength:null!==(o=null===(s=null===(i=null==l?void 0:l.bits)||void 0===i?void 0:i.bitmap)||void 0===s?void 0:s.length)&&void 0!==o?o:0,padding:null!==(c=null===(a=null==l?void 0:l.bits)||void 0===a?void 0:a.padding)&&void 0!==c?c:0}),u}(r,i,e.Vt))}}}}re(e,t){const{unchangedNames:n,count:r}=e.Vt;if(!n||!n.bits)return 1;const{bits:{bitmap:i="",padding:s=0},hashCount:o=0}=n;let a,c;try{a=Ua(i).toUint8Array()}catch(e){if(e instanceof La)return Hs("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),1;throw e}try{c=new wl(a,s,o)}catch(e){return Hs(e instanceof bl?"BloomFilter error: ":"Applying bloom filter failed: ",e),1}return 0===c.It?1:r!==t-this.oe(e.targetId,c)?2:0}oe(e,t){const n=this.Gt.getRemoteKeysForTarget(e);let r=0;return n.forEach(n=>{const i=this.Gt.ue(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;t.vt(s)||(this.Yt(e,n,null),r++)}),r}ce(e){const t=new Map;this.Qt.forEach((n,r)=>{const i=this.se(r);if(i){if(n.current&&Kc(i.target)){const t=new Eo(i.target.path);null!==this.jt.get(t)||this.ae(r,t)||this.Yt(r,t,yc.newNoDocument(t,e))}n.Mt&&(t.set(r,n.Ot()),n.Ft())}});let n=Tu();this.zt.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{const t=this.se(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.jt.forEach((t,n)=>n.setReadTime(e));const r=new Il(e,t,this.Wt,this.jt,n);return this.jt=mu(),this.zt=Nl(),this.Wt=new Da(po),r}Jt(e,t){if(!this.te(e))return;const n=this.ae(e,t.key)?2:0;this.Zt(e).Bt(t.key,n),this.jt=this.jt.insert(t.key,t),this.zt=this.zt.insert(t.key,this.he(t.key).add(e))}Yt(e,t,n){if(!this.te(e))return;const r=this.Zt(e);this.ae(e,t)?r.Bt(t,1):r.Lt(t),this.zt=this.zt.insert(t,this.he(t).delete(e)),n&&(this.jt=this.jt.insert(t,n))}removeTarget(e){this.Qt.delete(e)}ie(e){const t=this.Zt(e).Ot();return this.Gt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}qt(e){this.Zt(e).qt()}Zt(e){let t=this.Qt.get(e);return t||(t=new xl,this.Qt.set(e,t)),t}he(e){let t=this.zt.get(e);return t||(t=new Ra(po),this.zt=this.zt.insert(e,t)),t}te(e){const t=null!==this.se(e);return t||Ws("WatchChangeAggregator","Detected inactive target",e),t}se(e){const t=this.Qt.get(e);return t&&t.kt?null:this.Gt.le(e)}ee(e){this.Qt.set(e,new xl),this.Gt.getRemoteKeysForTarget(e).forEach(t=>{this.Yt(e,t,null)})}ae(e,t){return this.Gt.getRemoteKeysForTarget(e).has(t)}}function Nl(){return new Da(Eo.comparator)}function Dl(){return new Da(Eo.comparator)}const Al={asc:"ASCENDING",desc:"DESCENDING"},Pl={"<":"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"},Rl={and:"AND",or:"OR"};class Ol{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Ml(e,t){return e.useProto3Json||Ho(t)?t:{value:t}}function Fl(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Ll(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function ql(e,t){return Fl(e,t.toTimestamp())}function Vl(e){return Js(!!e),_o.fromTimestamp(function(e){const t=ja(e);return new yo(t.seconds,t.nanos)}(e))}function jl(e,t){return function(e){return new wo(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function Bl(e){const t=wo.fromString(e);return Js(uh(t)),t}function Ul(e,t){return jl(e.databaseId,t.path)}function zl(e,t){const n=Bl(t);if(n.get(1)!==e.databaseId.projectId)throw new to(eo.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 to(eo.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new Eo(Wl(n))}function $l(e,t){return jl(e.databaseId,t)}function Gl(e){const t=Bl(e);return 4===t.length?wo.emptyPath():Wl(t)}function Kl(e){return new wo(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Wl(e){return Js(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function Ql(e,t,n){return{name:Ul(e,t),fields:n.value.mapValue.fields}}function Hl(e,t,n){const r=zl(e,t.name),i=Vl(t.updateTime),s=t.createTime?Vl(t.createTime):_o.min(),o=new gc({mapValue:{fields:t.fields}}),a=yc.newFoundDocument(r,i,s,o);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Yl(e,t){let n;if(t instanceof Zu)n={update:Ql(e,t.key,t.value)};else if(t instanceof il)n={delete:Ul(e,t.key)};else if(t instanceof el)n={update:Ql(e,t.key,t.data),updateMask:ch(t.fieldMask)};else{if(!(t instanceof sl))return Xs();n={verify:Ul(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e,t){const n=t.transform;if(n instanceof Mu)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Fu)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof qu)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof ju)return{fieldPath:t.field.canonicalString(),increment:n.gt};throw Xs()}(0,e))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:ql(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Xs()}(e,t.precondition)),n}function Xl(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?Gu.updateTime(Vl(e.updateTime)):void 0!==e.exists?Gu.exists(e.exists):Gu.none()}(t.currentDocument):Gu.none(),r=t.updateTransforms?t.updateTransforms.map(t=>function(e,t){let n=null;if("setToServerValue"in t)Js("REQUEST_TIME"===t.setToServerValue),n=new Mu;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new Fu(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new qu(e)}else"increment"in t?n=new ju(e,t.increment):Xs();const r=Io.fromServerFormat(t.fieldPath);return new zu(r,n)}(e,t)):[];if(t.update){t.update.name;const i=zl(e,t.update.name),s=new gc({mapValue:{fields:t.update.fields}});if(t.updateMask){const e=function(e){const t=e.fieldPaths||[];return new Fa(t.map(e=>Io.fromServerFormat(e)))}(t.updateMask);return new el(i,s,e,n,r)}return new Zu(i,s,n,r)}if(t.delete){const r=zl(e,t.delete);return new il(r,n)}if(t.verify){const r=zl(e,t.verify);return new sl(r,n)}return Xs()}function Jl(e,t){return{documents:[$l(e,t.path)]}}function Zl(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=$l(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=$l(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const i=function(e){if(0!==e.length)return ah(Tc.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);const s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:sh(e.field),direction:nh(e.dir)}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);const o=Ml(e,t.limit);var a;return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt={before:(a=t.startAt).inclusive,values:a.position}),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function eh(e){let t=Gl(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){Js(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=function(e){const t=th(e);return t instanceof Tc&&kc(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new bc(oh(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,Ho(t)?null:t}(n.limit));let c=null;n.startAt&&(c=function(e){const t=!!e.before,n=e.values||[];return new _c(n,t)}(n.startAt));let u=null;return n.endAt&&(u=function(e){const t=!e.before,n=e.values||[];return new _c(n,t)}(n.endAt)),Xc(t,i,o,s,a,"F",c,u)}function th(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=oh(e.unaryFilter.field);return Cc.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=oh(e.unaryFilter.field);return Cc.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=oh(e.unaryFilter.field);return Cc.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=oh(e.unaryFilter.field);return Cc.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Xs()}}(e):void 0!==e.fieldFilter?function(e){return Cc.create(oh(e.fieldFilter.field),function(e){switch(e){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 Xs()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return Tc.create(e.compositeFilter.filters.map(e=>th(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Xs()}}(e.compositeFilter.op))}(e):Xs()}function nh(e){return Al[e]}function rh(e){return Pl[e]}function ih(e){return Rl[e]}function sh(e){return{fieldPath:e.canonicalString()}}function oh(e){return Io.fromServerFormat(e.fieldPath)}function ah(e){return e instanceof Cc?function(e){if("=="===e.op){if(ac(e.value))return{unaryFilter:{field:sh(e.field),op:"IS_NAN"}};if(oc(e.value))return{unaryFilter:{field:sh(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(ac(e.value))return{unaryFilter:{field:sh(e.field),op:"IS_NOT_NAN"}};if(oc(e.value))return{unaryFilter:{field:sh(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:sh(e.field),op:rh(e.op),value:e.value}}}(e):e instanceof Tc?function(e){const t=e.getFilters().map(e=>ah(e));return 1===t.length?t[0]:{compositeFilter:{op:ih(e.op),filters:t}}}(e):Xs()}function ch(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}function uh(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class lh{constructor(e,t,n,r,i=_o.min(),s=_o.min(),o=qa.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new lh(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new lh(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new lh(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new lh(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class hh{constructor(e){this.fe=e}}function dh(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:fh(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:Ul(e,t.key),fields:t.data.value.mapValue.fields,updateTime:Fl(e,t.version.toTimestamp()),createTime:Fl(e,t.createTime.toTimestamp())}}(e.fe,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:ph(t.version)};else{if(!t.isUnknownDocument())return Xs();r.unknownDocument={path:n.path.toArray(),version:ph(t.version)}}return r}function fh(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function ph(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function gh(e){const t=new yo(e.seconds,e.nanoseconds);return _o.fromTimestamp(t)}function mh(e,t){const n=(t.baseMutations||[]).map(t=>Xl(e.fe,t));for(let e=0;e<t.mutations.length-1;++e){const n=t.mutations[e];if(e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform){const r=t.mutations[e+1];n.updateTransforms=r.transform.fieldTransforms,t.mutations.splice(e+1,1),++e}}const r=t.mutations.map(t=>Xl(e.fe,t)),i=yo.fromMillis(t.localWriteTimeMs);return new ol(t.batchId,i,n,r)}function yh(e){const t=gh(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?gh(e.lastLimboFreeSnapshotVersion):_o.min();let r;var i;return void 0!==e.query.documents?(Js(1===(i=e.query).documents.length),r=iu(Jc(Gl(i.documents[0])))):r=function(e){return iu(eh(e))}(e.query),new lh(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,qa.fromBase64String(e.resumeToken))}function _h(e,t){const n=ph(t.snapshotVersion),r=ph(t.lastLimboFreeSnapshotVersion);let i;i=Kc(t.target)?Jl(e.fe,t.target):Zl(e.fe,t.target);const s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:$c(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function vh(e){const t=eh({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?ou(t,t.limit,"L"):t}function wh(e,t){return new cl(t.largestBatchId,Xl(e.fe,t.overlayMutation))}function bh(e,t){const n=t.path.lastSegment();return[e,Jo(t.path.popLast()),n]}function Ih(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:ph(r.readTime),documentKey:Jo(r.documentKey.path),largestBatchId:r.largestBatchId}}class Eh{getBundleMetadata(e,t){return Ch(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:gh(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return Ch(e).put({bundleId:(n=t).id,createTime:ph(Vl(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return Th(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:vh(t.bundledQuery),readTime:gh(t.readTime)};var t})}saveNamedQuery(e,t){return Th(e).put(function(e){return{name:e.name,readTime:ph(Vl(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function Ch(e){return Sa(e,"bundles")}function Th(e){return Sa(e,"namedQueries")}class Sh{constructor(e,t){this.serializer=e,this.userId=t}static de(e,t){const n=t.uid||"";return new Sh(e,n)}getOverlay(e,t){return xh(e).get(bh(this.userId,t)).next(e=>e?wh(this.serializer,e):null)}getOverlays(e,t){const n=wu();return Fo.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){const r=[];return n.forEach((n,i)=>{const s=new cl(t,i);r.push(this.we(e,s))}),Fo.waitFor(r)}removeOverlaysForBatchId(e,t,n){const r=new Set;t.forEach(e=>r.add(Jo(e.getCollectionPath())));const i=[];return r.forEach(t=>{const r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(xh(e).J("collectionPathOverlayIndex",r))}),Fo.waitFor(i)}getOverlaysForCollection(e,t,n){const r=wu(),i=Jo(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return xh(e).j("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=wh(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){const i=wu();let s;const o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return xh(e).X({index:"collectionGroupOverlayIndex",range:o},(e,t,n)=>{const o=wh(this.serializer,t);i.size()<r||o.largestBatchId===s?(i.set(o.getKey(),o),s=o.largestBatchId):n.done()}).next(()=>i)}we(e,t){return xh(e).put(function(e,t,n){const[r,i,s]=bh(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Yl(e.fe,n.mutation)}}(this.serializer,this.userId,t))}}function xh(e){return Sa(e,"documentOverlays")}class kh{constructor(){}_e(e,t){this.me(e,t),t.ge()}me(e,t){if("nullValue"in e)this.ye(t,5);else if("booleanValue"in e)this.ye(t,10),t.pe(e.booleanValue?1:0);else if("integerValue"in e)this.ye(t,15),t.pe(Ba(e.integerValue));else if("doubleValue"in e){const n=Ba(e.doubleValue);isNaN(n)?this.ye(t,13):(this.ye(t,15),Yo(n)?t.pe(0):t.pe(n))}else if("timestampValue"in e){const n=e.timestampValue;this.ye(t,20),"string"==typeof n?t.Ie(n):(t.Ie(`${n.seconds||""}`),t.pe(n.nanos||0))}else if("stringValue"in e)this.Te(e.stringValue,t),this.Ee(t);else if("bytesValue"in e)this.ye(t,30),t.Ae(Ua(e.bytesValue)),this.Ee(t);else if("referenceValue"in e)this.ve(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.ye(t,45),t.pe(n.latitude||0),t.pe(n.longitude||0)}else"mapValue"in e?lc(e)?this.ye(t,Number.MAX_SAFE_INTEGER):(this.Re(e.mapValue,t),this.Ee(t)):"arrayValue"in e?(this.Pe(e.arrayValue,t),this.Ee(t)):Xs()}Te(e,t){this.ye(t,25),this.be(e,t)}be(e,t){t.Ie(e)}Re(e,t){const n=e.fields||{};this.ye(t,55);for(const e of Object.keys(n))this.Te(e,t),this.me(n[e],t)}Pe(e,t){const n=e.values||[];this.ye(t,50);for(const e of n)this.me(e,t)}ve(e,t){this.ye(t,37),Eo.fromName(e).path.forEach(e=>{this.ye(t,60),this.be(e,t)})}ye(e,t){e.pe(t)}Ee(e){e.pe(2)}}function Nh(e){if(0===e)return 8;let t=0;return!(e>>4)&&(t+=4,e<<=4),!(e>>6)&&(t+=2,e<<=2),!(e>>7)&&(t+=1),t}function Dh(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=Nh(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}kh.Ve=new kh;class Ah{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Se(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.De(n.value),n=t.next();this.Ce()}xe(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ne(n.value),n=t.next();this.ke()}Me(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.De(e);else if(e<2048)this.De(960|e>>>6),this.De(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.De(480|e>>>12),this.De(128|63&e>>>6),this.De(128|63&e);else{const e=t.codePointAt(0);this.De(240|e>>>18),this.De(128|63&e>>>12),this.De(128|63&e>>>6),this.De(128|63&e)}}this.Ce()}$e(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ne(e);else if(e<2048)this.Ne(960|e>>>6),this.Ne(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ne(480|e>>>12),this.Ne(128|63&e>>>6),this.Ne(128|63&e);else{const e=t.codePointAt(0);this.Ne(240|e>>>18),this.Ne(128|63&e>>>12),this.Ne(128|63&e>>>6),this.Ne(128|63&e)}}this.ke()}Oe(e){const t=this.Fe(e),n=Dh(t);this.Be(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}Le(e){const t=this.Fe(e),n=Dh(t);this.Be(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}qe(){this.Ue(255),this.Ue(255)}Ke(){this.Ge(255),this.Ge(255)}reset(){this.position=0}seed(e){this.Be(e.length),this.buffer.set(e,this.position),this.position+=e.length}Qe(){return this.buffer.slice(0,this.position)}Fe(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=!!(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=n?255:0;return t}De(e){const t=255&e;0===t?(this.Ue(0),this.Ue(255)):255===t?(this.Ue(255),this.Ue(0)):this.Ue(t)}Ne(e){const t=255&e;0===t?(this.Ge(0),this.Ge(255)):255===t?(this.Ge(255),this.Ge(0)):this.Ge(e)}Ce(){this.Ue(0),this.Ue(1)}ke(){this.Ge(0),this.Ge(1)}Ue(e){this.Be(1),this.buffer[this.position++]=e}Ge(e){this.Be(1),this.buffer[this.position++]=~e}Be(e){const t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);const r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class Ph{constructor(e){this.je=e}Ae(e){this.je.Se(e)}Ie(e){this.je.Me(e)}pe(e){this.je.Oe(e)}ge(){this.je.qe()}}class Rh{constructor(e){this.je=e}Ae(e){this.je.xe(e)}Ie(e){this.je.$e(e)}pe(e){this.je.Le(e)}ge(){this.je.Ke()}}class Oh{constructor(){this.je=new Ah,this.ze=new Ph(this.je),this.We=new Rh(this.je)}seed(e){this.je.seed(e)}He(e){return 0===e?this.ze:this.We}Qe(){return this.je.Qe()}reset(){this.je.reset()}}class Mh{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Je(){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 Mh(this.indexId,this.documentKey,this.arrayValue,n)}}function Fh(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Lh(e.arrayValue,t.arrayValue),0!==n?n:(n=Lh(e.directionalValue,t.directionalValue),0!==n?n:Eo.comparator(e.documentKey,t.documentKey)))}function Lh(e,t){for(let n=0;n<e.length&&n<t.length;++n){const r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}class qh{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ye=e.orderBy,this.Xe=[];for(const t of e.filters){const e=t;e.isInequality()?this.Ze=e:this.Xe.push(e)}}tn(e){Js(e.collectionGroup===this.collectionId);const t=To(e);if(void 0!==t&&!this.en(t))return!1;const n=So(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.en(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.Ze){if(!r.has(this.Ze.field.canonicalString())){const e=n[i];if(!this.nn(this.Ze,e)||!this.sn(this.Ye[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Ye.length||!this.sn(this.Ye[s++],e))return!1}return!0}en(e){for(const t of this.Xe)if(this.nn(t,e))return!0;return!1}nn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;const n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function Vh(e){var t,n;if(Js(e instanceof Cc||e instanceof Tc),e instanceof Cc){if(e instanceof Vc){const r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map(t=>Cc.create(e.field,"==",t)))||[];return Tc.create(r,"or")}return e}const r=e.filters.map(e=>Vh(e));return Tc.create(r,e.op)}function jh(e){if(0===e.getFilters().length)return[];const t=$h(Vh(e));return Js(zh(t)),Bh(t)||Uh(t)?[t]:t.getFilters()}function Bh(e){return e instanceof Cc}function Uh(e){return e instanceof Tc&&kc(e)}function zh(e){return Bh(e)||Uh(e)||function(e){if(e instanceof Tc&&xc(e)){for(const t of e.getFilters())if(!Bh(t)&&!Uh(t))return!1;return!0}return!1}(e)}function $h(e){if(Js(e instanceof Cc||e instanceof Tc),e instanceof Cc)return e;if(1===e.filters.length)return $h(e.filters[0]);const t=e.filters.map(e=>$h(e));let n=Tc.create(t,e.op);return n=Wh(n),zh(n)?n:(Js(n instanceof Tc),Js(Sc(n)),Js(n.filters.length>1),n.filters.reduce((e,t)=>Gh(e,t)))}function Gh(e,t){let n;return Js(e instanceof Cc||e instanceof Tc),Js(t instanceof Cc||t instanceof Tc),n=e instanceof Cc?t instanceof Cc?function(e,t){return Tc.create([e,t],"and")}(e,t):Kh(e,t):t instanceof Cc?Kh(t,e):function(e,t){if(Js(e.filters.length>0&&t.filters.length>0),Sc(e)&&Sc(t))return Pc(e,t.getFilters());const n=xc(e)?e:t,r=xc(e)?t:e,i=n.filters.map(e=>Gh(e,r));return Tc.create(i,"or")}(e,t),Wh(n)}function Kh(e,t){if(Sc(t))return Pc(t,e.getFilters());{const n=t.filters.map(t=>Gh(e,t));return Tc.create(n,"or")}}function Wh(e){if(Js(e instanceof Cc||e instanceof Tc),e instanceof Cc)return e;const t=e.getFilters();if(1===t.length)return Wh(t[0]);if(Nc(e))return e;const n=t.map(e=>Wh(e)),r=[];return n.forEach(t=>{t instanceof Cc?r.push(t):t instanceof Tc&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:Tc.create(r,e.op)}class Qh{constructor(){this.rn=new Hh}addToCollectionParentIndex(e,t){return this.rn.add(t),Fo.resolve()}getCollectionParents(e,t){return Fo.resolve(this.rn.getEntries(t))}addFieldIndex(e,t){return Fo.resolve()}deleteFieldIndex(e,t){return Fo.resolve()}getDocumentsMatchingTarget(e,t){return Fo.resolve(null)}getIndexType(e,t){return Fo.resolve(0)}getFieldIndexes(e,t){return Fo.resolve([])}getNextCollectionGroupToUpdate(e){return Fo.resolve(null)}getMinOffset(e,t){return Fo.resolve(Ao.min())}getMinOffsetFromCollectionGroup(e,t){return Fo.resolve(Ao.min())}updateCollectionGroup(e,t,n){return Fo.resolve()}updateIndexEntries(e,t){return Fo.resolve()}}class Hh{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Ra(wo.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 Ra(wo.comparator)).toArray()}}const Yh=new Uint8Array(0);class Xh{constructor(e,t){this.user=e,this.databaseId=t,this.on=new Hh,this.un=new pu(e=>$c(e),(e,t)=>Gc(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.on.has(t)){const n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.on.add(t)});const i={collectionId:n,parent:Jo(r)};return Jh(e).put(i)}return Fo.resolve()}getCollectionParents(e,t){const n=[],r=IDBKeyRange.bound([t,""],[mo(t),""],!1,!0);return Jh(e).j(r).next(e=>{for(const r of e){if(r.collectionId!==t)break;n.push(ta(r.parent))}return n})}addFieldIndex(e,t){const n=ed(e),r=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])}}(t);delete r.indexId;const i=n.add(r);if(t.indexState){const n=td(e);return i.next(e=>{n.put(Ih(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=ed(e),r=td(e),i=Zh(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,t){const n=Zh(e);let r=!0;const i=new Map;return Fo.forEach(this.cn(t),t=>this.an(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>{if(r){let e=Tu();const r=[];return Fo.forEach(i,(i,s)=>{var o;Ws("IndexedDbIndexManager",`Using index ${o=i,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${$c(t)}`);const a=function(e,t){const n=To(t);if(void 0===n)return null;for(const t of Wc(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),c=function(e,t){const n=new Map;for(const r of So(t))for(const t of Wc(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}(s,i),u=function(e,t){const n=[];let r=!0;for(const i of So(t)){const t=0===i.kind?Qc(e,i.fieldPath,e.startAt):Hc(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new _c(n,r)}(s,i),l=function(e,t){const n=[];let r=!0;for(const i of So(t)){const t=0===i.kind?Hc(e,i.fieldPath,e.endAt):Qc(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new _c(n,r)}(s,i),h=this.hn(i,s,u),d=this.hn(i,s,l),f=this.ln(i,s,c),p=this.fn(i.indexId,a,h,u.inclusive,d,l.inclusive,f);return Fo.forEach(p,i=>n.H(i,t.limit).next(t=>{t.forEach(t=>{const n=Eo.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return Fo.resolve(null)})}cn(e){let t=this.un.get(e);return t||(t=0===e.filters.length?[e]:jh(Tc.create(e.filters,"and")).map(t=>zc(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.un.set(e,t),t)}fn(e,t,n,r,i,s,o){const a=(null!=t?t.length:1)*Math.max(n.length,i.length),c=a/(null!=t?t.length:1),u=[];for(let l=0;l<a;++l){const a=t?this.dn(t[l/c]):Yh,h=this.wn(e,a,n[l%c],r),d=this._n(e,a,i[l%c],s),f=o.map(t=>this.wn(e,a,t,!0));u.push(...this.createRange(h,d,f))}return u}wn(e,t,n,r){const i=new Mh(e,Eo.empty(),t,n);return r?i:i.Je()}_n(e,t,n,r){const i=new Mh(e,Eo.empty(),t,n);return r?i.Je():i}an(e,t){const n=new qh(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{let t=null;for(const r of e)n.tn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let n=2;const r=this.cn(t);return Fo.forEach(r,t=>this.an(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new Ra(Io.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())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(()=>function(e){return null!==e.limit}(t)&&r.length>1&&2===n?1:n)}mn(e,t){const n=new Oh;for(const r of So(e)){const e=t.data.field(r.fieldPath);if(null==e)return null;const i=n.He(r.kind);kh.Ve._e(e,i)}return n.Qe()}dn(e){const t=new Oh;return kh.Ve._e(e,t.He(0)),t.Qe()}gn(e,t){const n=new Oh;return kh.Ve._e(rc(this.databaseId,t),n.He(function(e){const t=So(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Qe()}ln(e,t,n){if(null===n)return[];let r=[];r.push(new Oh);let i=0;for(const s of So(e)){const e=n[i++];for(const n of r)if(this.yn(t,s.fieldPath)&&sc(e))r=this.pn(r,s,e);else{const t=n.He(s.kind);kh.Ve._e(e,t)}}return this.In(r)}hn(e,t,n){return this.ln(e,t,n.position)}In(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Qe();return t}pn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new Oh;r.seed(n.Qe()),kh.Ve._e(e,r.He(t.kind)),i.push(r)}return i}yn(e,t){return!!e.filters.find(e=>e instanceof Cc&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=ed(e),r=td(e);return(t?n.j("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.j()).next(e=>{const t=[];return Fo.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){const n=t?new ko(t.sequenceNumber,new Ao(gh(t.readTime),new Eo(ta(t.documentKey)),t.largestBatchId)):ko.empty(),r=e.fields.map(([e,t])=>new xo(Io.fromServerFormat(e),t));return new Co(e.indexId,e.collectionGroup,r,n)}(e,n))})).next(()=>t)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{const n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:po(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){const r=ed(e),i=td(e);return this.Tn(e).next(e=>r.j("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(t=>Fo.forEach(t,t=>i.put(Ih(t.indexId,this.user,e,n)))))}updateIndexEntries(e,t){const n=new Map;return Fo.forEach(t,(t,r)=>{const i=n.get(t.collectionGroup);return(i?Fo.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),Fo.forEach(i,n=>this.En(e,t,n).next(t=>{const i=this.An(r,n);return t.isEqual(i)?Fo.resolve():this.vn(e,r,n,t,i)}))))})}Rn(e,t,n,r){return Zh(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.gn(n,t.key),documentKey:t.key.path.toArray()})}Pn(e,t,n,r){return Zh(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.gn(n,t.key),t.key.path.toArray()])}En(e,t,n){const r=Zh(e);let i=new Ra(Fh);return r.X({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},(e,r)=>{i=i.add(new Mh(n.indexId,t,r.arrayValue,r.directionalValue))}).next(()=>i)}An(e,t){let n=new Ra(Fh);const r=this.mn(t,e);if(null==r)return n;const i=To(t);if(null!=i){const s=e.data.field(i.fieldPath);if(sc(s))for(const i of s.arrayValue.values||[])n=n.add(new Mh(t.indexId,e.key,this.dn(i),r))}else n=n.add(new Mh(t.indexId,e.key,Yh,r));return n}vn(e,t,n,r,i){Ws("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);const s=[];return function(e,t,n,r,i){const s=e.getIterator(),o=t.getIterator();let a=Ma(s),c=Ma(o);for(;a||c;){let e=!1,t=!1;if(a&&c){const r=n(a,c);r<0?t=!0:r>0&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(c),c=Ma(o)):t?(i(a),a=Ma(s)):(a=Ma(s),c=Ma(o))}}(r,i,Fh,r=>{s.push(this.Rn(e,t,n,r))},r=>{s.push(this.Pn(e,t,n,r))}),Fo.waitFor(s)}Tn(e){let t=1;return td(e).X({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,n,r)=>{r.done(),t=n.sequenceNumber+1}).next(()=>t)}createRange(e,t,n){n=n.sort((e,t)=>Fh(e,t)).filter((e,t,n)=>!t||0!==Fh(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=Fh(i,e),s=Fh(i,t);if(0===n)r[0]=e.Je();else if(n>0&&s<0)r.push(i),r.push(i.Je());else if(s>0)break}r.push(t);const i=[];for(let e=0;e<r.length;e+=2){if(this.bn(r[e],r[e+1]))return[];const t=[r[e].indexId,this.uid,r[e].arrayValue,r[e].directionalValue,Yh,[]],n=[r[e+1].indexId,this.uid,r[e+1].arrayValue,r[e+1].directionalValue,Yh,[]];i.push(IDBKeyRange.bound(t,n))}return i}bn(e,t){return Fh(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(nd)}getMinOffset(e,t){return Fo.mapArray(this.cn(t),t=>this.an(e,t).next(e=>e||Xs())).next(nd)}}function Jh(e){return Sa(e,"collectionParents")}function Zh(e){return Sa(e,"indexEntries")}function ed(e){return Sa(e,"indexConfiguration")}function td(e){return Sa(e,"indexState")}function nd(e){Js(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){const i=e[r].indexState.offset;Po(i,t)<0&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new Ao(t.readTime,t.documentKey,n)}const rd={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class id{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new id(e,id.DEFAULT_COLLECTION_PERCENTILE,id.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function sd(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.X({range:o},(e,t,n)=>(a++,n.delete()));s.push(c.next(()=>{Js(1===a)}));const u=[];for(const e of n.mutations){const r=ia(t,e.key.path,n.batchId);s.push(i.delete(r)),u.push(e.key)}return Fo.waitFor(s).next(()=>u)}function od(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 Xs();t=e.noDocument}return JSON.stringify(t).length}id.DEFAULT_COLLECTION_PERCENTILE=10,id.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,id.DEFAULT=new id(41943040,id.DEFAULT_COLLECTION_PERCENTILE,id.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),id.DISABLED=new id(-1,0,0);class ad{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Vn={}}static de(e,t,n,r){Js(""!==e.uid);const i=e.isAuthenticated()?e.uid:"";return new ad(i,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return ud(e).X({index:"userMutationsIndex",range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){const i=ld(e),s=ud(e);return s.add({}).next(o=>{Js("number"==typeof o);const a=new ol(o,t,n,r),c=function(e,t,n){const r=n.baseMutations.map(t=>Yl(e.fe,t)),i=n.mutations.map(t=>Yl(e.fe,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,a),u=[];let l=new Ra((e,t)=>po(e.canonicalString(),t.canonicalString()));for(const e of r){const t=ia(this.userId,e.key.path,o);l=l.add(e.key.path.popLast()),u.push(s.put(c)),u.push(i.put(t,sa))}return l.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.Vn[o]=a.keys()}),Fo.waitFor(u).next(()=>a)})}lookupMutationBatch(e,t){return ud(e).get(t).next(e=>e?(Js(e.userId===this.userId),mh(this.serializer,e)):null)}Sn(e,t){return this.Vn[t]?Fo.resolve(this.Vn[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){const n=e.keys();return this.Vn[t]=n,n}return null})}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]);let i=null;return ud(e).X({index:"userMutationsIndex",range:r},(e,t,r)=>{t.userId===this.userId&&(Js(t.batchId>=n),i=mh(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){const t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return ud(e).X({index:"userMutationsIndex",range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){const t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return ud(e).j("userMutationsIndex",t).next(e=>e.map(e=>mh(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){const n=ra(this.userId,t.path),r=IDBKeyRange.lowerBound(n),i=[];return ld(e).X({range:r},(n,r,s)=>{const[o,a,c]=n,u=ta(a);if(o===this.userId&&t.path.isEqual(u))return ud(e).get(c).next(e=>{if(!e)throw Xs();Js(e.userId===this.userId),i.push(mh(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new Ra(po);const r=[];return t.forEach(t=>{const i=ra(this.userId,t.path),s=IDBKeyRange.lowerBound(i),o=ld(e).X({range:s},(e,r,i)=>{const[s,o,a]=e,c=ta(o);s===this.userId&&t.path.isEqual(c)?n=n.add(a):i.done()});r.push(o)}),Fo.waitFor(r).next(()=>this.Dn(e,n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1,i=ra(this.userId,n),s=IDBKeyRange.lowerBound(i);let o=new Ra(po);return ld(e).X({range:s},(e,t,i)=>{const[s,a,c]=e,u=ta(a);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(o=o.add(c)):i.done()}).next(()=>this.Dn(e,o))}Dn(e,t){const n=[],r=[];return t.forEach(t=>{r.push(ud(e).get(t).next(e=>{if(null===e)throw Xs();Js(e.userId===this.userId),n.push(mh(this.serializer,e))}))}),Fo.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return sd(e.ht,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.Cn(t.batchId)}),Fo.forEach(n,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}Cn(e){delete this.Vn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>{if(!t)return Fo.resolve();const n=IDBKeyRange.lowerBound([this.userId]),r=[];return ld(e).X({range:n},(e,t,n)=>{if(e[0]===this.userId){const t=ta(e[1]);r.push(t)}else n.done()}).next(()=>{Js(0===r.length)})})}containsKey(e,t){return cd(e,this.userId,t)}xn(e){return hd(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function cd(e,t,n){const r=ra(t,n.path),i=r[1],s=IDBKeyRange.lowerBound(r);let o=!1;return ld(e).X({range:s,Y:!0},(e,n,r)=>{const[s,a,c]=e;s===t&&a===i&&(o=!0),r.done()}).next(()=>o)}function ud(e){return Sa(e,"mutations")}function ld(e){return Sa(e,"documentMutations")}function hd(e){return Sa(e,"mutationQueues")}class dd{constructor(e){this.Nn=e}next(){return this.Nn+=2,this.Nn}static kn(){return new dd(0)}static Mn(){return new dd(-1)}}class fd{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.$n(e).next(t=>{const n=new dd(t.highestTargetId);return t.highestTargetId=n.next(),this.On(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.$n(e).next(e=>_o.fromTimestamp(new yo(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.$n(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,n){return this.$n(e).next(r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.On(e,r)))}addTargetData(e,t){return this.Fn(e,t).next(()=>this.$n(e).next(n=>(n.targetCount+=1,this.Bn(t,n),this.On(e,n))))}updateTargetData(e,t){return this.Fn(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>pd(e).delete(t.targetId)).next(()=>this.$n(e)).next(t=>(Js(t.targetCount>0),t.targetCount-=1,this.On(e,t)))}removeTargets(e,t,n){let r=0;const i=[];return pd(e).X((s,o)=>{const a=yh(o);a.sequenceNumber<=t&&null===n.get(a.targetId)&&(r++,i.push(this.removeTargetData(e,a)))}).next(()=>Fo.waitFor(i)).next(()=>r)}forEachTarget(e,t){return pd(e).X((e,n)=>{const r=yh(n);t(r)})}$n(e){return gd(e).get("targetGlobalKey").next(e=>(Js(null!==e),e))}On(e,t){return gd(e).put("targetGlobalKey",t)}Fn(e,t){return pd(e).put(_h(this.serializer,t))}Bn(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.$n(e).next(e=>e.targetCount)}getTargetData(e,t){const n=$c(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let i=null;return pd(e).X({range:r,index:"queryTargetsIndex"},(e,n,r)=>{const s=yh(n);Gc(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){const r=[],i=md(e);return t.forEach(t=>{const s=Jo(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),Fo.waitFor(r)}removeMatchingKeys(e,t,n){const r=md(e);return Fo.forEach(t,t=>{const i=Jo(t.path);return Fo.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){const n=md(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=md(e);let i=Tu();return r.X({range:n,Y:!0},(e,t,n)=>{const r=ta(e[1]),s=new Eo(r);i=i.add(s)}).next(()=>i)}containsKey(e,t){const n=Jo(t.path),r=IDBKeyRange.bound([n],[mo(n)],!1,!0);let i=0;return md(e).X({index:"documentTargetsIndex",Y:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}le(e,t){return pd(e).get(t).next(e=>e?yh(e):null)}}function pd(e){return Sa(e,"targets")}function gd(e){return Sa(e,"targetGlobal")}function md(e){return Sa(e,"targetDocuments")}function yd([e,t],[n,r]){const i=po(e,n);return 0===i?po(t,r):i}class _d{constructor(e){this.Ln=e,this.buffer=new Ra(yd),this.qn=0}Un(){return++this.qn}Kn(e){const t=[e,this.Un()];if(this.buffer.size<this.Ln)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();yd(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class vd{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Qn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}Qn(e){Ws("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Bo(e)?Ws("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Mo(e)}await this.Qn(3e5)})}}class wd{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.zn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return Fo.resolve(Qo.ct);const n=new _d(t);return this.jn.forEachTarget(e,e=>n.Kn(e.sequenceNumber)).next(()=>this.jn.Wn(e,e=>n.Kn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(e,t){return-1===this.params.cacheSizeCollectionThreshold?(Ws("LruGarbageCollector","Garbage collection skipped; disabled"),Fo.resolve(rd)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(Ws("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),rd):this.Hn(e,t))}getCacheSize(e){return this.jn.getCacheSize(e)}Hn(e,t){let n,r,i,s,o,a,c;const u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(Ws("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,s=Date.now(),this.nthSequenceNumber(e,r))).next(r=>(n=r,o=Date.now(),this.removeTargets(e,n,t))).next(t=>(i=t,a=Date.now(),this.removeOrphanedDocuments(e,n))).next(e=>(c=Date.now(),Ks()<=K.DEBUG&&Ws("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${s-u}ms\n\tDetermined least recently used ${r} in `+(o-s)+"ms\n"+`\tRemoved ${i} targets in `+(a-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-a)+"ms\n"+`Total Duration: ${c-u}ms`),Fo.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class bd{constructor(e,t){this.db=e,this.garbageCollector=function(e,t){return new wd(e,t)}(this,t)}zn(e){const t=this.Jn(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}Jn(e){let t=0;return this.Wn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Wn(e,t){return this.Yn(e,(e,n)=>t(n))}addReference(e,t,n){return Id(e,n)}removeReference(e,t,n){return Id(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Id(e,t)}Xn(e,t){return function(e,t){let n=!1;return hd(e).Z(r=>cd(e,r,t).next(e=>(e&&(n=!0),Fo.resolve(!e)))).next(()=>n)}(e,t)}removeOrphanedDocuments(e,t){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[];let i=0;return this.Yn(e,(s,o)=>{if(o<=t){const t=this.Xn(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,_o.min()),md(e).delete([0,Jo(s.path)])))});r.push(t)}}).next(()=>Fo.waitFor(r)).next(()=>n.apply(e)).next(()=>i)}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Id(e,t)}Yn(e,t){const n=md(e);let r,i=Qo.ct;return n.X({index:"documentTargetsIndex"},([e,n],{path:s,sequenceNumber:o})=>{0===e?(i!==Qo.ct&&t(new Eo(ta(r)),i),i=o,r=s):i=Qo.ct}).next(()=>{i!==Qo.ct&&t(new Eo(ta(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Id(e,t){return md(e).put(function(e,t){return{targetId:0,path:Jo(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}class Ed{constructor(){this.changes=new pu(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,yc.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?Fo.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 Cd{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return kd(e).put(n)}removeEntry(e,t,n){return kd(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],fh(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next(n=>(n.byteSize+=t,this.Zn(e,n)))}getEntry(e,t){let n=yc.newInvalidDocument(t);return kd(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(Nd(t))},(e,r)=>{n=this.ts(t,r)}).next(()=>n)}es(e,t){let n={size:0,document:yc.newInvalidDocument(t)};return kd(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(Nd(t))},(e,r)=>{n={document:this.ts(t,r),size:od(r)}}).next(()=>n)}getEntries(e,t){let n=mu();return this.ns(e,t,(e,t)=>{const r=this.ts(e,t);n=n.insert(e,r)}).next(()=>n)}ss(e,t){let n=mu(),r=new Da(Eo.comparator);return this.ns(e,t,(e,t)=>{const i=this.ts(e,t);n=n.insert(e,i),r=r.insert(e,od(t))}).next(()=>({documents:n,rs:r}))}ns(e,t,n){if(t.isEmpty())return Fo.resolve();let r=new Ra(Ad);t.forEach(e=>r=r.add(e));const i=IDBKeyRange.bound(Nd(r.first()),Nd(r.last())),s=r.getIterator();let o=s.getNext();return kd(e).X({index:"documentKeyIndex",range:i},(e,t,r)=>{const i=Eo.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;o&&Ad(o,i)<0;)n(o,null),o=s.getNext();o&&o.isEqual(i)&&(n(o,t),o=s.hasNext()?s.getNext():null),o?r.G(Nd(o)):r.done()}).next(()=>{for(;o;)n(o,null),o=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,t,n,r){const i=t.path,s=[i.popLast().toArray(),i.lastSegment(),fh(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[i.popLast().toArray(),i.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return kd(e).j(IDBKeyRange.bound(s,o,!0)).next(e=>{let n=mu();for(const i of e){const e=this.ts(Eo.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(lu(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=mu();const s=Dd(t,n),o=Dd(t,Ao.max());return kd(e).X({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,o,!0)},(e,t,n)=>{const s=this.ts(Eo.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(s.key,s),i.size===r&&n.done()}).next(()=>i)}newChangeBuffer(e){return new Sd(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return xd(e).get("remoteDocumentGlobalKey").next(e=>(Js(!!e),e))}Zn(e,t){return xd(e).put("remoteDocumentGlobalKey",t)}ts(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Hl(e.fe,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=Eo.fromSegments(t.noDocument.path),r=gh(t.noDocument.readTime);n=yc.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Xs();{const e=Eo.fromSegments(t.unknownDocument.path),r=gh(t.unknownDocument.version);n=yc.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){const t=new yo(e[0],e[1]);return _o.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(_o.min()))return e}return yc.newInvalidDocument(e)}}function Td(e){return new Cd(e)}class Sd extends Ed{constructor(e,t){super(),this.os=e,this.trackRemovals=t,this.us=new pu(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){const t=[];let n=0,r=new Ra((e,t)=>po(e.canonicalString(),t.canonicalString()));return this.changes.forEach((i,s)=>{const o=this.us.get(i);if(t.push(this.os.removeEntry(e,i,o.readTime)),s.isValidDocument()){const a=dh(this.os.serializer,s);r=r.add(i.path.popLast());const c=od(a);n+=c-o.size,t.push(this.os.addEntry(e,i,a))}else if(n-=o.size,this.trackRemovals){const n=dh(this.os.serializer,s.convertToNoDocument(_o.min()));t.push(this.os.addEntry(e,i,n))}}),r.forEach(n=>{t.push(this.os.indexManager.addToCollectionParentIndex(e,n))}),t.push(this.os.updateMetadata(e,n)),Fo.waitFor(t)}getFromCache(e,t){return this.os.es(e,t).next(e=>(this.us.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.os.ss(e,t).next(({documents:e,rs:t})=>(t.forEach((t,n)=>{this.us.set(t,{size:n,readTime:e.get(t).readTime})}),e))}}function xd(e){return Sa(e,"remoteDocumentGlobal")}function kd(e){return Sa(e,"remoteDocumentsV14")}function Nd(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Dd(e,t){const n=t.documentKey.path.toArray();return[e,fh(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function Ad(e,t){const n=e.path.toArray(),r=t.path.toArray();let i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=po(n[e],r[e]),i)return i;return i=po(n.length,r.length),i||(i=po(n[n.length-2],r[r.length-2]),i||po(n[n.length-1],r[r.length-1]))}class Pd{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Rd{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(r=>(n=r,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==n&&Yu(n.mutation,e,Fa.empty(),yo.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,Tu()).next(()=>t))}getLocalViewOfDocuments(e,t,n=Tu()){const r=wu();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=_u();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){const n=wu();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Tu()))}populateOverlays(e,t,n){const r=[];return n.forEach(e=>{t.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,n)=>{t.set(e,n)})})}computeViews(e,t,n,r){let i=mu();const s=Iu(),o=Iu();return t.forEach((e,t)=>{const o=n.get(t.key);r.has(t.key)&&(void 0===o||o.mutation instanceof el)?i=i.insert(t.key,t):void 0!==o?(s.set(t.key,o.mutation.getFieldMask()),Yu(o.mutation,t,o.mutation.getFieldMask(),yo.now())):s.set(t.key,Fa.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new Pd(t,null!==(n=s.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(e,t){const n=Iu();let r=new Da((e,t)=>e-t),i=Tu();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(const i of e)i.keys().forEach(e=>{const s=t.get(e);if(null===s)return;let o=n.get(e)||Fa.empty();o=i.applyToLocalView(s,o),n.set(e,o);const a=(r.get(i.batchId)||Tu()).add(e);r=r.insert(i.batchId,a)})}).next(()=>{const s=[],o=r.getReverseIterator();for(;o.hasNext();){const r=o.getNext(),a=r.key,c=r.value,u=bu();c.forEach(e=>{if(!i.has(e)){const r=Qu(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,a,u))}return Fo.waitFor(s)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,n){return function(e){return Eo.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):nu(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(i=>{const s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):Fo.resolve(wu());let o=-1,a=i;return s.next(t=>Fo.forEach(t,(t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),i.get(t)?Fo.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{a=a.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,a,t,Tu())).next(e=>({batchId:o,changes:vu(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new Eo(t)).next(e=>{let t=_u();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n){const r=t.collectionGroup;let i=_u();return this.indexManager.getCollectionParents(e,r).next(s=>Fo.forEach(s,s=>{const o=function(e,t){return new Yc(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,s.child(r));return this.getDocumentsMatchingCollectionQuery(e,o,n).next(e=>{e.forEach((e,t)=>{i=i.insert(e,t)})})}).next(()=>i))}getDocumentsMatchingCollectionQuery(e,t,n){let r;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(i=>(r=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,r))).next(e=>{r.forEach((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,yc.newInvalidDocument(r)))});let n=_u();return e.forEach((e,i)=>{const s=r.get(e);void 0!==s&&Yu(s.mutation,i,Fa.empty(),yo.now()),lu(t,i)&&(n=n.insert(e,i))}),n})}}class Od{constructor(e){this.serializer=e,this.cs=new Map,this.hs=new Map}getBundleMetadata(e,t){return Fo.resolve(this.cs.get(t))}saveBundleMetadata(e,t){var n;return this.cs.set(t.id,{id:(n=t).id,version:n.version,createTime:Vl(n.createTime)}),Fo.resolve()}getNamedQuery(e,t){return Fo.resolve(this.hs.get(t))}saveNamedQuery(e,t){return this.hs.set(t.name,function(e){return{name:e.name,query:vh(e.bundledQuery),readTime:Vl(e.readTime)}}(t)),Fo.resolve()}}class Md{constructor(){this.overlays=new Da(Eo.comparator),this.ls=new Map}getOverlay(e,t){return Fo.resolve(this.overlays.get(t))}getOverlays(e,t){const n=wu();return Fo.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){return n.forEach((n,r)=>{this.we(e,t,r)}),Fo.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.ls.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.ls.delete(n)),Fo.resolve()}getOverlaysForCollection(e,t,n){const r=wu(),i=t.length+1,s=new Eo(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 Fo.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new Da((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=wu(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=wu(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach((e,t)=>o.set(e,t)),!(o.size()>=r)););return Fo.resolve(o)}we(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.ls.get(r.largestBatchId).delete(n.key);this.ls.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new cl(t,n));let i=this.ls.get(t);void 0===i&&(i=Tu(),this.ls.set(t,i)),this.ls.set(t,i.add(n.key))}}class Fd{constructor(){this.fs=new Ra(Ld.ds),this.ws=new Ra(Ld._s)}isEmpty(){return this.fs.isEmpty()}addReference(e,t){const n=new Ld(e,t);this.fs=this.fs.add(n),this.ws=this.ws.add(n)}gs(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.ys(new Ld(e,t))}ps(e,t){e.forEach(e=>this.removeReference(e,t))}Is(e){const t=new Eo(new wo([])),n=new Ld(t,e),r=new Ld(t,e+1),i=[];return this.ws.forEachInRange([n,r],e=>{this.ys(e),i.push(e.key)}),i}Ts(){this.fs.forEach(e=>this.ys(e))}ys(e){this.fs=this.fs.delete(e),this.ws=this.ws.delete(e)}Es(e){const t=new Eo(new wo([])),n=new Ld(t,e),r=new Ld(t,e+1);let i=Tu();return this.ws.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){const t=new Ld(e,0),n=this.fs.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class Ld{constructor(e,t){this.key=e,this.As=t}static ds(e,t){return Eo.comparator(e.key,t.key)||po(e.As,t.As)}static _s(e,t){return po(e.As,t.As)||Eo.comparator(e.key,t.key)}}class qd{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.vs=1,this.Rs=new Ra(Ld.ds)}checkEmpty(e){return Fo.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const i=this.vs;this.vs++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const s=new ol(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.Rs=this.Rs.add(new Ld(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return Fo.resolve(s)}lookupMutationBatch(e,t){return Fo.resolve(this.Ps(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.bs(n),i=r<0?0:r;return Fo.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return Fo.resolve(0===this.mutationQueue.length?-1:this.vs-1)}getAllMutationBatches(e){return Fo.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Ld(t,0),r=new Ld(t,Number.POSITIVE_INFINITY),i=[];return this.Rs.forEachInRange([n,r],e=>{const t=this.Ps(e.As);i.push(t)}),Fo.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new Ra(po);return t.forEach(e=>{const t=new Ld(e,0),r=new Ld(e,Number.POSITIVE_INFINITY);this.Rs.forEachInRange([t,r],e=>{n=n.add(e.As)})}),Fo.resolve(this.Vs(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;Eo.isDocumentKey(i)||(i=i.child(""));const s=new Ld(new Eo(i),0);let o=new Ra(po);return this.Rs.forEachWhile(e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.As)),!0)},s),Fo.resolve(this.Vs(o))}Vs(e){const t=[];return e.forEach(e=>{const n=this.Ps(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){Js(0===this.Ss(t.batchId,"removed")),this.mutationQueue.shift();let n=this.Rs;return Fo.forEach(t.mutations,r=>{const i=new Ld(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.Rs=n})}Cn(e){}containsKey(e,t){const n=new Ld(t,0),r=this.Rs.firstAfterOrEqual(n);return Fo.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,Fo.resolve()}Ss(e,t){return this.bs(e)}bs(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Ps(e){const t=this.bs(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Vd{constructor(e){this.Ds=e,this.docs=new Da(Eo.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.Ds(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){const 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 Fo.resolve(n?n.document.mutableCopy():yc.newInvalidDocument(t))}getEntries(e,t){let n=mu();return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():yc.newInvalidDocument(e))}),Fo.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=mu();const s=t.path,o=new Eo(s.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||Po(Do(o),n)<=0||(r.has(o.key)||lu(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return Fo.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Xs()}Cs(e,t){return Fo.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new jd(this)}getSize(e){return Fo.resolve(this.size)}}class jd extends Ed{constructor(e){super(),this.os=e}applyChanges(e){const t=[];return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.os.addEntry(e,r)):this.os.removeEntry(n)}),Fo.waitFor(t)}getFromCache(e,t){return this.os.getEntry(e,t)}getAllFromCache(e,t){return this.os.getEntries(e,t)}}class Bd{constructor(e){this.persistence=e,this.xs=new pu(e=>$c(e),Gc),this.lastRemoteSnapshotVersion=_o.min(),this.highestTargetId=0,this.Ns=0,this.ks=new Fd,this.targetCount=0,this.Ms=dd.kn()}forEachTarget(e,t){return this.xs.forEach((e,n)=>t(n)),Fo.resolve()}getLastRemoteSnapshotVersion(e){return Fo.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Fo.resolve(this.Ns)}allocateTargetId(e){return this.highestTargetId=this.Ms.next(),Fo.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Ns&&(this.Ns=t),Fo.resolve()}Fn(e){this.xs.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Ms=new dd(t),this.highestTargetId=t),e.sequenceNumber>this.Ns&&(this.Ns=e.sequenceNumber)}addTargetData(e,t){return this.Fn(t),this.targetCount+=1,Fo.resolve()}updateTargetData(e,t){return this.Fn(t),Fo.resolve()}removeTargetData(e,t){return this.xs.delete(t.target),this.ks.Is(t.targetId),this.targetCount-=1,Fo.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.xs.forEach((s,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.xs.delete(s),i.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)}),Fo.waitFor(i).next(()=>r)}getTargetCount(e){return Fo.resolve(this.targetCount)}getTargetData(e,t){const n=this.xs.get(t)||null;return Fo.resolve(n)}addMatchingKeys(e,t,n){return this.ks.gs(t,n),Fo.resolve()}removeMatchingKeys(e,t,n){this.ks.ps(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(t=>{i.push(r.markPotentiallyOrphaned(e,t))}),Fo.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.ks.Is(t),Fo.resolve()}getMatchingKeysForTargetId(e,t){const n=this.ks.Es(t);return Fo.resolve(n)}containsKey(e,t){return Fo.resolve(this.ks.containsKey(t))}}class Ud{constructor(e,t){this.$s={},this.overlays={},this.Os=new Qo(0),this.Fs=!1,this.Fs=!0,this.referenceDelegate=e(this),this.Bs=new Bd(this),this.indexManager=new Qh,this.remoteDocumentCache=function(e){return new Vd(e)}(e=>this.referenceDelegate.Ls(e)),this.serializer=new hh(t),this.qs=new Od(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Fs=!1,Promise.resolve()}get started(){return this.Fs}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Md,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.$s[e.toKey()];return n||(n=new qd(t,this.referenceDelegate),this.$s[e.toKey()]=n),n}getTargetCache(){return this.Bs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.qs}runTransaction(e,t,n){Ws("MemoryPersistence","Starting transaction:",e);const r=new zd(this.Os.next());return this.referenceDelegate.Us(),n(r).next(e=>this.referenceDelegate.Ks(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gs(e,t){return Fo.or(Object.values(this.$s).map(n=>()=>n.containsKey(e,t)))}}class zd extends Oo{constructor(e){super(),this.currentSequenceNumber=e}}class $d{constructor(e){this.persistence=e,this.Qs=new Fd,this.js=null}static zs(e){return new $d(e)}get Ws(){if(this.js)return this.js;throw Xs()}addReference(e,t,n){return this.Qs.addReference(n,t),this.Ws.delete(n.toString()),Fo.resolve()}removeReference(e,t,n){return this.Qs.removeReference(n,t),this.Ws.add(n.toString()),Fo.resolve()}markPotentiallyOrphaned(e,t){return this.Ws.add(t.toString()),Fo.resolve()}removeTarget(e,t){this.Qs.Is(t.targetId).forEach(e=>this.Ws.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Ws.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Us(){this.js=new Set}Ks(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Fo.forEach(this.Ws,n=>{const r=Eo.fromPath(n);return this.Hs(e,r).next(e=>{e||t.removeEntry(r,_o.min())})}).next(()=>(this.js=null,t.apply(e)))}updateLimboDocument(e,t){return this.Hs(e,t).next(e=>{e?this.Ws.delete(t.toString()):this.Ws.add(t.toString())})}Ls(e){return 0}Hs(e,t){return Fo.or([()=>Fo.resolve(this.Qs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gs(e,t)])}}class Gd{constructor(e){this.serializer=e}O(e,t,n,r){const i=new Lo("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",na,{unique:!0}),e.createObjectStore("documentMutations")}(e),Kd(e),function(e){e.createObjectStore("remoteDocuments")}(e));let s=Fo.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),Kd(e)),s=s.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:_o.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>function(e,t){return t.store("mutations").j().next(n=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",na,{unique:!0});const r=t.store("mutations"),i=n.map(e=>r.put(e));return Fo.waitFor(i)})}(e,i))),s=s.next(()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)})),n<5&&r>=5&&(s=s.next(()=>this.Ys(i))),n<6&&r>=6&&(s=s.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.Xs(i)))),n<7&&r>=7&&(s=s.next(()=>this.Zs(i))),n<8&&r>=8&&(s=s.next(()=>this.ti(e,i))),n<9&&r>=9&&(s=s.next(()=>{!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)})),n<10&&r>=10&&(s=s.next(()=>this.ei(i))),n<11&&r>=11&&(s=s.next(()=>{!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)})),n<12&&r>=12&&(s=s.next(()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:ya});t.createIndex("collectionPathOverlayIndex",_a,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",va,{unique:!1})}(e)})),n<13&&r>=13&&(s=s.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:oa});t.createIndex("documentKeyIndex",aa),t.createIndex("collectionGroupIndex",ca)}(e)).next(()=>this.ni(e,i)).next(()=>e.deleteObjectStore("remoteDocuments"))),n<14&&r>=14&&(s=s.next(()=>this.si(e,i))),n<15&&r>=15&&(s=s.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:fa}).createIndex("sequenceNumberIndex",pa,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:ga}).createIndex("documentKeyIndex",ma,{unique:!1})}(e))),s}Xs(e){let t=0;return e.store("remoteDocuments").X((e,n)=>{t+=od(n)}).next(()=>{const n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)})}Ys(e){const t=e.store("mutationQueues"),n=e.store("mutations");return t.j().next(t=>Fo.forEach(t,t=>{const r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.j("userMutationsIndex",r).next(n=>Fo.forEach(n,n=>{Js(n.userId===t.userId);const r=mh(this.serializer,n);return sd(e,t.userId,r).next(()=>{})}))}))}Zs(e){const t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(e=>{const r=[];return n.X((n,i)=>{const s=new wo(n),o=function(e){return[0,Jo(e)]}(s);r.push(t.get(o).next(n=>n?Fo.resolve():(n=>t.put({targetId:0,path:Jo(n),sequenceNumber:e.highestListenSequenceNumber}))(s)))}).next(()=>Fo.waitFor(r))})}ti(e,t){e.createObjectStore("collectionParents",{keyPath:da});const n=t.store("collectionParents"),r=new Hh,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Jo(r)})}};return t.store("remoteDocuments").X({Y:!0},(e,t)=>{const n=new wo(e);return i(n.popLast())}).next(()=>t.store("documentMutations").X({Y:!0},([e,t,n],r)=>{const s=ta(t);return i(s.popLast())}))}ei(e){const t=e.store("targets");return t.X((e,n)=>{const r=yh(n),i=_h(this.serializer,r);return t.put(i)})}ni(e,t){const n=t.store("remoteDocuments"),r=[];return n.X((e,n)=>{const i=t.store("remoteDocumentsV14"),s=(o=n,o.document?new Eo(wo.fromString(o.document.name).popFirst(5)):o.noDocument?Eo.fromSegments(o.noDocument.path):o.unknownDocument?Eo.fromSegments(o.unknownDocument.path):Xs()).path.toArray();var o;const a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))}).next(()=>Fo.waitFor(r))}si(e,t){const n=t.store("mutations"),r=Td(this.serializer),i=new Ud($d.zs,this.serializer.fe);return n.j().next(e=>{const n=new Map;return e.forEach(e=>{var t;let r=null!==(t=n.get(e.userId))&&void 0!==t?t:Tu();mh(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),Fo.forEach(n,(e,n)=>{const s=new zs(n),o=Sh.de(this.serializer,s),a=i.getIndexManager(s),c=ad.de(s,this.serializer,a,i.referenceDelegate);return new Rd(r,c,o,a).recalculateAndSaveOverlaysForDocumentKeys(new Ta(t,Qo.ct),e).next()})})}}function Kd(e){e.createObjectStore("targetDocuments",{keyPath:la}).createIndex("documentTargetsIndex",ha,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",ua,{unique:!0}),e.createObjectStore("targetGlobal")}const Wd="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 Qd{constructor(e,t,n,r,i,s,o,a,c,u,l=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.ii=i,this.window=s,this.document=o,this.ri=c,this.oi=u,this.ui=l,this.Os=null,this.Fs=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.ai=null,this.hi=null,this.li=Number.NEGATIVE_INFINITY,this.fi=e=>Promise.resolve(),!Qd.D())throw new to(eo.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new bd(this,r),this.di=t+"main",this.serializer=new hh(a),this.wi=new qo(this.di,this.ui,new Gd(this.serializer)),this.Bs=new fd(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Td(this.serializer),this.qs=new Eh,this.window&&this.window.localStorage?this._i=this.window.localStorage:(this._i=null,!1===u&&Qs("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.mi().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new to(eo.FAILED_PRECONDITION,Wd);return this.gi(),this.yi(),this.pi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Bs.getHighestSequenceNumber(e))}).then(e=>{this.Os=new Qo(e,this.ri)}).then(()=>{this.Fs=!0}).catch(e=>(this.wi&&this.wi.close(),Promise.reject(e)))}Ii(e){return this.fi=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.wi.B(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.ii.enqueueAndForget(async()=>{this.started&&await this.mi()}))}mi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>Yd(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Ti(e).next(e=>{e||(this.isPrimary=!1,this.ii.enqueueRetryable(()=>this.fi(!1)))})}).next(()=>this.Ei(e)).next(t=>this.isPrimary&&!t?this.Ai(e).next(()=>!1):!!t&&this.vi(e).next(()=>!0))).catch(e=>{if(Bo(e))return Ws("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Ws("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.ii.enqueueRetryable(()=>this.fi(e)),this.isPrimary=e})}Ti(e){return Hd(e).get("owner").next(e=>Fo.resolve(this.Ri(e)))}Pi(e){return Yd(e).delete(this.clientId)}async bi(){if(this.isPrimary&&!this.Vi(this.li,18e5)){this.li=Date.now();const e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const t=Sa(e,"clientMetadata");return t.j().next(e=>{const n=this.Si(e,18e5),r=e.filter(e=>-1===n.indexOf(e));return Fo.forEach(r,e=>t.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this._i)for(const t of e)this._i.removeItem(this.Di(t.clientId))}}pi(){this.hi=this.ii.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.mi().then(()=>this.bi()).then(()=>this.pi()))}Ri(e){return!!e&&e.ownerId===this.clientId}Ei(e){return this.oi?Fo.resolve(!0):Hd(e).get("owner").next(t=>{if(null!==t&&this.Vi(t.leaseTimestampMs,5e3)&&!this.Ci(t.ownerId)){if(this.Ri(t)&&this.networkEnabled)return!0;if(!this.Ri(t)){if(!t.allowTabSynchronization)throw new to(eo.FAILED_PRECONDITION,Wd);return!1}}return!(!this.networkEnabled||!this.inForeground)||Yd(e).j().next(e=>void 0===this.Si(e,5e3).find(e=>{if(this.clientId!==e.clientId){const 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&&Ws("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Fs=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Ni(),this.ki(),await this.wi.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new Ta(e,Qo.ct);return this.Ai(t).next(()=>this.Pi(t))}),this.wi.close(),this.Mi()}Si(e,t){return e.filter(e=>this.Vi(e.updateTimeMs,t)&&!this.Ci(e.clientId))}$i(){return this.runTransaction("getActiveClients","readonly",e=>Yd(e).j().next(e=>this.Si(e,18e5).map(e=>e.clientId)))}get started(){return this.Fs}getMutationQueue(e,t){return ad.de(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Bs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Xh(e,this.serializer.fe.databaseId)}getDocumentOverlayCache(e){return Sh.de(this.serializer,e)}getBundleCache(){return this.qs}runTransaction(e,t,n){Ws("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",i=15===(s=this.ui)?Ca:14===s?Ea:13===s?Ia:12===s?ba:11===s?wa:void Xs();var s;let o;return this.wi.runTransaction(e,r,i,r=>(o=new Ta(r,this.Os?this.Os.next():Qo.ct),"readwrite-primary"===t?this.Ti(o).next(e=>!!e||this.Ei(o)).next(t=>{if(!t)throw Qs(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.ii.enqueueRetryable(()=>this.fi(!1)),new to(eo.FAILED_PRECONDITION,Ro);return n(o)}).next(e=>this.vi(o).next(()=>e)):this.Oi(o).next(()=>n(o)))).then(e=>(o.raiseOnCommittedEvent(),e))}Oi(e){return Hd(e).get("owner").next(e=>{if(null!==e&&this.Vi(e.leaseTimestampMs,5e3)&&!this.Ci(e.ownerId)&&!this.Ri(e)&&!(this.oi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new to(eo.FAILED_PRECONDITION,Wd)})}vi(e){const t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Hd(e).put("owner",t)}static D(){return qo.D()}Ai(e){const t=Hd(e);return t.get("owner").next(e=>this.Ri(e)?(Ws("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):Fo.resolve())}Vi(e,t){const n=Date.now();return!(e<n-t||e>n&&(Qs(`Detected an update time that is in the future: ${e} > ${n}`),1))}gi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ai=()=>{this.ii.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.mi()))},this.document.addEventListener("visibilitychange",this.ai),this.inForeground="visible"===this.document.visibilityState)}Ni(){this.ai&&(this.document.removeEventListener("visibilitychange",this.ai),this.ai=null)}yi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();const e=/(?:Version|Mobile)\/1[456]/;!function(){var e;const t=null===(e=d())||void 0===e?void 0:e.forceEnvironment;if("node"===t)return!0;if("browser"===t)return!1;try{return"[object process]"===Object.prototype.toString.call(n.g.process)}catch(e){return!1}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.ii.enterRestrictedMode(!0),this.ii.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}ki(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Ci(e){var t;try{const n=null!==(null===(t=this._i)||void 0===t?void 0:t.getItem(this.Di(e)));return Ws("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Qs("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this._i)try{this._i.setItem(this.Di(this.clientId),String(Date.now()))}catch(e){Qs("Failed to set zombie client id.",e)}}Mi(){if(this._i)try{this._i.removeItem(this.Di(this.clientId))}catch(e){}}Di(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function Hd(e){return Sa(e,"owner")}function Yd(e){return Sa(e,"clientMetadata")}function Xd(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Jd{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Fi=n,this.Bi=r}static Li(e,t){let n=Tu(),r=Tu();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 Jd(e,t.fromCache,n,r)}}class Zd{constructor(){this.qi=!1}initialize(e,t){this.Ui=e,this.indexManager=t,this.qi=!0}getDocumentsMatchingQuery(e,t,n,r){return this.Ki(e,t).next(i=>i||this.Gi(e,t,r,n)).next(n=>n||this.Qi(e,t))}Ki(e,t){if(Zc(t))return Fo.resolve(null);let n=iu(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(t=ou(t,null,"F"),n=iu(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{const i=Tu(...r);return this.Ui.getDocuments(e,i).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{const s=this.ji(t,r);return this.zi(t,s,i,n.readTime)?this.Ki(e,ou(t,null,"F")):this.Wi(e,s,t,n)}))})))}Gi(e,t,n,r){return Zc(t)||r.isEqual(_o.min())?this.Qi(e,t):this.Ui.getDocuments(e,n).next(i=>{const s=this.ji(t,i);return this.zi(t,s,n,r)?this.Qi(e,t):(Ks()<=K.DEBUG&&Ws("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),uu(t)),this.Wi(e,s,t,No(r,-1)))})}ji(e,t){let n=new Ra(du(e));return t.forEach((t,r)=>{lu(e,r)&&(n=n.add(r))}),n}zi(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||i.version.compareTo(r)>0)}Qi(e,t){return Ks()<=K.DEBUG&&Ws("QueryEngine","Using full collection scan to execute query:",uu(t)),this.Ui.getDocumentsMatchingQuery(e,t,Ao.min())}Wi(e,t,n,r){return this.Ui.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}class ef{constructor(e,t,n,r){this.persistence=e,this.Hi=t,this.serializer=r,this.Ji=new Da(po),this.Yi=new pu(e=>$c(e),Gc),this.Xi=new Map,this.Zi=e.getRemoteDocumentCache(),this.Bs=e.getTargetCache(),this.qs=e.getBundleCache(),this.tr(n)}tr(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Rd(this.Zi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Zi.setIndexManager(this.indexManager),this.Hi.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Ji))}}function tf(e,t,n,r){return new ef(e,t,n,r)}async function nf(e,t){const n=Zs(e);return await n.persistence.runTransaction("Handle user change","readonly",e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next(i=>(r=i,n.tr(t),n.mutationQueue.getAllMutationBatches(e))).next(t=>{const i=[],s=[];let o=Tu();for(const e of r){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){s.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next(e=>({er:e,removedBatchIds:i,addedBatchIds:s}))})})}function rf(e){const t=Zs(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Bs.getLastRemoteSnapshotVersion(e))}function sf(e,t,n){let r=Tu(),i=Tu();return n.forEach(e=>r=r.add(e)),t.getEntries(e,r).next(e=>{let r=mu();return n.forEach((n,s)=>{const o=e.get(n);s.isFoundDocument()!==o.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(_o.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!o.isValidDocument()||s.version.compareTo(o.version)>0||0===s.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):Ws("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",s.version)}),{nr:r,sr:i}})}function of(e,t){const n=Zs(e);return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}function af(e,t){const n=Zs(e);return n.persistence.runTransaction("Allocate target","readwrite",e=>{let r;return n.Bs.getTargetData(e,t).next(i=>i?(r=i,Fo.resolve(r)):n.Bs.allocateTargetId(e).next(i=>(r=new lh(t,i,"TargetPurposeListen",e.currentSequenceNumber),n.Bs.addTargetData(e,r).next(()=>r))))}).then(e=>{const r=n.Ji.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.Ji=n.Ji.insert(e.targetId,e),n.Yi.set(t,e.targetId)),e})}async function cf(e,t,n){const r=Zs(e),i=r.Ji.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(!Bo(e))throw e;Ws("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Ji=r.Ji.remove(t),r.Yi.delete(i.target)}function uf(e,t,n){const r=Zs(e);let i=_o.min(),s=Tu();return r.persistence.runTransaction("Execute query","readonly",e=>function(e,t,n){const r=Zs(e),i=r.Yi.get(n);return void 0!==i?Fo.resolve(r.Ji.get(i)):r.Bs.getTargetData(t,n)}(r,e,iu(t)).next(t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.Bs.getMatchingKeysForTargetId(e,t.targetId).next(e=>{s=e})}).next(()=>r.Hi.getDocumentsMatchingQuery(e,t,n?i:_o.min(),n?s:Tu())).next(e=>(df(r,hu(t),e),{documents:e,ir:s})))}function lf(e,t){const n=Zs(e),r=Zs(n.Bs),i=n.Ji.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.le(e,t).next(e=>e?e.target:null))}function hf(e,t){const n=Zs(e),r=n.Xi.get(t)||_o.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.Zi.getAllFromCollectionGroup(e,t,No(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(df(n,t,e),e))}function df(e,t,n){let r=e.Xi.get(t)||_o.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.Xi.set(t,r)}async function ff(e,t,n=Tu()){const r=await af(e,iu(vh(t.bundledQuery))),i=Zs(e);return i.persistence.runTransaction("Save named query","readwrite",e=>{const s=Vl(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return i.qs.saveNamedQuery(e,t);const o=r.withResumeToken(qa.EMPTY_BYTE_STRING,s);return i.Ji=i.Ji.insert(o.targetId,o),i.Bs.updateTargetData(e,o).next(()=>i.Bs.removeMatchingKeysForTargetId(e,r.targetId)).next(()=>i.Bs.addMatchingKeys(e,n,r.targetId)).next(()=>i.qs.saveNamedQuery(e,t))})}function pf(e,t){return`firestore_clients_${e}_${t}`}function gf(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function mf(e,t){return`firestore_targets_${e}_${t}`}class yf{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static ar(e,t,n){const 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 to(r.error.code,r.error.message))),s?new yf(e,t,r.state,i):(Qs("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}hr(){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 _f{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static ar(e,t){const 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 to(n.error.code,n.error.message))),i?new _f(e,n.state,r):(Qs("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}hr(){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 vf{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static ar(e,t){const n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=xu();for(let e=0;r&&e<n.activeTargetIds.length;++e)r=Xo(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new vf(e,i):(Qs("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class wf{constructor(e,t){this.clientId=e,this.onlineState=t}static ar(e){const t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new wf(t.clientId,t.onlineState):(Qs("SharedClientState",`Failed to parse online state: ${e}`),null)}}class bf{constructor(){this.activeTargetIds=xu()}lr(e){this.activeTargetIds=this.activeTargetIds.add(e)}dr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}hr(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class If{constructor(e,t,n,r,i){this.window=e,this.ii=t,this.persistenceKey=n,this.wr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this._r=this.mr.bind(this),this.gr=new Da(po),this.started=!1,this.yr=[];const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.pr=pf(this.persistenceKey,this.wr),this.Ir=function(e){return`firestore_sequence_number_${e}`}(this.persistenceKey),this.gr=this.gr.insert(this.wr,new bf),this.Tr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Er=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Ar=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.vr=function(e){return`firestore_online_state_${e}`}(this.persistenceKey),this.Rr=function(e){return`firestore_bundle_loaded_v2_${e}`}(this.persistenceKey),this.window.addEventListener("storage",this._r)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.$i();for(const t of e){if(t===this.wr)continue;const e=this.getItem(pf(this.persistenceKey,t));if(e){const n=vf.ar(t,e);n&&(this.gr=this.gr.insert(n.clientId,n))}}this.Pr();const t=this.storage.getItem(this.vr);if(t){const e=this.br(t);e&&this.Vr(e)}for(const e of this.yr)this.mr(e);this.yr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ir,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Sr(this.gr)}isActiveQueryTarget(e){let t=!1;return this.gr.forEach((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.Dr(e,"pending")}updateMutationState(e,t,n){this.Dr(e,t,n),this.Cr(e)}addLocalQueryTarget(e){let t="not-current";if(this.isActiveQueryTarget(e)){const n=this.storage.getItem(mf(this.persistenceKey,e));if(n){const r=_f.ar(e,n);r&&(t=r.state)}}return this.Nr.lr(e),this.Pr(),t}removeLocalQueryTarget(e){this.Nr.dr(e),this.Pr()}isLocalQueryTarget(e){return this.Nr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(mf(this.persistenceKey,e))}updateQueryState(e,t,n){this.kr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Cr(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Mr(e)}notifyBundleLoaded(e){this.$r(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this._r),this.removeItem(this.pr),this.started=!1)}getItem(e){const t=this.storage.getItem(e);return Ws("SharedClientState","READ",e,t),t}setItem(e,t){Ws("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Ws("SharedClientState","REMOVE",e),this.storage.removeItem(e)}mr(e){const t=e;if(t.storageArea===this.storage){if(Ws("SharedClientState","EVENT",t.key,t.newValue),t.key===this.pr)return void Qs("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.ii.enqueueRetryable(async()=>{if(this.started){if(null!==t.key)if(this.Tr.test(t.key)){if(null==t.newValue){const e=this.Or(t.key);return this.Fr(e,null)}{const e=this.Br(t.key,t.newValue);if(e)return this.Fr(e.clientId,e)}}else if(this.Er.test(t.key)){if(null!==t.newValue){const e=this.Lr(t.key,t.newValue);if(e)return this.qr(e)}}else if(this.Ar.test(t.key)){if(null!==t.newValue){const e=this.Ur(t.key,t.newValue);if(e)return this.Kr(e)}}else if(t.key===this.vr){if(null!==t.newValue){const e=this.br(t.newValue);if(e)return this.Vr(e)}}else if(t.key===this.Ir){const e=function(e){let t=Qo.ct;if(null!=e)try{const n=JSON.parse(e);Js("number"==typeof n),t=n}catch(e){Qs("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==Qo.ct&&this.sequenceNumberHandler(e)}else if(t.key===this.Rr){const e=this.Gr(t.newValue);await Promise.all(e.map(e=>this.syncEngine.Qr(e)))}}else this.yr.push(t)})}}get Nr(){return this.gr.get(this.wr)}Pr(){this.setItem(this.pr,this.Nr.hr())}Dr(e,t,n){const r=new yf(this.currentUser,e,t,n),i=gf(this.persistenceKey,this.currentUser,e);this.setItem(i,r.hr())}Cr(e){const t=gf(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Mr(e){const t={clientId:this.wr,onlineState:e};this.storage.setItem(this.vr,JSON.stringify(t))}kr(e,t,n){const r=mf(this.persistenceKey,e),i=new _f(e,t,n);this.setItem(r,i.hr())}$r(e){const t=JSON.stringify(Array.from(e));this.setItem(this.Rr,t)}Or(e){const t=this.Tr.exec(e);return t?t[1]:null}Br(e,t){const n=this.Or(e);return vf.ar(n,t)}Lr(e,t){const n=this.Er.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return yf.ar(new zs(i),r,t)}Ur(e,t){const n=this.Ar.exec(e),r=Number(n[1]);return _f.ar(r,t)}br(e){return wf.ar(e)}Gr(e){return JSON.parse(e)}async qr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.jr(e.batchId,e.state,e.error);Ws("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Kr(e){return this.syncEngine.zr(e.targetId,e.state,e.error)}Fr(e,t){const n=t?this.gr.insert(e,t):this.gr.remove(e),r=this.Sr(this.gr),i=this.Sr(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.Wr(s,o).then(()=>{this.gr=n})}Vr(e){this.gr.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Sr(e){let t=xu();return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class Ef{constructor(){this.Hr=new bf,this.Jr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Hr.lr(e),this.Jr[e]||"not-current"}updateQueryState(e,t,n){this.Jr[e]=t}removeLocalQueryTarget(e){this.Hr.dr(e)}isLocalQueryTarget(e){return this.Hr.activeTargetIds.has(e)}clearQueryState(e){delete this.Jr[e]}getAllActiveQueryTargets(){return this.Hr.activeTargetIds}isActiveQueryTarget(e){return this.Hr.activeTargetIds.has(e)}start(){return this.Hr=new bf,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Cf{Yr(e){}shutdown(){}}class Tf{constructor(){this.Xr=()=>this.Zr(),this.eo=()=>this.no(),this.so=[],this.io()}Yr(e){this.so.push(e)}shutdown(){window.removeEventListener("online",this.Xr),window.removeEventListener("offline",this.eo)}io(){window.addEventListener("online",this.Xr),window.addEventListener("offline",this.eo)}Zr(){Ws("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.so)e(0)}no(){Ws("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.so)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Sf=null;function xf(){return null===Sf?Sf=268435456+Math.round(2147483648*Math.random()):Sf++,"0x"+Sf.toString(16)}const kf={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Nf{constructor(e){this.ro=e.ro,this.oo=e.oo}uo(e){this.co=e}ao(e){this.ho=e}onMessage(e){this.lo=e}close(){this.oo()}send(e){this.ro(e)}fo(){this.co()}wo(e){this.ho(e)}_o(e){this.lo(e)}}const Df="WebChannelConnection";class Af extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http";this.mo=t+"://"+e.host,this.yo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get po(){return!1}Io(e,t,n,r,i){const s=xf(),o=this.To(e,t);Ws("RestConnection",`Sending RPC '${e}' ${s}:`,o,n);const a={};return this.Eo(a,r,i),this.Ao(e,o,a,n).then(t=>(Ws("RestConnection",`Received RPC '${e}' ${s}: `,t),t),t=>{throw Hs("RestConnection",`RPC '${e}' ${s} failed with error: `,t,"url: ",o,"request:",n),t})}vo(e,t,n,r,i,s){return this.Io(e,t,n,r,i)}Eo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+$s,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,n)=>e[n]=t),n&&n.headers.forEach((t,n)=>e[n]=t)}To(e,t){const n=kf[e];return`${this.mo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Ao(e,t,n,r){const i=xf();return new Promise((s,o)=>{const a=new Vs;a.setWithCredentials(!0),a.listenOnce(Os.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case Rs.NO_ERROR:const t=a.getResponseJson();Ws(Df,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case Rs.TIMEOUT:Ws(Df,`RPC '${e}' ${i} timed out`),o(new to(eo.DEADLINE_EXCEEDED,"Request time out"));break;case Rs.HTTP_ERROR:const n=a.getStatus();if(Ws(Df,`RPC '${e}' ${i} failed with status:`,n,"response text:",a.getResponseText()),n>0){let e=a.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(eo).indexOf(t)>=0?t:eo.UNKNOWN}(t.status);o(new to(e,t.message))}else o(new to(eo.UNKNOWN,"Server responded with status "+a.getStatus()))}else o(new to(eo.UNAVAILABLE,"Connection failed."));break;default:Xs()}}finally{Ws(Df,`RPC '${e}' ${i} completed.`)}});const c=JSON.stringify(r);Ws(Df,`RPC '${e}' ${i} sending request:`,r),a.send(t,"POST",c,n,15)})}Ro(e,t,n){const r=xf(),i=[this.mo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=As(),o=Ps(),a={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},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(a.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(a.xmlHttpFactory=new Ls({})),this.Eo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const u=i.join("");Ws(Df,`Creating RPC '${e}' stream ${r}: ${u}`,a);const l=s.createWebChannel(u,a);let h=!1,d=!1;const f=new Nf({ro:t=>{d?Ws(Df,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(h||(Ws(Df,`Opening RPC '${e}' stream ${r} transport.`),l.open(),h=!0),Ws(Df,`RPC '${e}' stream ${r} sending:`,t),l.send(t))},oo:()=>l.close()}),p=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return p(l,qs.EventType.OPEN,()=>{d||Ws(Df,`RPC '${e}' stream ${r} transport opened.`)}),p(l,qs.EventType.CLOSE,()=>{d||(d=!0,Ws(Df,`RPC '${e}' stream ${r} transport closed`),f.wo())}),p(l,qs.EventType.ERROR,t=>{d||(d=!0,Hs(Df,`RPC '${e}' stream ${r} transport errored:`,t),f.wo(new to(eo.UNAVAILABLE,"The operation could not be completed")))}),p(l,qs.EventType.MESSAGE,t=>{var n;if(!d){const i=t.data[0];Js(!!i);const s=i,o=s.error||(null===(n=s[0])||void 0===n?void 0:n.error);if(o){Ws(Df,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=ll[e];if(void 0!==t)return fl(t)}(t),i=o.message;void 0===n&&(n=eo.INTERNAL,i="Unknown error status: "+t+" with message "+o.message),d=!0,f.wo(new to(n,i)),l.close()}else Ws(Df,`RPC '${e}' stream ${r} received:`,i),f._o(i)}}),p(o,Ms.STAT_EVENT,t=>{t.stat===Fs.PROXY?Ws(Df,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===Fs.NOPROXY&&Ws(Df,`RPC '${e}' stream ${r} detected no buffering proxy`)}),setTimeout(()=>{f.fo()},0),f}}function Pf(){return"undefined"!=typeof window?window:null}function Rf(){return"undefined"!=typeof document?document:null}function Of(e){return new Ol(e,!0)}class Mf{constructor(e,t,n=1e3,r=1.5,i=6e4){this.ii=e,this.timerId=t,this.Po=n,this.bo=r,this.Vo=i,this.So=0,this.Do=null,this.Co=Date.now(),this.reset()}reset(){this.So=0}xo(){this.So=this.Vo}No(e){this.cancel();const t=Math.floor(this.So+this.ko()),n=Math.max(0,Date.now()-this.Co),r=Math.max(0,t-n);r>0&&Ws("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.So} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Do=this.ii.enqueueAfterDelay(this.timerId,r,()=>(this.Co=Date.now(),e())),this.So*=this.bo,this.So<this.Po&&(this.So=this.Po),this.So>this.Vo&&(this.So=this.Vo)}Mo(){null!==this.Do&&(this.Do.skipDelay(),this.Do=null)}cancel(){null!==this.Do&&(this.Do.cancel(),this.Do=null)}ko(){return(Math.random()-.5)*this.So}}class Ff{constructor(e,t,n,r,i,s,o,a){this.ii=e,this.$o=n,this.Oo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Fo=0,this.Bo=null,this.Lo=null,this.stream=null,this.qo=new Mf(e,t)}Uo(){return 1===this.state||5===this.state||this.Ko()}Ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Go()}async stop(){this.Uo()&&await this.close(0)}Qo(){this.state=0,this.qo.reset()}jo(){this.Ko()&&null===this.Bo&&(this.Bo=this.ii.enqueueAfterDelay(this.$o,6e4,()=>this.zo()))}Wo(e){this.Ho(),this.stream.send(e)}async zo(){if(this.Ko())return this.close(0)}Ho(){this.Bo&&(this.Bo.cancel(),this.Bo=null)}Jo(){this.Lo&&(this.Lo.cancel(),this.Lo=null)}async close(e,t){this.Ho(),this.Jo(),this.qo.cancel(),this.Fo++,4!==e?this.qo.reset():t&&t.code===eo.RESOURCE_EXHAUSTED?(Qs(t.toString()),Qs("Using maximum backoff delay to prevent overloading the backend."),this.qo.xo()):t&&t.code===eo.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Yo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.ao(t)}Yo(){}auth(){this.state=1;const e=this.Xo(this.Fo),t=this.Fo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.Fo===t&&this.Zo(e,n)},t=>{e(()=>{const e=new to(eo.UNKNOWN,"Fetching auth token failed: "+t.message);return this.tu(e)})})}Zo(e,t){const n=this.Xo(this.Fo);this.stream=this.eu(e,t),this.stream.uo(()=>{n(()=>(this.state=2,this.Lo=this.ii.enqueueAfterDelay(this.Oo,1e4,()=>(this.Ko()&&(this.state=3),Promise.resolve())),this.listener.uo()))}),this.stream.ao(e=>{n(()=>this.tu(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Go(){this.state=5,this.qo.No(async()=>{this.state=0,this.start()})}tu(e){return Ws("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Xo(e){return t=>{this.ii.enqueueAndForget(()=>this.Fo===e?t():(Ws("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class Lf extends Ff{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}eu(e,t){return this.connection.Ro("Listen",e,t)}onMessage(e){this.qo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:Xs()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(Js(void 0===t||"string"==typeof t),qa.fromBase64String(t||"")):(Js(void 0===t||t instanceof Uint8Array),qa.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?eo.UNKNOWN:fl(e.code);return new to(t,e.message||"")}(o);n=new Sl(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=zl(e,r.document.name),s=Vl(r.document.updateTime),o=r.document.createTime?Vl(r.document.createTime):_o.min(),a=new gc({mapValue:{fields:r.document.fields}}),c=yc.newFoundDocument(i,s,o,a),u=r.targetIds||[],l=r.removedTargetIds||[];n=new Cl(u,l,c.key,c)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=zl(e,r.document),s=r.readTime?Vl(r.readTime):_o.min(),o=yc.newNoDocument(i,s),a=r.removedTargetIds||[];n=new Cl([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=zl(e,r.document),s=r.removedTargetIds||[];n=new Cl([],s,i,null)}else{if(!("filter"in t))return Xs();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new ul(r,i),o=e.targetId;n=new Tl(o,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return _o.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?_o.min():t.readTime?Vl(t.readTime):_o.min()}(e);return this.listener.nu(t,n)}su(e){const t={};t.database=Kl(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=Kc(r)?{documents:Jl(e,r)}:{query:Zl(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=Ll(e,t.resumeToken);const r=Ml(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(_o.min())>0){n.readTime=Fl(e,t.snapshotVersion.toTimestamp());const r=Ml(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Xs()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.Wo(t)}iu(e){const t={};t.database=Kl(this.serializer),t.removeTarget=e,this.Wo(t)}}class qf extends Ff{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.ru=!1}get ou(){return this.ru}start(){this.ru=!1,this.lastStreamToken=void 0,super.start()}Yo(){this.ru&&this.uu([])}eu(e,t){return this.connection.Ro("Write",e,t)}onMessage(e){if(Js(!!e.streamToken),this.lastStreamToken=e.streamToken,this.ru){this.qo.reset();const t=function(e,t){return e&&e.length>0?(Js(void 0!==t),e.map(e=>function(e,t){let n=e.updateTime?Vl(e.updateTime):Vl(t);return n.isEqual(_o.min())&&(n=Vl(t)),new $u(n,e.transformResults||[])}(e,t))):[]}(e.writeResults,e.commitTime),n=Vl(e.commitTime);return this.listener.cu(n,t)}return Js(!e.writeResults||0===e.writeResults.length),this.ru=!0,this.listener.au()}hu(){const e={};e.database=Kl(this.serializer),this.Wo(e)}uu(e){const t={streamToken:this.lastStreamToken,writes:e.map(e=>Yl(this.serializer,e))};this.Wo(t)}}class Vf extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.lu=!1}fu(){if(this.lu)throw new to(eo.FAILED_PRECONDITION,"The client has already been terminated.")}Io(e,t,n){return this.fu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([r,i])=>this.connection.Io(e,t,n,r,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===eo.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new to(eo.UNKNOWN,e.toString())})}vo(e,t,n,r){return this.fu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.vo(e,t,n,i,s,r)).catch(e=>{throw"FirebaseError"===e.name?(e.code===eo.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new to(eo.UNKNOWN,e.toString())})}terminate(){this.lu=!0}}class jf{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.wu=0,this._u=null,this.mu=!0}gu(){0===this.wu&&(this.yu("Unknown"),this._u=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._u=null,this.pu("Backend didn't respond within 10 seconds."),this.yu("Offline"),Promise.resolve())))}Iu(e){"Online"===this.state?this.yu("Unknown"):(this.wu++,this.wu>=1&&(this.Tu(),this.pu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.yu("Offline")))}set(e){this.Tu(),this.wu=0,"Online"===e&&(this.mu=!1),this.yu(e)}yu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}pu(e){const 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.mu?(Qs(t),this.mu=!1):Ws("OnlineStateTracker",t)}Tu(){null!==this._u&&(this._u.cancel(),this._u=null)}}class Bf{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Eu=[],this.Au=new Map,this.vu=new Set,this.Ru=[],this.Pu=i,this.Pu.Yr(e=>{n.enqueueAndForget(async()=>{Yf(this)&&(Ws("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=Zs(e);t.vu.add(4),await zf(t),t.bu.set("Unknown"),t.vu.delete(4),await Uf(t)}(this))})}),this.bu=new jf(n,r)}}async function Uf(e){if(Yf(e))for(const t of e.Ru)await t(!0)}async function zf(e){for(const t of e.Ru)await t(!1)}function $f(e,t){const n=Zs(e);n.Au.has(t.targetId)||(n.Au.set(t.targetId,t),Hf(n)?Qf(n):pp(n).Ko()&&Kf(n,t))}function Gf(e,t){const n=Zs(e),r=pp(n);n.Au.delete(t),r.Ko()&&Wf(n,t),0===n.Au.size&&(r.Ko()?r.jo():Yf(n)&&n.bu.set("Unknown"))}function Kf(e,t){if(e.Vu.qt(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(_o.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}pp(e).su(t)}function Wf(e,t){e.Vu.qt(t),pp(e).iu(t)}function Qf(e){e.Vu=new kl({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),le:t=>e.Au.get(t)||null,ue:()=>e.datastore.serializer.databaseId}),pp(e).start(),e.bu.gu()}function Hf(e){return Yf(e)&&!pp(e).Uo()&&e.Au.size>0}function Yf(e){return 0===Zs(e).vu.size}function Xf(e){e.Vu=void 0}async function Jf(e){e.Au.forEach((t,n)=>{Kf(e,t)})}async function Zf(e,t){Xf(e),Hf(e)?(e.bu.Iu(t),Qf(e)):e.bu.set("Unknown")}async function ep(e,t,n){if(e.bu.set("Online"),t instanceof Sl&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.Au.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Au.delete(r),e.Vu.removeTarget(r))}(e,t)}catch(n){Ws("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await tp(e,n)}else if(t instanceof Cl?e.Vu.Ht(t):t instanceof Tl?e.Vu.ne(t):e.Vu.Xt(t),!n.isEqual(_o.min()))try{const t=await rf(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.Vu.ce(t);return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.Au.get(r);i&&e.Au.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{const r=e.Au.get(t);if(!r)return;e.Au.set(t,r.withResumeToken(qa.EMPTY_BYTE_STRING,r.snapshotVersion)),Wf(e,t);const i=new lh(r.target,t,n,r.sequenceNumber);Kf(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){Ws("RemoteStore","Failed to raise snapshot:",t),await tp(e,t)}}async function tp(e,t,n){if(!Bo(t))throw t;e.vu.add(1),await zf(e),e.bu.set("Offline"),n||(n=()=>rf(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Ws("RemoteStore","Retrying IndexedDB access"),await n(),e.vu.delete(1),await Uf(e)})}function np(e,t){return t().catch(n=>tp(e,n,t))}async function rp(e){const t=Zs(e),n=gp(t);let r=t.Eu.length>0?t.Eu[t.Eu.length-1].batchId:-1;for(;ip(t);)try{const e=await of(t.localStore,r);if(null===e){0===t.Eu.length&&n.jo();break}r=e.batchId,sp(t,e)}catch(e){await tp(t,e)}op(t)&&ap(t)}function ip(e){return Yf(e)&&e.Eu.length<10}function sp(e,t){e.Eu.push(t);const n=gp(e);n.Ko()&&n.ou&&n.uu(t.mutations)}function op(e){return Yf(e)&&!gp(e).Uo()&&e.Eu.length>0}function ap(e){gp(e).start()}async function cp(e){gp(e).hu()}async function up(e){const t=gp(e);for(const n of e.Eu)t.uu(n.mutations)}async function lp(e,t,n){const r=e.Eu.shift(),i=al.from(r,t,n);await np(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await rp(e)}async function hp(e,t){t&&gp(e).ou&&await async function(e,t){if(dl(n=t.code)&&n!==eo.ABORTED){const n=e.Eu.shift();gp(e).Qo(),await np(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await rp(e)}var n}(e,t),op(e)&&ap(e)}async function dp(e,t){const n=Zs(e);n.asyncQueue.verifyOperationInProgress(),Ws("RemoteStore","RemoteStore received new credentials");const r=Yf(n);n.vu.add(3),await zf(n),r&&n.bu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.vu.delete(3),await Uf(n)}async function fp(e,t){const n=Zs(e);t?(n.vu.delete(2),await Uf(n)):t||(n.vu.add(2),await zf(n),n.bu.set("Unknown"))}function pp(e){return e.Su||(e.Su=function(e,t,n){const r=Zs(e);return r.fu(),new Lf(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{uo:Jf.bind(null,e),ao:Zf.bind(null,e),nu:ep.bind(null,e)}),e.Ru.push(async t=>{t?(e.Su.Qo(),Hf(e)?Qf(e):e.bu.set("Unknown")):(await e.Su.stop(),Xf(e))})),e.Su}function gp(e){return e.Du||(e.Du=function(e,t,n){const r=Zs(e);return r.fu(),new qf(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{uo:cp.bind(null,e),ao:hp.bind(null,e),au:up.bind(null,e),cu:lp.bind(null,e)}),e.Ru.push(async t=>{t?(e.Du.Qo(),await rp(e)):(await e.Du.stop(),e.Eu.length>0&&(Ws("RemoteStore",`Stopping write stream with ${e.Eu.length} pending writes`),e.Eu=[]))})),e.Du}class mp{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new no,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 mp(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 to(eo.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 yp(e,t){if(Qs("AsyncQueue",`${t}: ${e}`),Bo(e))return new to(eo.UNAVAILABLE,`${t}: ${e}`);throw e}class _p{constructor(e){this.comparator=e?(t,n)=>e(t,n)||Eo.comparator(t.key,n.key):(e,t)=>Eo.comparator(e.key,t.key),this.keyedMap=_u(),this.sortedSet=new Da(this.comparator)}static emptySet(e){return new _p(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){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!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){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof _p))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 e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new _p;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class vp{constructor(){this.Cu=new Da(Eo.comparator)}track(e){const t=e.doc.key,n=this.Cu.get(t);n?0!==e.type&&3===n.type?this.Cu=this.Cu.insert(t,e):3===e.type&&1!==n.type?this.Cu=this.Cu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Cu=this.Cu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Cu=this.Cu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Cu=this.Cu.remove(t):1===e.type&&2===n.type?this.Cu=this.Cu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Cu=this.Cu.insert(t,{type:2,doc:e.doc}):Xs():this.Cu=this.Cu.insert(t,e)}xu(){const e=[];return this.Cu.inorderTraversal((t,n)=>{e.push(n)}),e}}class wp{constructor(e,t,n,r,i,s,o,a,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new wp(e,t,_p.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&au(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 e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class bp{constructor(){this.Nu=void 0,this.listeners=[]}}class Ip{constructor(){this.queries=new pu(e=>cu(e),au),this.onlineState="Unknown",this.ku=new Set}}async function Ep(e,t){const n=Zs(e),r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new bp),i)try{s.Nu=await n.onListen(r)}catch(e){const n=yp(e,`Initialization of query '${uu(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Mu(n.onlineState),s.Nu&&t.$u(s.Nu)&&xp(n)}async function Cp(e,t){const n=Zs(e),r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);e>=0&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Tp(e,t){const n=Zs(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.$u(e)&&(r=!0);i.Nu=e}}r&&xp(n)}function Sp(e,t,n){const r=Zs(e),i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}function xp(e){e.ku.forEach(e=>{e.next()})}class kp{constructor(e,t,n){this.query=e,this.Ou=t,this.Fu=!1,this.Bu=null,this.onlineState="Unknown",this.options=n||{}}$u(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new wp(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Fu?this.Lu(e)&&(this.Ou.next(e),t=!0):this.qu(e,this.onlineState)&&(this.Uu(e),t=!0),this.Bu=e,t}onError(e){this.Ou.error(e)}Mu(e){this.onlineState=e;let t=!1;return this.Bu&&!this.Fu&&this.qu(this.Bu,e)&&(this.Uu(this.Bu),t=!0),t}qu(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.Ku||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Lu(e){if(e.docChanges.length>0)return!0;const t=this.Bu&&this.Bu.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Uu(e){e=wp.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Fu=!0,this.Ou.next(e)}}class Np{constructor(e,t){this.Gu=e,this.byteLength=t}Qu(){return"metadata"in this.Gu}}class Dp{constructor(e){this.serializer=e}rr(e){return zl(this.serializer,e)}ur(e){return e.metadata.exists?Hl(this.serializer,e.document,!1):yc.newNoDocument(this.rr(e.metadata.name),this.cr(e.metadata.readTime))}cr(e){return Vl(e)}}class Ap{constructor(e,t,n){this.ju=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Pp(e)}zu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.Gu.namedQuery)this.queries.push(e.Gu.namedQuery);else if(e.Gu.documentMetadata){this.documents.push({metadata:e.Gu.documentMetadata}),e.Gu.documentMetadata.exists||++t;const n=wo.fromString(e.Gu.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.Gu.document&&(this.documents[this.documents.length-1].document=e.Gu.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Wu(e){const t=new Map,n=new Dp(this.serializer);for(const r of e)if(r.metadata.queries){const e=n.rr(r.metadata.name);for(const n of r.metadata.queries){const r=(t.get(n)||Tu()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=Zs(e);let s=Tu(),o=mu();for(const e of n){const n=t.rr(e.metadata.name);e.document&&(s=s.add(n));const r=t.ur(e);r.setReadTime(t.cr(e.metadata.readTime)),o=o.insert(n,r)}const a=i.Zi.newChangeBuffer({trackRemovals:!0}),c=await af(i,function(e){return iu(Jc(wo.fromString(`__bundle__/docs/${e}`)))}(r));return i.persistence.runTransaction("Apply bundle documents","readwrite",e=>sf(e,a,o).next(t=>(a.apply(e),t)).next(t=>i.Bs.removeMatchingKeysForTargetId(e,c.targetId).next(()=>i.Bs.addMatchingKeys(e,s,c.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(e,t.nr,t.sr)).next(()=>t.nr)))}(this.localStore,new Dp(this.serializer),this.documents,this.ju.id),t=this.Wu(this.documents);for(const e of this.queries)await ff(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Hu:this.collectionGroups,Ju:e}}}function Pp(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Rp{constructor(e){this.key=e}}class Op{constructor(e){this.key=e}}class Mp{constructor(e,t){this.query=e,this.Yu=t,this.Xu=null,this.hasCachedResults=!1,this.current=!1,this.Zu=Tu(),this.mutatedKeys=Tu(),this.tc=du(e),this.ec=new _p(this.tc)}get nc(){return this.Yu}sc(e,t){const n=t?t.ic:new vp,r=t?t.ec:this.ec;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,o=!1;const a="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,c="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal((e,t)=>{const u=r.get(e),l=lu(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;u&&l?u.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.rc(u,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.tc(l,a)>0||c&&this.tc(l,c)<0)&&(o=!0)):!u&&l?(n.track({type:0,doc:l}),f=!0):u&&!l&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(l?(s=s.add(l),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;){const e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{ec:s,ic:n,zi:o,mutatedKeys:i}}rc(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.ec;this.ec=e.ec,this.mutatedKeys=e.mutatedKeys;const i=e.ic.xu();i.sort((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Xs()}};return n(e)-n(t)}(e.type,t.type)||this.tc(e.doc,t.doc)),this.oc(n);const s=t?this.uc():[],o=0===this.Zu.size&&this.current?1:0,a=o!==this.Xu;return this.Xu=o,0!==i.length||a?{snapshot:new wp(this.query,e.ec,r,i,e.mutatedKeys,0===o,a,!1,!!n&&n.resumeToken.approximateByteSize()>0),cc:s}:{cc:s}}Mu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ec:this.ec,ic:new vp,mutatedKeys:this.mutatedKeys,zi:!1},!1)):{cc:[]}}ac(e){return!this.Yu.has(e)&&!!this.ec.has(e)&&!this.ec.get(e).hasLocalMutations}oc(e){e&&(e.addedDocuments.forEach(e=>this.Yu=this.Yu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Yu=this.Yu.delete(e)),this.current=e.current)}uc(){if(!this.current)return[];const e=this.Zu;this.Zu=Tu(),this.ec.forEach(e=>{this.ac(e.key)&&(this.Zu=this.Zu.add(e.key))});const t=[];return e.forEach(e=>{this.Zu.has(e)||t.push(new Op(e))}),this.Zu.forEach(n=>{e.has(n)||t.push(new Rp(n))}),t}hc(e){this.Yu=e.ir,this.Zu=Tu();const t=this.sc(e.documents);return this.applyChanges(t,!0)}lc(){return wp.fromInitialDocuments(this.query,this.ec,this.mutatedKeys,0===this.Xu,this.hasCachedResults)}}class Fp{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Lp{constructor(e){this.key=e,this.fc=!1}}class qp{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.dc={},this.wc=new pu(e=>cu(e),au),this._c=new Map,this.mc=new Set,this.gc=new Da(Eo.comparator),this.yc=new Map,this.Ic=new Fd,this.Tc={},this.Ec=new Map,this.Ac=dd.Mn(),this.onlineState="Unknown",this.vc=void 0}get isPrimaryClient(){return!0===this.vc}}async function Vp(e,t){const n=hg(e);let r,i;const s=n.wc.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.lc();else{const e=await af(n.localStore,iu(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await jp(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&$f(n.remoteStore,e)}return i}async function jp(e,t,n,r,i){e.Rc=(t,n,r)=>async function(e,t,n,r){let i=t.view.sc(n);i.zi&&(i=await uf(e.localStore,t.query,!1).then(({documents:e})=>t.view.sc(e,i)));const s=r&&r.targetChanges.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s);return Xp(e,t.targetId,o.cc),o.snapshot}(e,t,n,r);const s=await uf(e.localStore,t,!0),o=new Mp(t,s.ir),a=o.sc(s.documents),c=El.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=o.applyChanges(a,e.isPrimaryClient,c);Xp(e,n,u.cc);const l=new Fp(t,n,o);return e.wc.set(t,l),e._c.has(n)?e._c.get(n).push(t):e._c.set(n,[t]),u.snapshot}async function Bp(e,t){const n=Zs(e),r=n.wc.get(t),i=n._c.get(r.targetId);if(i.length>1)return n._c.set(r.targetId,i.filter(e=>!au(e,t))),void n.wc.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await cf(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),Gf(n.remoteStore,r.targetId),Hp(n,r.targetId)}).catch(Mo)):(Hp(n,r.targetId),await cf(n.localStore,r.targetId,!0))}async function Up(e,t){const n=Zs(e);try{const e=await function(e,t){const n=Zs(e),r=t.snapshotVersion;let i=n.Ji;return n.persistence.runTransaction("Apply remote event","readwrite-primary",e=>{const s=n.Zi.newChangeBuffer({trackRemovals:!0});i=n.Ji;const o=[];t.targetChanges.forEach((s,a)=>{const c=i.get(a);if(!c)return;o.push(n.Bs.removeMatchingKeys(e,s.removedDocuments,a).next(()=>n.Bs.addMatchingKeys(e,s.addedDocuments,a)));let u=c.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(qa.EMPTY_BYTE_STRING,_o.min()).withLastLimboFreeSnapshotVersion(_o.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,r)),i=i.insert(a,u),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(c,u,s)&&o.push(n.Bs.updateTargetData(e,u))});let a=mu(),c=Tu();if(t.documentUpdates.forEach(r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))}),o.push(sf(e,s,t.documentUpdates).next(e=>{a=e.nr,c=e.sr})),!r.isEqual(_o.min())){const t=n.Bs.getLastRemoteSnapshotVersion(e).next(t=>n.Bs.setTargetsMetadata(e,e.currentSequenceNumber,r));o.push(t)}return Fo.waitFor(o).next(()=>s.apply(e)).next(()=>n.localDocuments.getLocalViewOfDocuments(e,a,c)).next(()=>a)}).then(e=>(n.Ji=i,e))}(n.localStore,t);t.targetChanges.forEach((e,t)=>{const r=n.yc.get(t);r&&(Js(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.fc=!0:e.modifiedDocuments.size>0?Js(r.fc):e.removedDocuments.size>0&&(Js(r.fc),r.fc=!1))}),await eg(n,e,t)}catch(e){await Mo(e)}}function zp(e,t,n){const r=Zs(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.wc.forEach((n,r)=>{const i=r.view.Mu(t);i.snapshot&&e.push(i.snapshot)}),function(e,t){const n=Zs(e);n.onlineState=t;let r=!1;n.queries.forEach((e,n)=>{for(const e of n.listeners)e.Mu(t)&&(r=!0)}),r&&xp(n)}(r.eventManager,t),e.length&&r.dc.nu(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function $p(e,t,n){const r=Zs(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.yc.get(t),s=i&&i.key;if(s){let e=new Da(Eo.comparator);e=e.insert(s,yc.newNoDocument(s,_o.min()));const n=Tu().add(s),i=new Il(_o.min(),new Map,new Da(po),e,n);await Up(r,i),r.gc=r.gc.remove(s),r.yc.delete(t),Zp(r)}else await cf(r.localStore,t,!1).then(()=>Hp(r,t,n)).catch(Mo)}async function Gp(e,t){const n=Zs(e),r=t.batch.batchId;try{const e=await function(e,t){const n=Zs(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const r=t.batch.keys(),i=n.Zi.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let o=Fo.resolve();return s.forEach(e=>{o=o.next(()=>r.getEntry(t,e)).next(t=>{const s=n.docVersions.get(e);Js(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),o.next(()=>e.mutationQueue.removeMutationBatch(t,i))}(n,e,t,i).next(()=>i.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Tu();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))).next(()=>n.localDocuments.getDocuments(e,r))})}(n.localStore,t);Qp(n,r,null),Wp(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await eg(n,e)}catch(e){await Mo(e)}}async function Kp(e,t,n){const r=Zs(e);try{const e=await function(e,t){const n=Zs(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next(t=>(Js(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t))).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r)).next(()=>n.localDocuments.getDocuments(e,r))})}(r.localStore,t);Qp(r,t,n),Wp(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await eg(r,e)}catch(n){await Mo(n)}}function Wp(e,t){(e.Ec.get(t)||[]).forEach(e=>{e.resolve()}),e.Ec.delete(t)}function Qp(e,t,n){const r=Zs(e);let i=r.Tc[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Tc[r.currentUser.toKey()]=i}}function Hp(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e._c.get(t))e.wc.delete(r),n&&e.dc.Pc(r,n);e._c.delete(t),e.isPrimaryClient&&e.Ic.Is(t).forEach(t=>{e.Ic.containsKey(t)||Yp(e,t)})}function Yp(e,t){e.mc.delete(t.path.canonicalString());const n=e.gc.get(t);null!==n&&(Gf(e.remoteStore,n),e.gc=e.gc.remove(t),e.yc.delete(n),Zp(e))}function Xp(e,t,n){for(const r of n)r instanceof Rp?(e.Ic.addReference(r.key,t),Jp(e,r)):r instanceof Op?(Ws("SyncEngine","Document no longer in limbo: "+r.key),e.Ic.removeReference(r.key,t),e.Ic.containsKey(r.key)||Yp(e,r.key)):Xs()}function Jp(e,t){const n=t.key,r=n.path.canonicalString();e.gc.get(n)||e.mc.has(r)||(Ws("SyncEngine","New document in limbo: "+n),e.mc.add(r),Zp(e))}function Zp(e){for(;e.mc.size>0&&e.gc.size<e.maxConcurrentLimboResolutions;){const t=e.mc.values().next().value;e.mc.delete(t);const n=new Eo(wo.fromString(t)),r=e.Ac.next();e.yc.set(r,new Lp(n)),e.gc=e.gc.insert(n,r),$f(e.remoteStore,new lh(iu(Jc(n.path)),r,"TargetPurposeLimboResolution",Qo.ct))}}async function eg(e,t,n){const r=Zs(e),i=[],s=[],o=[];r.wc.isEmpty()||(r.wc.forEach((e,a)=>{o.push(r.Rc(a,t,n).then(e=>{if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(a.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){i.push(e);const t=Jd.Li(a.targetId,e);s.push(t)}}))}),await Promise.all(o),r.dc.nu(i),await async function(e,t){const n=Zs(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",e=>Fo.forEach(t,t=>Fo.forEach(t.Fi,r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r)).next(()=>Fo.forEach(t.Bi,r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))}catch(e){if(!Bo(e))throw e;Ws("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=n.Ji.get(t),r=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(r);n.Ji=n.Ji.insert(t,i)}}}(r.localStore,s))}async function tg(e,t){const n=Zs(e);if(!n.currentUser.isEqual(t)){Ws("SyncEngine","User change. New user:",t.toKey());const e=await nf(n.localStore,t);n.currentUser=t,function(e){e.Ec.forEach(e=>{e.forEach(e=>{e.reject(new to(eo.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Ec.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await eg(n,e.er)}}function ng(e,t){const n=Zs(e),r=n.yc.get(t);if(r&&r.fc)return Tu().add(r.key);{let e=Tu();const r=n._c.get(t);if(!r)return e;for(const t of r){const r=n.wc.get(t);e=e.unionWith(r.view.nc)}return e}}async function rg(e,t){const n=Zs(e),r=await uf(n.localStore,t.query,!0),i=t.view.hc(r);return n.isPrimaryClient&&Xp(n,t.targetId,i.cc),i}async function ig(e,t){const n=Zs(e);return hf(n.localStore,t).then(e=>eg(n,e))}async function sg(e,t,n,r){const i=Zs(e),s=await function(e,t){const n=Zs(e),r=Zs(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",e=>r.Sn(e,t).next(t=>t?n.localDocuments.getDocuments(e,t):Fo.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await rp(i.remoteStore):"acknowledged"===n||"rejected"===n?(Qp(i,t,r||null),Wp(i,t),function(e,t){Zs(Zs(e).mutationQueue).Cn(t)}(i.localStore,t)):Xs(),await eg(i,s)):Ws("SyncEngine","Cannot apply mutation batch with id: "+t)}async function og(e,t,n){const r=Zs(e),i=[],s=[];for(const e of t){let t;const n=r._c.get(e);if(n&&0!==n.length){t=await af(r.localStore,iu(n[0]));for(const e of n){const t=r.wc.get(e),n=await rg(r,t);n.snapshot&&s.push(n.snapshot)}}else{const n=await lf(r.localStore,e);t=await af(r.localStore,n),await jp(r,ag(n),e,!1,t.resumeToken)}i.push(t)}return r.dc.nu(s),i}function ag(e){return Xc(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function cg(e){const t=Zs(e);return Zs(Zs(t.localStore).persistence).$i()}async function ug(e,t,n,r){const i=Zs(e);if(i.vc)return void Ws("SyncEngine","Ignoring unexpected query state notification.");const s=i._c.get(t);if(s&&s.length>0)switch(n){case"current":case"not-current":{const e=await hf(i.localStore,hu(s[0])),r=Il.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,qa.EMPTY_BYTE_STRING);await eg(i,e,r);break}case"rejected":await cf(i.localStore,t,!0),Hp(i,t,r);break;default:Xs()}}async function lg(e,t,n){const r=hg(e);if(r.vc){for(const e of t){if(r._c.has(e)){Ws("SyncEngine","Adding an already active target "+e);continue}const t=await lf(r.localStore,e),n=await af(r.localStore,t);await jp(r,ag(t),n.targetId,!1,n.resumeToken),$f(r.remoteStore,n)}for(const e of n)r._c.has(e)&&await cf(r.localStore,e,!1).then(()=>{Gf(r.remoteStore,e),Hp(r,e)}).catch(Mo)}}function hg(e){const t=Zs(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Up.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=ng.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=$p.bind(null,t),t.dc.nu=Tp.bind(null,t.eventManager),t.dc.Pc=Sp.bind(null,t.eventManager),t}function dg(e){const t=Zs(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Gp.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Kp.bind(null,t),t}class fg{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=Of(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return tf(this.persistence,new Zd,e.initialUser,this.serializer)}createPersistence(e){return new Ud($d.zs,this.serializer)}createSharedClientState(e){return new Ef}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class pg extends fg{constructor(e,t,n){super(),this.Vc=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Vc.initialize(this,e),await dg(this.Vc.syncEngine),await rp(this.Vc.remoteStore),await this.persistence.Ii(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return tf(this.persistence,new Zd,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){const n=this.persistence.referenceDelegate.garbageCollector;return new vd(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){const n=new Wo(t,this.persistence);return new Ko(e.asyncQueue,n)}createPersistence(e){const t=Xd(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?id.withCacheSize(this.cacheSizeBytes):id.DEFAULT;return new Qd(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,Pf(),Rf(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new Ef}}class gg extends pg{constructor(e,t){super(e,t,!1),this.Vc=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const t=this.Vc.syncEngine;this.sharedClientState instanceof If&&(this.sharedClientState.syncEngine={jr:sg.bind(null,t),zr:ug.bind(null,t),Wr:lg.bind(null,t),$i:cg.bind(null,t),Qr:ig.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ii(async e=>{await async function(e,t){const n=Zs(e);if(hg(n),dg(n),!0===t&&!0!==n.vc){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await og(n,e.toArray());n.vc=!0,await fp(n.remoteStore,!0);for(const e of t)$f(n.remoteStore,e)}else if(!1===t&&!1!==n.vc){const e=[];let t=Promise.resolve();n._c.forEach((r,i)=>{n.sharedClientState.isLocalQueryTarget(i)?e.push(i):t=t.then(()=>(Hp(n,i),cf(n.localStore,i,!0))),Gf(n.remoteStore,i)}),await t,await og(n,e),function(e){const t=Zs(e);t.yc.forEach((e,n)=>{Gf(t.remoteStore,n)}),t.Ic.Ts(),t.yc=new Map,t.gc=new Da(Eo.comparator)}(n),n.vc=!1,await fp(n.remoteStore,!1)}}(this.Vc.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}createSharedClientState(e){const t=Pf();if(!If.D(t))throw new to(eo.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=Xd(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new If(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class mg{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=>zp(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=tg.bind(null,this.syncEngine),await fp(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Ip}createDatastore(e){const t=Of(e.databaseInfo.databaseId),n=(r=e.databaseInfo,new Af(r));var r;return function(e,t,n,r){return new Vf(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>zp(this.syncEngine,e,0),s=Tf.D()?new Tf:new Cf,new Bf(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 qp(e,t,n,r,i,s);return o&&(a.vc=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=Zs(e);Ws("RemoteStore","RemoteStore shutting down."),t.vu.add(5),await zf(t),t.Pu.shutdown(),t.bu.set("Unknown")}(this.remoteStore)}}function yg(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){const r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class _g{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Sc(this.observer.next,e)}error(e){this.observer.error?this.Sc(this.observer.error,e):Qs("Uncaught Error in snapshot listener:",e.toString())}Dc(){this.muted=!0}Sc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class vg{constructor(e,t){this.Cc=e,this.serializer=t,this.metadata=new no,this.buffer=new Uint8Array,this.xc=new TextDecoder("utf-8"),this.Nc().then(e=>{e&&e.Qu()?this.metadata.resolve(e.Gu.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.Gu)}`))},e=>this.metadata.reject(e))}close(){return this.Cc.cancel()}async getMetadata(){return this.metadata.promise}async bc(){return await this.getMetadata(),this.Nc()}async Nc(){const e=await this.kc();if(null===e)return null;const t=this.xc.decode(e),n=Number(t);isNaN(n)&&this.Mc(`length string (${t}) is not valid number`);const r=await this.$c(n);return new Np(JSON.parse(r),e.length+n)}Oc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async kc(){for(;this.Oc()<0&&!await this.Fc(););if(0===this.buffer.length)return null;const e=this.Oc();e<0&&this.Mc("Reached the end of bundle when a length string is expected.");const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async $c(e){for(;this.buffer.length<e;)await this.Fc()&&this.Mc("Reached the end of bundle when more is expected.");const t=this.xc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Mc(e){throw this.Cc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Fc(){const e=await this.Cc.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 wg{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(),this.mutations.length>0)throw new to(eo.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const n=Zs(e),r=Kl(n.serializer)+"/documents",i={documents:t.map(e=>Ul(n.serializer,e))},s=await n.vo("BatchGetDocuments",r,i,t.length),o=new Map;s.forEach(e=>{const t=function(e,t){return"found"in t?function(e,t){Js(!!t.found),t.found.name,t.found.updateTime;const n=zl(e,t.found.name),r=Vl(t.found.updateTime),i=t.found.createTime?Vl(t.found.createTime):_o.min(),s=new gc({mapValue:{fields:t.found.fields}});return yc.newFoundDocument(n,r,i,s)}(e,t):"missing"in t?function(e,t){Js(!!t.missing),Js(!!t.readTime);const n=zl(e,t.missing),r=Vl(t.readTime);return yc.newNoDocument(n,r)}(e,t):Xs()}(n.serializer,e);o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{const t=o.get(e.toString());Js(!!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 il(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const e=this.readVersions;this.mutations.forEach(t=>{e.delete(t.key.toString())}),e.forEach((e,t)=>{const n=Eo.fromPath(t);this.mutations.push(new sl(n,this.precondition(n)))}),await async function(e,t){const n=Zs(e),r=Kl(n.serializer)+"/documents",i={writes:t.map(e=>Yl(n.serializer,e))};await n.Io("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 Xs();t=_o.min()}const n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new to(eo.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(_o.min())?Gu.exists(!1):Gu.updateTime(t):Gu.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(_o.min()))throw new to(eo.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Gu.updateTime(t)}return Gu.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class bg{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Bc=n.maxAttempts,this.qo=new Mf(this.asyncQueue,"transaction_retry")}run(){this.Bc-=1,this.Lc()}Lc(){this.qo.No(async()=>{const e=new wg(this.datastore),t=this.qc(e);t&&t.then(t=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(t)}).catch(e=>{this.Uc(e)}))}).catch(e=>{this.Uc(e)})})}qc(e){try{const t=this.updateFunction(e);return!Ho(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}}Uc(e){this.Bc>0&&this.Kc(e)?(this.Bc-=1,this.asyncQueue.enqueueAndForget(()=>(this.Lc(),Promise.resolve()))):this.deferred.reject(e)}Kc(e){if("FirebaseError"===e.name){const t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!dl(t)}return!1}}class Ig{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=zs.UNAUTHENTICATED,this.clientId=fo.A(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Ws("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Ws("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 to(eo.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new no;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=yp(t,"Failed to shutdown persistence");e.reject(n)}}),e.promise}}async function Eg(e,t){e.asyncQueue.verifyOperationInProgress(),Ws("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await nf(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function Cg(e,t){e.asyncQueue.verifyOperationInProgress();const n=await Sg(e);Ws("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener(e=>dp(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>dp(t.remoteStore,n)),e._onlineComponents=t}function Tg(e){return"FirebaseError"===e.name?e.code===eo.FAILED_PRECONDITION||e.code===eo.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function Sg(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){Ws("FirestoreClient","Using user provided OfflineComponentProvider");try{await Eg(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!Tg(n))throw n;Hs("Error using user provided cache. Falling back to memory cache: "+n),await Eg(e,new fg)}}else Ws("FirestoreClient","Using default OfflineComponentProvider"),await Eg(e,new fg);return e._offlineComponents}async function xg(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Ws("FirestoreClient","Using user provided OnlineComponentProvider"),await Cg(e,e._uninitializedComponentsProvider._online)):(Ws("FirestoreClient","Using default OnlineComponentProvider"),await Cg(e,new mg))),e._onlineComponents}function kg(e){return Sg(e).then(e=>e.persistence)}function Ng(e){return Sg(e).then(e=>e.localStore)}function Dg(e){return xg(e).then(e=>e.remoteStore)}function Ag(e){return xg(e).then(e=>e.syncEngine)}async function Pg(e){const t=await xg(e),n=t.eventManager;return n.onListen=Vp.bind(null,t.syncEngine),n.onUnlisten=Bp.bind(null,t.syncEngine),n}function Rg(e,t,n={}){const r=new no;return e.asyncQueue.enqueueAndForget(async()=>function(e,t,n,r,i){const s=new _g({next:s=>{t.enqueueAndForget(()=>Cp(e,o));const a=s.docs.has(n);!a&&s.fromCache?i.reject(new to(eo.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&s.fromCache&&r&&"server"===r.source?i.reject(new to(eo.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.)')):i.resolve(s)},error:e=>i.reject(e)}),o=new kp(Jc(n.path),s,{includeMetadataChanges:!0,Ku:!0});return Ep(e,o)}(await Pg(e),e.asyncQueue,t,n,r)),r.promise}function Og(e,t,n={}){const r=new no;return e.asyncQueue.enqueueAndForget(async()=>function(e,t,n,r,i){const s=new _g({next:n=>{t.enqueueAndForget(()=>Cp(e,o)),n.fromCache&&"server"===r.source?i.reject(new to(eo.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(n)},error:e=>i.reject(e)}),o=new kp(n,s,{includeMetadataChanges:!0,Ku:!0});return Ep(e,o)}(await Pg(e),e.asyncQueue,t,n,r)),r.promise}function Mg(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Fg=new Map;function Lg(e,t,n){if(!n)throw new to(eo.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function qg(e,t,n,r){if(!0===t&&!0===r)throw new to(eo.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Vg(e){if(!Eo.isDocumentKey(e))throw new to(eo.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function jg(e){if(Eo.isDocumentKey(e))throw new to(eo.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Bg(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":Xs()}function Ug(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new to(eo.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Bg(e);throw new to(eo.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function zg(e,t){if(t<=0)throw new to(eo.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class $g{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new to(eo.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,this.cache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new to(eo.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}qg("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Mg(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new to(eo.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new to(eo.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new to(eo.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}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&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class Gg{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new $g({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new to(eo.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 to(eo.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 $g(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new io;switch(e.type){case"firstParty":return new co(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new to(eo.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=Fg.get(e);t&&(Ws("ComponentProvider","Removing Datastore"),Fg.delete(e),t.terminate())}(this),Promise.resolve()}}class Kg{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 Qg(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Kg(this.firestore,e,this._key)}}class Wg{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Wg(this.firestore,e,this._query)}}class Qg extends Wg{constructor(e,t,n){super(e,t,Jc(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 Kg(this.firestore,null,new Eo(e))}withConverter(e){return new Qg(this.firestore,e,this._path)}}function Hg(e,t,...n){if(e=j(e),Lg("collection","path",t),e instanceof Gg){const r=wo.fromString(t,...n);return jg(r),new Qg(e,null,r)}{if(!(e instanceof Kg||e instanceof Qg))throw new to(eo.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(wo.fromString(t,...n));return jg(r),new Qg(e.firestore,null,r)}}function Yg(e,t,...n){if(e=j(e),1===arguments.length&&(t=fo.A()),Lg("doc","path",t),e instanceof Gg){const r=wo.fromString(t,...n);return Vg(r),new Kg(e,null,new Eo(r))}{if(!(e instanceof Kg||e instanceof Qg))throw new to(eo.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(wo.fromString(t,...n));return Vg(r),new Kg(e.firestore,e instanceof Qg?e.converter:null,new Eo(r))}}function Xg(e,t){return e=j(e),t=j(t),(e instanceof Kg||e instanceof Qg)&&(t instanceof Kg||t instanceof Qg)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Jg(e,t){return e=j(e),t=j(t),e instanceof Wg&&t instanceof Wg&&e.firestore===t.firestore&&au(e._query,t._query)&&e.converter===t.converter}class Zg{constructor(){this.Gc=Promise.resolve(),this.Qc=[],this.jc=!1,this.zc=[],this.Wc=null,this.Hc=!1,this.Jc=!1,this.Yc=[],this.qo=new Mf(this,"async_queue_retry"),this.Xc=()=>{const e=Rf();e&&Ws("AsyncQueue","Visibility state changed to "+e.visibilityState),this.qo.Mo()};const e=Rf();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Xc)}get isShuttingDown(){return this.jc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Zc(),this.ta(e)}enterRestrictedMode(e){if(!this.jc){this.jc=!0,this.Jc=e||!1;const t=Rf();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Xc)}}enqueue(e){if(this.Zc(),this.jc)return new Promise(()=>{});const t=new no;return this.ta(()=>this.jc&&this.Jc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Qc.push(e),this.ea()))}async ea(){if(0!==this.Qc.length){try{await this.Qc[0](),this.Qc.shift(),this.qo.reset()}catch(e){if(!Bo(e))throw e;Ws("AsyncQueue","Operation failed with retryable error: "+e)}this.Qc.length>0&&this.qo.No(()=>this.ea())}}ta(e){const t=this.Gc.then(()=>(this.Hc=!0,e().catch(e=>{this.Wc=e,this.Hc=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw Qs("INTERNAL UNHANDLED ERROR: ",t),e}).then(e=>(this.Hc=!1,e))));return this.Gc=t,t}enqueueAfterDelay(e,t,n){this.Zc(),this.Yc.indexOf(e)>-1&&(t=0);const r=mp.createAndSchedule(this,e,t,n,e=>this.na(e));return this.zc.push(r),r}Zc(){this.Wc&&Xs()}verifyOperationInProgress(){}async sa(){let e;do{e=this.Gc,await e}while(e!==this.Gc)}ia(e){for(const t of this.zc)if(t.timerId===e)return!0;return!1}ra(e){return this.sa().then(()=>{this.zc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const t of this.zc)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.sa()})}oa(e){this.Yc.push(e)}na(e){const t=this.zc.indexOf(e);this.zc.splice(t,1)}}function em(e){return function(e){if("object"!=typeof e||null===e)return!1;const t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return!0;return!1}(e)}class tm{constructor(){this._progressObserver={},this._taskCompletionResolver=new no,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)}}class nm extends Gg{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new Zg,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||im(this),this._firestoreClient.terminate()}}function rm(e){return e._firestoreClient||im(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function im(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new Ka(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Mg(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,i);e._firestoreClient=new Ig(e._authCredentials,e._appCheckCredentials,e._queue,s),(null===(n=i.cache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=i.cache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:i.cache.kind,_offline:i.cache._offlineComponentProvider,_online:i.cache._onlineComponentProvider})}function sm(e,t,n){const r=new no;return e.asyncQueue.enqueue(async()=>{try{await Eg(e,n),await Cg(e,t),r.resolve()}catch(e){const t=e;if(!Tg(t))throw t;Hs("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function om(e){if(e._initialized||e._terminated)throw new to(eo.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 am{constructor(e){this._byteString=e}static fromBase64String(e){try{return new am(qa.fromBase64String(e))}catch(e){throw new to(eo.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new am(qa.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 cm{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new to(eo.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Io(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class um{constructor(e){this._methodName=e}}class lm{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new to(eo.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new to(eo.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 po(this._lat,e._lat)||po(this._long,e._long)}}const hm=/^__.*__$/;class dm{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new el(e,this.data,this.fieldMask,t,this.fieldTransforms):new Zu(e,this.data,t,this.fieldTransforms)}}class fm{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new el(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function pm(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Xs()}}class gm{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.ua(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get ca(){return this.settings.ca}aa(e){return new gm(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ha(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.aa({path:n,la:!1});return r.fa(e),r}da(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.aa({path:n,la:!1});return r.ua(),r}wa(e){return this.aa({path:void 0,la:!0})}_a(e){return Mm(e,this.settings.methodName,this.settings.ma||!1,this.path,this.settings.ga)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}ua(){if(this.path)for(let e=0;e<this.path.length;e++)this.fa(this.path.get(e))}fa(e){if(0===e.length)throw this._a("Document fields must not be empty");if(pm(this.ca)&&hm.test(e))throw this._a('Document fields cannot begin and end with "__"')}}class mm{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||Of(e)}ya(e,t,n,r=!1){return new gm({ca:e,methodName:t,ga:n,path:Io.emptyPath(),la:!1,ma:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ym(e){const t=e._freezeSettings(),n=Of(e._databaseId);return new mm(e._databaseId,!!t.ignoreUndefinedProperties,n)}function _m(e,t,n,r,i,s={}){const o=e.ya(s.merge||s.mergeFields?2:0,t,n,i);Am("Data must be an object, but it was:",o,r);const a=Nm(r,o);let c,u;if(s.merge)c=new Fa(o.fieldMask),u=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Pm(t,r,n);if(!o.contains(i))throw new to(eo.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Fm(e,i)||e.push(i)}c=new Fa(e),u=o.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,u=o.fieldTransforms;return new dm(new gc(a),c,u)}class vm extends um{_toFieldTransform(e){if(2!==e.ca)throw 1===e.ca?e._a(`${this._methodName}() can only appear at the top level of your update data`):e._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof vm}}function wm(e,t,n){return new gm({ca:3,ga:t.settings.ga,methodName:e._methodName,la:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class bm extends um{_toFieldTransform(e){return new zu(e.path,new Mu)}isEqual(e){return e instanceof bm}}class Im extends um{constructor(e,t){super(e),this.pa=t}_toFieldTransform(e){const t=wm(this,e,!0),n=this.pa.map(e=>km(e,t)),r=new Fu(n);return new zu(e.path,r)}isEqual(e){return this===e}}class Em extends um{constructor(e,t){super(e),this.pa=t}_toFieldTransform(e){const t=wm(this,e,!0),n=this.pa.map(e=>km(e,t)),r=new qu(n);return new zu(e.path,r)}isEqual(e){return this===e}}class Cm extends um{constructor(e,t){super(e),this.Ia=t}_toFieldTransform(e){const t=new ju(e.serializer,Du(e.serializer,this.Ia));return new zu(e.path,t)}isEqual(e){return this===e}}function Tm(e,t,n,r){const i=e.ya(1,t,n);Am("Data must be an object, but it was:",i,r);const s=[],o=gc.empty();ka(r,(e,r)=>{const a=Om(t,e,n);r=j(r);const c=i.da(a);if(r instanceof vm)s.push(a);else{const e=km(r,c);null!=e&&(s.push(a),o.set(a,e))}});const a=new Fa(s);return new fm(o,a,i.fieldTransforms)}function Sm(e,t,n,r,i,s){const o=e.ya(1,t,n),a=[Pm(t,r,n)],c=[i];if(s.length%2!=0)throw new to(eo.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)a.push(Pm(t,s[e])),c.push(s[e+1]);const u=[],l=gc.empty();for(let e=a.length-1;e>=0;--e)if(!Fm(u,a[e])){const t=a[e];let n=c[e];n=j(n);const r=o.da(t);if(n instanceof vm)u.push(t);else{const e=km(n,r);null!=e&&(u.push(t),l.set(t,e))}}const h=new Fa(u);return new fm(l,h,o.fieldTransforms)}function xm(e,t,n,r=!1){return km(n,e.ya(r?4:3,t))}function km(e,t){if(Dm(e=j(e)))return Am("Unsupported field value:",t,e),Nm(e,t);if(e instanceof um)return function(e,t){if(!pm(t.ca))throw t._a(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t._a(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.la&&4!==t.ca)throw t._a("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=km(i,t.wa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=j(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Du(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=yo.fromDate(e);return{timestampValue:Fl(t.serializer,n)}}if(e instanceof yo){const n=new yo(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Fl(t.serializer,n)}}if(e instanceof lm)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof am)return{bytesValue:Ll(t.serializer,e._byteString)};if(e instanceof Kg){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t._a(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:jl(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t._a(`Unsupported field value: ${Bg(e)}`)}(e,t)}function Nm(e,t){const n={};return Na(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):ka(e,(e,r)=>{const i=km(r,t.ha(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function Dm(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof yo||e instanceof lm||e instanceof am||e instanceof Kg||e instanceof um)}function Am(e,t,n){if(!Dm(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Bg(n);throw"an object"===r?t._a(e+" a custom object"):t._a(e+" "+r)}}function Pm(e,t,n){if((t=j(t))instanceof cm)return t._internalPath;if("string"==typeof t)return Om(e,t);throw Mm("Field path arguments must be of type string or ",e,!1,void 0,n)}const Rm=new RegExp("[~\\*/\\[\\]]");function Om(e,t,n){if(t.search(Rm)>=0)throw Mm(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new cm(...t.split("."))._internalPath}catch(r){throw Mm(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Mm(e,t,n,r,i){const 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 to(eo.INVALID_ARGUMENT,a+e+c)}function Fm(e,t){return e.some(e=>e.isEqual(t))}class Lm{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 Kg(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new qm(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){const t=this._document.data.field(Vm("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class qm extends Lm{data(){return super.data()}}function Vm(e,t){return"string"==typeof t?Om(e,t):t instanceof cm?t._internalPath:t._delegate._internalPath}function jm(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new to(eo.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Bm{}class Um extends Bm{}function zm(e,t,...n){let r=[];t instanceof Bm&&r.push(t),r=r.concat(n),function(e){const t=e.filter(e=>e instanceof Gm).length,n=e.filter(e=>e instanceof $m).length;if(t>1||t>0&&n>0)throw new to(eo.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class $m extends Um{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new $m(e,t,n)}_apply(e){const t=this._parse(e);return Zm(e._query,t),new Wg(e.firestore,e.converter,su(e._query,t))}_parse(e){const t=ym(e.firestore),n=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new to(eo.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){Jm(o,s);const t=[];for(const n of o)t.push(Xm(r,e,n));a={arrayValue:{values:t}}}else a=Xm(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||Jm(o,s),a=xm(n,"where",o,"in"===s||"not-in"===s);return Cc.create(i,s,a)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value);return n}}class Gm extends Bm{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Gm(e,t)}_parse(e){const t=this._queryConstraints.map(t=>t._parse(e)).filter(e=>e.getFilters().length>0);return 1===t.length?t[0]:Tc.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const e of r)Zm(n,e),n=su(n,e)}(e._query,t),new Wg(e.firestore,e.converter,su(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class Km extends Um{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Km(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new to(eo.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new to(eo.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const r=new bc(t,n);return function(e,t){if(null===eu(e)){const n=tu(e);null!==n&&ey(0,n,t.field)}}(e,r),r}(e._query,this._field,this._direction);return new Wg(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new Yc(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class Wm extends Um{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new Wm(e,t,n)}_apply(e){return new Wg(e.firestore,e.converter,ou(e._query,this._limit,this._limitType))}}class Qm extends Um{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Qm(e,t,n)}_apply(e){const t=Ym(e,this.type,this._docOrFields,this._inclusive);return new Wg(e.firestore,e.converter,function(e,t){return new Yc(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}class Hm extends Um{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Hm(e,t,n)}_apply(e){const t=Ym(e,this.type,this._docOrFields,this._inclusive);return new Wg(e.firestore,e.converter,function(e,t){return new Yc(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}function Ym(e,t,n,r){if(n[0]=j(n[0]),n[0]instanceof Lm)return function(e,t,n,r,i){if(!r)throw new to(eo.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of ru(e))if(n.field.isKeyField())s.push(rc(t,r.key));else{const e=r.data.field(n.field);if(za(e))throw new to(eo.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 to(eo.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 _c(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const i=ym(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new to(eo.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 s=0;s<i.length;s++){const c=i[s];if(o[s].field.isKeyField()){if("string"!=typeof c)throw new to(eo.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!nu(e)&&-1!==c.indexOf("/"))throw new to(eo.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(wo.fromString(c));if(!Eo.isDocumentKey(n))throw new to(eo.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 Eo(n);a.push(rc(t,i))}else{const e=xm(n,r,c);a.push(e)}}return new _c(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function Xm(e,t,n){if("string"==typeof(n=j(n))){if(""===n)throw new to(eo.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!nu(t)&&-1!==n.indexOf("/"))throw new to(eo.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const r=t.path.child(wo.fromString(n));if(!Eo.isDocumentKey(r))throw new to(eo.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 rc(e,new Eo(r))}if(n instanceof Kg)return rc(e,n._key);throw new to(eo.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Bg(n)}.`)}function Jm(e,t){if(!Array.isArray(e)||0===e.length)throw new to(eo.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Zm(e,t){if(t.isInequality()){const n=tu(e),r=t.field;if(null!==n&&!n.isEqual(r))throw new to(eo.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 '${n.toString()}' and '${r.toString()}'`);const i=eu(e);null!==i&&ey(0,r,i)}const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new to(eo.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new to(eo.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function ey(e,t,n){if(!n.isEqual(t))throw new to(eo.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 ty{convertValue(e,t="none"){switch(Ya(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Ba(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(Ua(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 Xs()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return ka(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertGeoPoint(e){return new lm(Ba(e.latitude),Ba(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":const n=$a(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ga(e));default:return null}}convertTimestamp(e){const t=ja(e);return new yo(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=wo.fromString(e);Js(uh(n));const r=new Wa(n.get(1),n.get(3)),i=new Eo(n.popFirst(5));return r.isEqual(t)||Qs(`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 ny(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class ry extends ty{constructor(e){super(),this.firestore=e}convertBytes(e){return new am(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Kg(this.firestore,null,t)}}class iy{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class sy extends Lm{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){const t=new oy(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){const n=this._document.data.field(Vm("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class oy extends sy{data(e={}){return super.data(e)}}class ay{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new iy(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach(n=>{e.call(t,new oy(this._firestore,this._userDataWriter,n.key,n,new iy(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new to(eo.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(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map(n=>{const r=new oy(e._firestore,e._userDataWriter,n.doc.key,n.doc,new iy(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}})}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>t||3!==e.type).map(t=>{const r=new oy(e._firestore,e._userDataWriter,t.doc.key,t.doc,new iy(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:cy(t.type),doc:r,oldIndex:i,newIndex:s}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function cy(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Xs()}}function uy(e,t){return e instanceof sy&&t instanceof sy?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 ay&&t instanceof ay&&e._firestore===t._firestore&&Jg(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class ly extends ty{constructor(e){super(),this.firestore=e}convertBytes(e){return new am(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Kg(this.firestore,null,t)}}function hy(e,t,n){e=Ug(e,Kg);const r=Ug(e.firestore,nm),i=ny(e.converter,t,n);return py(r,[_m(ym(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Gu.none())])}function dy(e,t,n,...r){e=Ug(e,Kg);const i=Ug(e.firestore,nm),s=ym(i);let o;return o="string"==typeof(t=j(t))||t instanceof cm?Sm(s,"updateDoc",e._key,t,n,r):Tm(s,"updateDoc",e._key,t),py(i,[o.toMutation(e._key,Gu.exists(!0))])}function fy(e,...t){var n,r,i;e=j(e);let s={includeMetadataChanges:!1},o=0;"object"!=typeof t[o]||em(t[o])||(s=t[o],o++);const a={includeMetadataChanges:s.includeMetadataChanges};if(em(t[o])){const e=t[o];t[o]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[o+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[o+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}let c,u,l;if(e instanceof Kg)u=Ug(e.firestore,nm),l=Jc(e._key.path),c={next:n=>{t[o]&&t[o](gy(u,e,n))},error:t[o+1],complete:t[o+2]};else{const n=Ug(e,Wg);u=Ug(n.firestore,nm),l=n._query;const r=new ly(u);c={next:e=>{t[o]&&t[o](new ay(u,r,n,e))},error:t[o+1],complete:t[o+2]},jm(e._query)}return function(e,t,n,r){const i=new _g(r),s=new kp(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Ep(await Pg(e),s)),()=>{i.Dc(),e.asyncQueue.enqueueAndForget(async()=>Cp(await Pg(e),s))}}(rm(u),l,a,c)}function py(e,t){return function(e,t){const n=new no;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){const r=dg(e);try{const e=await function(e,t){const n=Zs(e),r=yo.now(),i=t.reduce((e,t)=>e.add(t.key),Tu());let s,o;return n.persistence.runTransaction("Locally write mutations","readwrite",e=>{let a=mu(),c=Tu();return n.Zi.getEntries(e,i).next(e=>{a=e,a.forEach((e,t)=>{t.isValidDocument()||(c=c.add(e))})}).next(()=>n.localDocuments.getOverlayedDocuments(e,a)).next(i=>{s=i;const o=[];for(const e of t){const t=Xu(e,s.get(e.key).overlayedDocument);null!=t&&o.push(new el(e.key,t,mc(t.value.mapValue),Gu.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,o,t)}).next(t=>{o=t;const r=t.applyToLocalDocumentSet(s,c);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)})}).then(()=>({batchId:o.batchId,changes:vu(s)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Tc[e.currentUser.toKey()];r||(r=new Da(po)),r=r.insert(t,n),e.Tc[e.currentUser.toKey()]=r}(r,e.batchId,n),await eg(r,e.changes),await rp(r.remoteStore)}catch(e){const t=yp(e,"Failed to persist write");n.reject(t)}}(await Ag(e),t,n)),n.promise}(rm(e),t)}function gy(e,t,n){const r=n.docs.get(t._key),i=new ly(e);return new sy(e,i,t._key,r,new iy(n.hasPendingWrites,n.fromCache),t.converter)}const my={maxAttempts:5};class yy{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ym(e)}set(e,t,n){this._verifyNotCommitted();const r=_y(e,this._firestore),i=ny(r.converter,t,n),s=_m(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Gu.none())),this}update(e,t,n,...r){this._verifyNotCommitted();const i=_y(e,this._firestore);let s;return s="string"==typeof(t=j(t))||t instanceof cm?Sm(this._dataReader,"WriteBatch.update",i._key,t,n,r):Tm(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Gu.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=_y(e,this._firestore);return this._mutations=this._mutations.concat(new il(t._key,Gu.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new to(eo.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function _y(e,t){if((e=j(e)).firestore!==t)throw new to(eo.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class vy extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=ym(e)}get(e){const t=_y(e,this._firestore),n=new ry(this._firestore);return this._transaction.lookup([t._key]).then(e=>{if(!e||1!==e.length)return Xs();const r=e[0];if(r.isFoundDocument())return new Lm(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new Lm(this._firestore,n,t._key,null,t.converter);throw Xs()})}set(e,t,n){const r=_y(e,this._firestore),i=ny(r.converter,t,n),s=_m(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){const i=_y(e,this._firestore);let s;return s="string"==typeof(t=j(t))||t instanceof cm?Sm(this._dataReader,"Transaction.update",i._key,t,n,r):Tm(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=_y(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=_y(e,this._firestore),n=new ly(this._firestore);return super.get(e).then(e=>new sy(this._firestore,n,t._key,e._document,new iy(!1,!1),t.converter))}}function wy(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new to("invalid-argument",`Invalid options passed to function ${e}(): You cannot specify both "merge" and "mergeFields".`);return t}function by(){if("undefined"==typeof Uint8Array)throw new to("unimplemented","Uint8Arrays are not available in this environment.")}function Iy(){if("undefined"==typeof atob)throw new to("unimplemented","Blobs are unavailable in Firestore in this environment.")}!function(e,t=!0){!function(e){$s=e}(et),Qe(new B("firestore",(e,{instanceIdentifier:n,options:r})=>{const i=e.getProvider("app").getImmediate(),s=new nm(new oo(e.getProvider("auth-internal")),new lo(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new to(eo.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Wa(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:t},r),s._setSettings(r),s},"PUBLIC").setMultipleInstances(!0)),st(Us,"3.13.0",e),st(Us,"3.13.0","esm2017")}();class Ey{constructor(e){this._delegate=e}static fromBase64String(e){return Iy(),new Ey(am.fromBase64String(e))}static fromUint8Array(e){return by(),new Ey(am.fromUint8Array(e))}toBase64(){return Iy(),this._delegate.toBase64()}toUint8Array(){return by(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Cy(e){return function(e){if("object"!=typeof e||null===e)return!1;const t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return!0;return!1}(e)}class Ty{enableIndexedDbPersistence(e,t){return function(e,t){om(e=Ug(e,nm));const n=rm(e);if(n._uninitializedComponentsProvider)throw new to(eo.FAILED_PRECONDITION,"SDK cache is already specified.");Hs("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const r=e._freezeSettings(),i=new mg;return sm(n,i,new pg(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){om(e=Ug(e,nm));const t=rm(e);if(t._uninitializedComponentsProvider)throw new to(eo.FAILED_PRECONDITION,"SDK cache is already specified.");Hs("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings(),r=new mg;return sm(t,r,new gg(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new to(eo.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new no;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!qo.D())return Promise.resolve();const t=e+"main";await qo.delete(t)}(Xd(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Sy{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Wa||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){const t=this._delegate._getSettings();e.merge||t.host===e.host||Hs("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(e,t,n,r={}){var i;const s=(e=Ug(e,Gg))._getSettings(),o=`${t}:${n}`;if("firestore.googleapis.com"!==s.host&&s.host!==o&&Hs("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:o,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=zs.MOCK_USER;else{t=g(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new to(eo.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new zs(s)}e._authCredentials=new so(new ro(t,n))}}(this._delegate,e,t,n)}enableNetwork(){return function(e){return e.asyncQueue.enqueue(async()=>{const t=await kg(e),n=await Dg(e);return t.setNetworkEnabled(!0),function(e){const t=Zs(e);return t.vu.delete(0),Uf(t)}(n)})}(rm(Ug(this._delegate,nm)))}disableNetwork(){return function(e){return e.asyncQueue.enqueue(async()=>{const t=await kg(e),n=await Dg(e);return t.setNetworkEnabled(!1),async function(e){const t=Zs(e);t.vu.add(0),await zf(t),t.bu.set("Offline")}(n)})}(rm(Ug(this._delegate,nm)))}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,qg("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 function(e){const t=new no;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=Zs(e);Yf(n.remoteStore)||Ws("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=Zs(e);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Ec.get(e)||[];r.push(t),n.Ec.set(e,r)}catch(e){const n=yp(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await Ag(e),t)),t.promise}(rm(Ug(this._delegate,nm)))}onSnapshotsInSync(e){return t=this._delegate,n=e,function(e,t){const n=new _g(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){Zs(e).ku.add(t),t.next()}(await Pg(e),n)),()=>{n.Dc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){Zs(e).ku.delete(t)}(await Pg(e),n))}}(rm(t=Ug(t,nm)),em(n)?n:{next:n});var t,n}get app(){if(!this._appCompat)throw new to("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new jy(this,Hg(this._delegate,e))}catch(e){throw Py(e,"collection()","Firestore.collection()")}}doc(e){try{return new Ay(this,Yg(this._delegate,e))}catch(e){throw Py(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Ly(this,function(e,t){if(e=Ug(e,Gg),Lg("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new to(eo.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Wg(e,null,function(e){return new Yc(wo.emptyPath(),e)}(t))}(this._delegate,e))}catch(e){throw Py(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(e){return function(e,t){e=Ug(e,nm);const n=Object.assign(Object.assign({},my),void 0);return function(e){if(e.maxAttempts<1)throw new to(eo.INVALID_ARGUMENT,"Max attempts must be at least 1")}(n),function(e,t,n){const r=new no;return e.asyncQueue.enqueueAndForget(async()=>{const i=await function(e){return xg(e).then(e=>e.datastore)}(e);new bg(e.asyncQueue,i,n,t,r).run()}),r.promise}(rm(e),n=>t(new vy(e,n)),n)}(this._delegate,t=>e(new ky(this,t)))}batch(){return rm(this._delegate),new Ny(new yy(this._delegate,e=>py(this._delegate,e)))}loadBundle(e){return function(e,t){const n=rm(e=Ug(e,nm)),r=new tm;return function(e,t,n,r){const i=function(e,t){let n;return n="string"==typeof e?ml().encode(e):e,function(e,t){return new vg(e,t)}(function(e,t){if(e instanceof Uint8Array)return yg(e,t);if(e instanceof ArrayBuffer)return yg(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(n),t)}(n,Of(t));e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=Zs(e);(async function(e,t,n){try{const r=await t.getMetadata();if(await function(e,t){const n=Zs(e),r=Vl(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.qs.getBundleMetadata(e,t.id)).then(e=>!!e&&e.createTime.compareTo(r)>=0)}(e.localStore,r))return await t.close(),n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),Promise.resolve(new Set);n._updateProgress(Pp(r));const i=new Ap(r,e.localStore,t.serializer);let s=await t.bc();for(;s;){const e=await i.zu(s);e&&n._updateProgress(e),s=await t.bc()}const o=await i.complete();return await eg(e,o.Ju,void 0),await function(e,t){const n=Zs(e);return n.persistence.runTransaction("Save bundle","readwrite",e=>n.qs.saveBundleMetadata(e,t))}(e.localStore,r),n._completeWith(o.progress),Promise.resolve(o.Hu)}catch(e){return Hs("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await Ag(e),i,r)})}(n,e._databaseId,t,r),r}(this._delegate,e)}namedQuery(e){return(t=this._delegate,n=e,function(e,t){return e.asyncQueue.enqueue(async()=>function(e,t){const n=Zs(e);return n.persistence.runTransaction("Get named query","readonly",e=>n.qs.getNamedQuery(e,t))}(await Ng(e),t))}(rm(t=Ug(t,nm)),n).then(e=>e?new Wg(t,null,e.query):null)).then(e=>e?new Ly(this,e):null);var t,n}}class xy extends ty{constructor(e){super(),this.firestore=e}convertBytes(e){return new Ey(new am(e))}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return Ay.forKey(t,this.firestore,null)}}class ky{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new xy(e)}get(e){const t=By(e);return this._delegate.get(t).then(e=>new My(this._firestore,new sy(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){const r=By(e);return n?(wy("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){const i=By(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){const t=By(e);return this._delegate.delete(t),this}}class Ny{constructor(e){this._delegate=e}set(e,t,n){const r=By(e);return n?(wy("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){const i=By(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){const t=By(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Dy{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){const n=new oy(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Fy(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=Dy.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Dy(e,new xy(e),t),r.set(t,i)),i}}Dy.INSTANCES=new WeakMap;class Ay{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new xy(e)}static forPath(e,t,n){if(e.length%2!=0)throw new to("invalid-argument",`Invalid document reference. Document references must have an even number of segments, but ${e.canonicalString()} has ${e.length}`);return new Ay(t,new Kg(t._delegate,n,new Eo(e)))}static forKey(e,t,n){return new Ay(t,new Kg(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new jy(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new jy(this.firestore,Hg(this._delegate,e))}catch(e){throw Py(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=j(e))instanceof Kg&&Xg(this._delegate,e)}set(e,t){t=wy("DocumentReference.set",t);try{return t?hy(this._delegate,e,t):hy(this._delegate,e)}catch(e){throw Py(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?dy(this._delegate,e):dy(this._delegate,e,t,...n)}catch(e){throw Py(e,"updateDoc()","DocumentReference.update()")}}delete(){return py(Ug((e=this._delegate).firestore,nm),[new il(e._key,Gu.none())]);var e}onSnapshot(...e){const t=Ry(e),n=Oy(e,e=>new My(this.firestore,new sy(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return fy(this._delegate,t,n)}get(e){let t;return t="cache"===(null==e?void 0:e.source)?function(e){e=Ug(e,Kg);const t=Ug(e.firestore,nm),n=rm(t),r=new ly(t);return function(e,t){const n=new no;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const r=await function(e,t){const n=Zs(e);return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new to(eo.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){const r=yp(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await Ng(e),t,n)),n.promise}(n,e._key).then(n=>new sy(t,r,e._key,n,new iy(null!==n&&n.hasLocalMutations,!0),e.converter))}(this._delegate):"server"===(null==e?void 0:e.source)?function(e){e=Ug(e,Kg);const t=Ug(e.firestore,nm);return Rg(rm(t),e._key,{source:"server"}).then(n=>gy(t,e,n))}(this._delegate):function(e){e=Ug(e,Kg);const t=Ug(e.firestore,nm);return Rg(rm(t),e._key).then(n=>gy(t,e,n))}(this._delegate),t.then(e=>new My(this.firestore,new sy(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Ay(this.firestore,e?this._delegate.withConverter(Dy.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Py(e,t,n){return e.message=e.message.replace(t,n),e}function Ry(e){for(const t of e)if("object"==typeof t&&!Cy(t))return t;return{}}function Oy(e,t){var n,r;let i;return i=Cy(e[0])?e[0]:Cy(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=>{i.next&&i.next(t(e))},error:null===(n=i.error)||void 0===n?void 0:n.bind(i),complete:null===(r=i.complete)||void 0===r?void 0:r.bind(i)}}class My{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Ay(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 uy(this._delegate,e._delegate)}}class Fy extends My{data(e){const t=this._delegate.data(e);return void 0!==t||Xs(),t}}class Ly{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new xy(e)}where(e,t,n){try{return new Ly(this.firestore,zm(this._delegate,function(e,t,n){const r=t,i=Vm("where",e);return $m._create(i,r,n)}(e,t,n)))}catch(e){throw Py(e,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(e,t){try{return new Ly(this.firestore,zm(this._delegate,function(e,t="asc"){const n=t,r=Vm("orderBy",e);return Km._create(r,n)}(e,t)))}catch(e){throw Py(e,/(orderBy|where)\(\)/,"Query.$1()")}}limit(e){try{return new Ly(this.firestore,zm(this._delegate,(zg("limit",t=e),Wm._create("limit",t,"F"))))}catch(e){throw Py(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Ly(this.firestore,zm(this._delegate,(zg("limitToLast",t=e),Wm._create("limitToLast",t,"L"))))}catch(e){throw Py(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Ly(this.firestore,zm(this._delegate,function(...e){return Qm._create("startAt",e,!0)}(...e)))}catch(e){throw Py(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Ly(this.firestore,zm(this._delegate,function(...e){return Qm._create("startAfter",e,!1)}(...e)))}catch(e){throw Py(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Ly(this.firestore,zm(this._delegate,function(...e){return Hm._create("endBefore",e,!1)}(...e)))}catch(e){throw Py(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Ly(this.firestore,zm(this._delegate,function(...e){return Hm._create("endAt",e,!0)}(...e)))}catch(e){throw Py(e,"endAt()","Query.endAt()")}}isEqual(e){return Jg(this._delegate,e._delegate)}get(e){let t;return t="cache"===(null==e?void 0:e.source)?function(e){e=Ug(e,Wg);const t=Ug(e.firestore,nm),n=rm(t),r=new ly(t);return function(e,t){const n=new no;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const r=await uf(e,t,!0),i=new Mp(t,r.ir),s=i.sc(r.documents),o=i.applyChanges(s,!1);n.resolve(o.snapshot)}catch(e){const r=yp(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await Ng(e),t,n)),n.promise}(n,e._query).then(n=>new ay(t,r,e,n))}(this._delegate):"server"===(null==e?void 0:e.source)?function(e){e=Ug(e,Wg);const t=Ug(e.firestore,nm),n=rm(t),r=new ly(t);return Og(n,e._query,{source:"server"}).then(n=>new ay(t,r,e,n))}(this._delegate):function(e){e=Ug(e,Wg);const t=Ug(e.firestore,nm),n=rm(t),r=new ly(t);return jm(e._query),Og(n,e._query).then(n=>new ay(t,r,e,n))}(this._delegate),t.then(e=>new Vy(this.firestore,new ay(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){const t=Ry(e),n=Oy(e,e=>new Vy(this.firestore,new ay(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return fy(this._delegate,t,n)}withConverter(e){return new Ly(this.firestore,e?this._delegate.withConverter(Dy.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class qy{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Fy(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Vy{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Ly(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 Fy(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new qy(this._firestore,e))}forEach(e,t){this._delegate.forEach(n=>{e.call(t,new Fy(this._firestore,n))})}isEqual(e){return uy(this._delegate,e._delegate)}}class jy extends Ly{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(){const e=this._delegate.parent;return e?new Ay(this.firestore,e):null}doc(e){try{return new Ay(this.firestore,void 0===e?Yg(this._delegate):Yg(this._delegate,e))}catch(e){throw Py(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Ug(e.firestore,nm),r=Yg(e),i=ny(e.converter,t);return py(n,[_m(ym(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Gu.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Ay(this.firestore,e))}isEqual(e){return Xg(this._delegate,e._delegate)}withConverter(e){return new jy(this.firestore,e?this._delegate.withConverter(Dy.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function By(e){return Ug(e,Kg)}class Uy{constructor(...e){this._delegate=new cm(...e)}static documentId(){return new Uy(Io.keyField().canonicalString())}isEqual(e){return(e=j(e))instanceof cm&&this._delegate._internalPath.isEqual(e._internalPath)}}class zy{constructor(e){this._delegate=e}static serverTimestamp(){const e=new bm("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new zy(e)}static delete(){const e=new vm("deleteField");return e._methodName="FieldValue.delete",new zy(e)}static arrayUnion(...e){const t=function(...e){return new Im("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new zy(t)}static arrayRemove(...e){const t=function(...e){return new Em("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new zy(t)}static increment(e){const t=new Cm("increment",e);return t._methodName="FieldValue.increment",new zy(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}}const $y={Firestore:Sy,GeoPoint:lm,Timestamp:yo,Blob:Ey,Transaction:ky,WriteBatch:Ny,DocumentReference:Ay,DocumentSnapshot:My,Query:Ly,QueryDocumentSnapshot:Fy,QuerySnapshot:Vy,CollectionReference:jy,FieldPath:Uy,FieldValue:zy,setLogLevel:function(e){var t;t=e,Gs.setLogLevel(t)},CACHE_SIZE_UNLIMITED:-1};var Gy;(function(e){e.INTERNAL.registerComponent(new B("firestore-compat",e=>((e,t)=>new Sy(e,t,new Ty))(e.getProvider("app-compat").getImmediate(),e.getProvider("firestore").getImmediate()),"PUBLIC").setServiceProps(Object.assign({},$y)))})(Gy=bt),Gy.registerVersion("@firebase/firestore-compat","0.3.12");const Ky="@firebase/database",Wy="0.14.4";let Qy="";function Hy(e){Qy=e}class Yy{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),E(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:I(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Xy{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return T(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const Jy=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 Yy(t)}}catch(e){}return new Xy},Zy=Jy("localStorage"),e_=Jy("sessionStorage"),t_=new X("@firebase/database"),n_=function(){let e=1;return function(){return e++}}(),r_=function(e){const n=function(e){const n=[];let r=0;for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);if(s>=55296&&s<=56319){const n=s-55296;i++,t(i<e.length,"Surrogate pair missing trail surrogate."),s=65536+(n<<10)+(e.charCodeAt(i)-56320)}s<128?n[r++]=s:s<2048?(n[r++]=s>>6|192,n[r++]=63&s|128):s<65536?(n[r++]=s>>12|224,n[r++]=s>>6&63|128,n[r++]=63&s|128):(n[r++]=s>>18|240,n[r++]=s>>12&63|128,n[r++]=s>>6&63|128,n[r++]=63&s|128)}return n}(e),r=new A;r.update(n);const i=r.digest();return s.encodeByteArray(i)},i_=function(...e){let t="";for(let n=0;n<e.length;n++){const r=e[n];Array.isArray(r)||r&&"object"==typeof r&&"number"==typeof r.length?t+=i_.apply(null,r):t+="object"==typeof r?E(r):r,t+=" "}return t};let s_=null,o_=!0;const a_=function(e,n){t(!n||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(t_.logLevel=K.VERBOSE,s_=t_.log.bind(t_),n&&e_.set("logging_enabled",!0)):"function"==typeof e?s_=e:(s_=null,e_.remove("logging_enabled"))},c_=function(...e){if(!0===o_&&(o_=!1,null===s_&&!0===e_.get("logging_enabled")&&a_(!0)),s_){const t=i_.apply(null,e);s_(t)}},u_=function(e){return function(...t){c_(e,...t)}},l_=function(...e){const t="FIREBASE INTERNAL ERROR: "+i_(...e);t_.error(t)},h_=function(...e){const t=`FIREBASE FATAL ERROR: ${i_(...e)}`;throw t_.error(t),new Error(t)},d_=function(...e){const t="FIREBASE WARNING: "+i_(...e);t_.warn(t)},f_=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},p_="[MIN_NAME]",g_="[MAX_NAME]",m_=function(e,t){if(e===t)return 0;if(e===p_||t===g_)return-1;if(t===p_||e===g_)return 1;{const n=C_(e),r=C_(t);return null!==n?null!==r?n-r===0?e.length-t.length:n-r:-1:null!==r?1:e<t?-1:1}},y_=function(e,t){return e===t?0:e<t?-1:1},__=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+E(t))},v_=function(e){if("object"!=typeof e||null===e)return E(e);const t=[];for(const n in e)t.push(n);t.sort();let n="{";for(let r=0;r<t.length;r++)0!==r&&(n+=","),n+=E(t[r]),n+=":",n+=v_(e[t[r]]);return n+="}",n},w_=function(e,t){const 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};function b_(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const I_=function(e){t(!f_(e),"Invalid JSON number");let n,r,i,s,o;0===e?(r=0,i=0,n=1/e==-1/0?1:0):(n=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(s=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),r=s+1023,i=Math.round(e*Math.pow(2,52-s)-Math.pow(2,52))):(r=0,i=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(i%2?1:0),i=Math.floor(i/2);for(o=11;o;o-=1)a.push(r%2?1:0),r=Math.floor(r/2);a.push(n?1:0),a.reverse();const c=a.join("");let u="";for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),u+=e}return u.toLowerCase()},E_=new RegExp("^-?(0*)\\d{1,10}$"),C_=function(e){if(E_.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},T_=function(e){try{e()}catch(e){setTimeout(()=>{const t=e.stack||"";throw d_("Exception was thrown by user callback.",t),e},Math.floor(0))}},S_=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class x_{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(e){return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){d_(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class k_{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(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&"auth/token-not-initialized"===e.code?(c_("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}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/.',d_(e)}}class N_{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}N_.OWNER="owner";const D_="5",A_=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,P_="ac",R_="websocket",O_="long_polling";class M_{constructor(e,t,n,r,i=!1,s="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Zy.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()&&Zy.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function F_(e,n,r){let i;if(t("string"==typeof n,"typeof type must == string"),t("object"==typeof r,"typeof params must == object"),n===R_)i=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(n!==O_)throw new Error("Unknown connection type: "+n);i=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(r.ns=e.namespace);const s=[];return b_(r,(e,t)=>{s.push(e+"="+t)}),i+s.join("&")}class L_{constructor(){this.counters_={}}incrementCounter(e,t=1){T(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return l(void 0,this.counters_)}}const q_={},V_={};function j_(e){const t=e.toString();return q_[t]||(q_[t]=new L_),q_[t]}class B_{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 e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&T_(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const U_="start";class z_{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_=u_(e),this.stats_=j_(t),this.urlFn=e=>(this.appCheckToken&&(e[P_]=this.appCheckToken),F_(t,O_,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new B_(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):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_)return;this.scriptTagHolder=new $_((...e)=>{const[t,n,r,i,s]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===U_)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)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const e={};e[U_]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v=D_,this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[P_]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&A_.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){z_.forceAllow_=!0}static forceDisallow(){z_.forceDisallow_=!0}static isAvailable(){return!(!z_.forceAllow_&&(z_.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){const t=E(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=a(t),r=w_(n,1840);for(let e=0;e<r.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[e]),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){const t=E(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class $_{constructor(e,t,n,r){this.onDisconnect=n,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=n_(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=$_.createIFrame_();let n="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)&&(n='<script>document.domain="'+document.domain+'";<\/script>');const r="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(r),this.myIFrame.doc.close()}catch(e){c_("frame writing exception"),e.stack&&c_(e.stack),c_(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||c_("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",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<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",r=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+n.length<=1870;){const e=this.pendingSegs.shift();n=n+"&seg"+r+"="+e.seg+"&ts"+r+"="+e.ts+"&d"+r+"="+e.d,r++}return t+=n,this.addLongPollTag_(t,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,t){setTimeout(()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{c_("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}},Math.floor(1))}}let G_=null;"undefined"!=typeof MozWebSocket?G_=MozWebSocket:"undefined"!=typeof WebSocket&&(G_=WebSocket);class K_{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_=u_(this.connId),this.stats_=j_(t),this.connURL=K_.connectionURL_(t,s,o,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={};return s.v=D_,"undefined"!=typeof location&&location.hostname&&A_.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s[P_]=r),i&&(s.p=i),F_(e,R_,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Zy.set("previous_websocket_failure",!0);try{let e;0,this.mySock=new G_(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),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.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){K_.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==G_&&!K_.forceDisallow_}static previouslyFailed(){return Zy.isInMemoryStorage||!0===Zy.get("previous_websocket_failure")}markConnectionHealthy(){Zy.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=I(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(t(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=E(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=w_(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}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)}}}K_.responsesRequiredToBeHealthy=2,K_.healthyTimeout=3e4;class W_{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[z_,K_]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=K_&&K_.isAvailable();let n=t&&!K_.previouslyFailed();if(e.webSocketOnly&&(t||d_("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[K_];else{const e=this.transports_=[];for(const t of W_.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);W_.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}W_.globalTransportInitialized_=!1;class Q_{constructor(e,t,n,r,i,s,o,a,c,u){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=u,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=u_("c:"+this.id+":"),this.transportManager_=new W_(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));const r=e.healthyTimeout||0;r>0&&(this.healthyTimeout_=S_(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?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_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}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){if("t"in e){const t=e.t;"a"===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){const t=__("t",e),n=__("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){const t=__("t",e),n=__("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){const t=__("t",e);if("d"in e){const n=e.d;if("h"===t){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}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?l_("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):l_("Unknown control packet command: "+t)}}onHandshake_(e){const 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),D_!==n&&d_("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const 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;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),S_(()=>{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):S_(()=>{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_(){const 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()&&(Zy.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 H_{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 Y_{constructor(e){this.allowedEvents_=e,this.listeners_={},t(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let e=0;e<r.length;e++)if(r[e].callback===t&&(!n||n===r[e].context))return void r.splice(e,1)}validateEventType_(e){t(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class X_ extends Y_{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||y()||(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 X_}getInitialEvent(e){return t("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class J_{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function Z_(){return new J_("")}function ev(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function tv(e){return e.pieces_.length-e.pieceNum_}function nv(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new J_(e.pieces_,t)}function rv(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function iv(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function sv(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 J_(t,0)}function ov(e,t){const n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof J_)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new J_(n,0)}function av(e){return e.pieceNum_>=e.pieces_.length}function cv(e,t){const n=ev(e),r=ev(t);if(null===n)return t;if(n===r)return cv(nv(e),nv(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function uv(e,t){const n=iv(e,0),r=iv(t,0);for(let e=0;e<n.length&&e<r.length;e++){const t=m_(n[e],r[e]);if(0!==t)return t}return n.length===r.length?0:n.length<r.length?-1:1}function lv(e,t){if(tv(e)!==tv(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 hv(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(tv(e)>tv(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class dv{constructor(e,t){this.errorPrefix_=t,this.parts_=iv(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=V(this.parts_[e]);fv(this)}}function fv(e){if(e.byteLength_>768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+pv(e))}function pv(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class gv extends Y_{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new gv}getInitialEvent(e){return t("visible"===e,"Unknown event type: "+e),[this.visible_]}}const mv=1e3;class yv extends H_{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=yv.nextPersistentConnectionId_++,this.log_=u_("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_=mv,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)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");gv.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&X_.getInstance().on("online",this.onOnline_,this)}sendRequest(e,n,r){const i=++this.requestNumber_,s={r:i,a:e,b:n};this.log_(E(s)),t(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),r&&(this.requestCBHash_[i]=r)}get(e){this.initConnection_();const t=new p,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,n,r,i){this.initConnection_();const s=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+s),this.listens.has(o)||this.listens.set(o,new Map),t(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),t(!this.listens.get(o).has(s),"listen() called twice for same path/queryId.");const a={onComplete:i,hashFn:n,query:e,tag:r};this.listens.get(o).set(s,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(e){const t=e.query,n=t._path.toString(),r=t._queryIdentifier;this.log_("Listen on "+n+" for "+r);const i={p:n};e.tag&&(i.q=t._queryObject,i.t=e.tag),i.h=e.hashFn(),this.sendRequest("q",i,i=>{const s=i.d,o=i.s;yv.warnOnListenWarnings_(s,t),(this.listens.get(n)&&this.listens.get(n).get(r))===e&&(this.log_("listen response",i),"ok"!==o&&this.removeListen_(n,r),e.onComplete&&e.onComplete(o,s))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&T(e,"w")){const n=S(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();d_(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} 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){(e&&40===e.length||function(e){const t=C(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(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 e=this.authToken_,t=function(e){const t=C(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{const n=t.s,r=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,r))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,n){const r=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+r+" "+i),t(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(r,i)&&this.connected_&&this.sendUnlisten_(r,i,e._queryObject,n)}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){const 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_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,r=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(n.s,n.d)})}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+E(e));const t=e.r,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):l_("Unrecognized action received from server: "+E(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){t(!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_=mv,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=mv,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&((new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=mv),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime());const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),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;const e=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+yv.nextConnectionId_++,s=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,r())},u=function(e){t(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:c,sendRequest:u};const l=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[t,c]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);o?c_("getToken() completed but was canceled"):(c_("getToken() completed. Creating connection."),this.authToken_=t&&t.accessToken,this.appCheckToken_=c&&c.token,a=new Q_(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,n,r,e=>{d_(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&d_(e),c())}}}interrupt(e){c_("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){c_("Resuming connection for reason: "+e),delete this.interruptReasons_[e],x(this.interruptReasons_)&&(this.reconnectDelay_=mv,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const 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=>v_(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){const n=new J_(e).toString();let r;if(this.listens.has(n)){const e=this.listens.get(n);r=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){c_("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){c_("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&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 e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let t="js";e["sdk."+t+"."+Qy.replace(/\./g,"-")]=1,y()?e["framework.cordova"]=1:"object"==typeof navigator&&"ReactNative"===navigator.product&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=X_.getInstance().currentlyOnline();return x(this.interruptReasons_)&&e}}yv.nextPersistentConnectionId_=0,yv.nextConnectionId_=0;class _v{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new _v(e,t)}}class vv{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new _v(p_,e),r=new _v(p_,t);return 0!==this.compare(n,r)}minPost(){return _v.MIN}}let wv;class bv extends vv{static get __EMPTY_NODE(){return wv}static set __EMPTY_NODE(e){wv=e}compare(e,t){return m_(e.name,t.name)}isDefinedOn(e){throw r("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return _v.MIN}maxPost(){return new _v(g_,wv)}makePost(e,n){return t("string"==typeof e,"KeyIndex indexValue must always be a string."),new _v(e,wv)}toString(){return".key"}}const Iv=new bv;class Ev{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,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Cv{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Cv.RED,this.left=null!=r?r:Tv.EMPTY_NODE,this.right=null!=i?i:Tv.EMPTY_NODE}copy(e,t,n,r,i){return new Cv(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;const 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 Tv.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 Tv.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_(){const e=this.copy(null,null,Cv.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,Cv.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const 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_(){const 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");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Cv.RED=!0,Cv.BLACK=!1;class Tv{constructor(e,t=Tv.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Tv(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Cv.BLACK,null,null))}remove(e){return new Tv(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Cv.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){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:t>0&&(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 Ev(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Ev(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Ev(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Ev(this.root_,null,this.comparator_,!0,e)}}function Sv(e,t){return m_(e.name,t.name)}function xv(e,t){return m_(e,t)}let kv;Tv.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new Cv(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}};const Nv=function(e){return"number"==typeof e?"number:"+I_(e):"string:"+e},Dv=function(e){if(e.isLeafNode()){const n=e.val();t("string"==typeof n||"number"==typeof n||"object"==typeof n&&T(n,".sv"),"Priority must be a string or number.")}else t(e===kv||e.isEmpty(),"priority of unexpected type.");t(e===kv||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Av,Pv,Rv;class Ov{constructor(e,n=Ov.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=n,this.lazyHash_=null,t(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Dv(this.priorityNode_)}static set __childrenNodeConstructor(e){Av=e}static get __childrenNodeConstructor(){return Av}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Ov(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Ov.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return av(e)?this:".priority"===ev(e)?this.priorityNode_:Ov.__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:Ov.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,n){const r=ev(e);return null===r?n:n.isEmpty()&&".priority"!==r?this:(t(".priority"!==r||1===tv(e),".priority must be the last token in a path"),this.updateImmediateChild(r,Ov.__childrenNodeConstructor.EMPTY_NODE.updateChild(nv(e),n)))}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:"+Nv(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?I_(this.value_):this.value_,this.lazyHash_=r_(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Ov.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Ov.__childrenNodeConstructor?-1:(t(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const n=typeof e.value_,r=typeof this.value_,i=Ov.VALUE_TYPE_ORDER.indexOf(n),s=Ov.VALUE_TYPE_ORDER.indexOf(r);return t(i>=0,"Unknown leaf type: "+n),t(s>=0,"Unknown leaf type: "+r),i===s?"object"===r?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:s-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}Ov.VALUE_TYPE_ORDER=["object","boolean","number","string"];const Mv=new class extends vv{compare(e,t){const n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?m_(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return _v.MIN}maxPost(){return new _v(g_,new Ov("[PRIORITY-POST]",Rv))}makePost(e,t){const n=Pv(e);return new _v(t,new Ov("[PRIORITY-POST]",n))}toString(){return".priority"}},Fv=Math.log(2);class Lv{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Fv,10)),this.current_=this.count-1;const n=(r=this.count,parseInt(Array(r+1).join("1"),2));var r;this.bits_=e+1&n}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const qv=function(e,t,n,r){e.sort(t);const i=function(t,r){const s=r-t;let o,a;if(0===s)return null;if(1===s)return o=e[t],a=n?n(o):o,new Cv(a,o.node,Cv.BLACK,null,null);{const c=parseInt(s/2,10)+t,u=i(t,c),l=i(c+1,r);return o=e[c],a=n?n(o):o,new Cv(a,o.node,Cv.BLACK,u,l)}},s=function(t){let r=null,s=null,o=e.length;const a=function(t,r){const s=o-t,a=o;o-=t;const u=i(s+1,a),l=e[s],h=n?n(l):l;c(new Cv(h,l.node,r,null,u))},c=function(e){r?(r.left=e,r=e):(s=e,r=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),r=Math.pow(2,t.count-(e+1));n?a(r,Cv.BLACK):(a(r,Cv.BLACK),a(r,Cv.RED))}return s}(new Lv(e.length));return new Tv(r||t,s)};let Vv;const jv={};class Bv{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return t(jv&&Mv,"ChildrenNode.ts has not been loaded"),Vv=Vv||new Bv({".priority":jv},{".priority":Mv}),Vv}get(e){const t=S(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Tv?t:null}hasIndex(e){return T(this.indexSet_,e.toString())}addIndex(e,n){t(e!==Iv,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const r=[];let i=!1;const s=n.getIterator(_v.Wrap);let o,a=s.getNext();for(;a;)i=i||e.isDefinedOn(a.node),r.push(a),a=s.getNext();o=i?qv(r,e.getCompare()):jv;const c=e.toString(),u=Object.assign({},this.indexSet_);u[c]=e;const l=Object.assign({},this.indexes_);return l[c]=o,new Bv(l,u)}addToIndexes(e,n){const r=k(this.indexes_,(r,i)=>{const s=S(this.indexSet_,i);if(t(s,"Missing index implementation for "+i),r===jv){if(s.isDefinedOn(e.node)){const t=[],r=n.getIterator(_v.Wrap);let i=r.getNext();for(;i;)i.name!==e.name&&t.push(i),i=r.getNext();return t.push(e),qv(t,s.getCompare())}return jv}{const t=n.get(e.name);let i=r;return t&&(i=i.remove(new _v(e.name,t))),i.insert(e,e.node)}});return new Bv(r,this.indexSet_)}removeFromIndexes(e,t){const n=k(this.indexes_,n=>{if(n===jv)return n;{const r=t.get(e.name);return r?n.remove(new _v(e.name,r)):n}});return new Bv(n,this.indexSet_)}}let Uv;class zv{constructor(e,n,r){this.children_=e,this.priorityNode_=n,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&Dv(this.priorityNode_),this.children_.isEmpty()&&t(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Uv||(Uv=new zv(new Tv(xv),null,Bv.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Uv}updatePriority(e){return this.children_.isEmpty()?this:new zv(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?Uv:t}}getChild(e){const t=ev(e);return null===t?this:this.getImmediateChild(t).getChild(nv(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,n){if(t(n,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(n);{const t=new _v(e,n);let r,i;n.isEmpty()?(r=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(t,this.children_)):(r=this.children_.insert(e,n),i=this.indexMap_.addToIndexes(t,this.children_));const s=r.isEmpty()?Uv:this.priorityNode_;return new zv(r,s,i)}}updateChild(e,n){const r=ev(e);if(null===r)return n;{t(".priority"!==ev(e)||1===tv(e),".priority must be the last token in a path");const i=this.getImmediateChild(r).updateChild(nv(e),n);return this.updateImmediateChild(r,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,r=0,i=!0;if(this.forEachChild(Mv,(s,o)=>{t[s]=o.val(e),n++,i&&zv.INTEGER_REGEXP_.test(s)?r=Math.max(r,Number(s)):i=!1}),!e&&i&&r<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Nv(this.getPriority().val())+":"),this.forEachChild(Mv,(t,n)=>{const r=n.hash();""!==r&&(e+=":"+t+":"+r)}),this.lazyHash_=""===e?"":r_(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){const n=r.getPredecessorKey(new _v(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new _v(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new _v(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(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{const n=this.children_.getIteratorFrom(e.name,_v.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)<0;)n.getNext(),r=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{const n=this.children_.getReverseIteratorFrom(e.name,_v.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)>0;)n.getNext(),r=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===$v?-1:0}withIndex(e){if(e===Iv||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new zv(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Iv||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(Mv),n=t.getIterator(Mv);let r=e.getNext(),i=n.getNext();for(;r&&i;){if(r.name!==i.name||!r.node.equals(i.node))return!1;r=e.getNext(),i=n.getNext()}return null===r&&null===i}return!1}return!1}}resolveIndex_(e){return e===Iv?null:this.indexMap_.get(e.toString())}}zv.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const $v=new class extends zv{constructor(){super(new Tv(xv),zv.EMPTY_NODE,Bv.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return zv.EMPTY_NODE}isEmpty(){return!1}};function Gv(e,n=null){if(null===e)return zv.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(n=e[".priority"]),t(null===n||"string"==typeof n||"number"==typeof n||"object"==typeof n&&".sv"in n,"Invalid priority type found: "+typeof n),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new Ov(e,Gv(n));if(e instanceof Array){let t=zv.EMPTY_NODE;return b_(e,(n,r)=>{if(T(e,n)&&"."!==n.substring(0,1)){const e=Gv(r);!e.isLeafNode()&&e.isEmpty()||(t=t.updateImmediateChild(n,e))}}),t.updatePriority(Gv(n))}{const t=[];let r=!1;if(b_(e,(e,n)=>{if("."!==e.substring(0,1)){const i=Gv(n);i.isEmpty()||(r=r||!i.getPriority().isEmpty(),t.push(new _v(e,i)))}}),0===t.length)return zv.EMPTY_NODE;const i=qv(t,Sv,e=>e.name,xv);if(r){const e=qv(t,Mv.getCompare());return new zv(i,Gv(n),new Bv({".priority":e},{".priority":Mv}))}return new zv(i,Gv(n),Bv.Default)}}Object.defineProperties(_v,{MIN:{value:new _v(p_,zv.EMPTY_NODE)},MAX:{value:new _v(g_,$v)}}),bv.__EMPTY_NODE=zv.EMPTY_NODE,Ov.__childrenNodeConstructor=zv,kv=$v,Rv=$v,function(e){Pv=e}(Gv);class Kv extends vv{constructor(e){super(),this.indexPath_=e,t(!av(e)&&".priority"!==ev(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),r=this.extractChild(t.node),i=n.compareTo(r);return 0===i?m_(e.name,t.name):i}makePost(e,t){const n=Gv(e),r=zv.EMPTY_NODE.updateChild(this.indexPath_,n);return new _v(t,r)}maxPost(){const e=zv.EMPTY_NODE.updateChild(this.indexPath_,$v);return new _v(g_,e)}toString(){return iv(this.indexPath_,0).join("/")}}const Wv=new class extends vv{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?m_(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return _v.MIN}maxPost(){return _v.MAX}makePost(e,t){const n=Gv(e);return new _v(t,n)}toString(){return".value"}};function Qv(e){return{type:"value",snapshotNode:e}}function Hv(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function Yv(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function Xv(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class Jv{constructor(e){this.index_=e}updateChild(e,n,r,i,s,o){t(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(n);return a.getChild(i).equals(r.getChild(i))&&a.isEmpty()===r.isEmpty()?e:(null!=o&&(r.isEmpty()?e.hasChild(n)?o.trackChildChange(Yv(n,a)):t(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Hv(n,r)):o.trackChildChange(Xv(n,r,a))),e.isLeafNode()&&r.isEmpty()?e:e.updateImmediateChild(n,r).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(Mv,(e,r)=>{t.hasChild(e)||n.trackChildChange(Yv(e,r))}),t.isLeafNode()||t.forEachChild(Mv,(t,r)=>{if(e.hasChild(t)){const i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(Xv(t,r,i))}else n.trackChildChange(Hv(t,r))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?zv.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Zv{constructor(e){this.indexedFilter_=new Jv(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Zv.getStartPost_(e),this.endPost_=Zv.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new _v(t,n))||(n=zv.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=zv.EMPTY_NODE);let r=t.withIndex(this.index_);r=r.updatePriority(zv.EMPTY_NODE);const i=this;return t.forEachChild(Mv,(e,t)=>{i.matches(new _v(e,t))||(r=r.updateImmediateChild(e,zv.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()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class ew{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new Zv(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new _v(t,n))||(n=zv.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,t,n){let r;if(t.isLeafNode()||t.isEmpty())r=zv.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;r=zv.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;r=r.updateImmediateChild(t.name,t.node),n++}}}else{let e;r=t.withIndex(this.index_),r=r.updatePriority(zv.EMPTY_NODE),e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:r=r.updateImmediateChild(t.name,zv.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,n,r,i,s){let o;if(this.reverse_){const e=this.index_.getCompare();o=(t,n)=>e(n,t)}else o=this.index_.getCompare();const a=e;t(a.numChildren()===this.limit_,"");const c=new _v(n,r),u=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),l=this.rangedFilter_.matches(c);if(a.hasChild(n)){const e=a.getImmediateChild(n);let t=i.getChildAfterChild(this.index_,u,this.reverse_);for(;null!=t&&(t.name===n||a.hasChild(t.name));)t=i.getChildAfterChild(this.index_,t,this.reverse_);const h=null==t?1:o(t,c);if(l&&!r.isEmpty()&&h>=0)return null!=s&&s.trackChildChange(Xv(n,r,e)),a.updateImmediateChild(n,r);{null!=s&&s.trackChildChange(Yv(n,e));const r=a.updateImmediateChild(n,zv.EMPTY_NODE);return null!=t&&this.rangedFilter_.matches(t)?(null!=s&&s.trackChildChange(Hv(t.name,t.node)),r.updateImmediateChild(t.name,t.node)):r}}return r.isEmpty()?e:l&&o(u,c)>=0?(null!=s&&(s.trackChildChange(Yv(u.name,u.node)),s.trackChildChange(Hv(n,r))),a.updateImmediateChild(n,r).updateImmediateChild(u.name,zv.EMPTY_NODE)):e}}class tw{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_=Mv}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return t(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return t(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:p_}hasEnd(){return this.endSet_}getIndexEndValue(){return t(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return t(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:g_}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return t(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_===Mv}copy(){const e=new tw;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function nw(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 rw(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 iw(e,t){const n=e.copy();return n.index_=t,n}function sw(e){const n={};if(e.isDefault())return n;let r;if(e.index_===Mv?r="$priority":e.index_===Wv?r="$value":e.index_===Iv?r="$key":(t(e.index_ instanceof Kv,"Unrecognized index type!"),r=e.index_.toString()),n.orderBy=E(r),e.startSet_){const t=e.startAfterSet_?"startAfter":"startAt";n[t]=E(e.indexStartValue_),e.startNameSet_&&(n[t]+=","+E(e.indexStartName_))}if(e.endSet_){const t=e.endBeforeSet_?"endBefore":"endAt";n[t]=E(e.indexEndValue_),e.endNameSet_&&(n[t]+=","+E(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?n.limitToFirst=e.limit_:n.limitToLast=e.limit_),n}function ow(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==Mv&&(t.i=e.index_.toString()),t}class aw extends H_{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=u_("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return void 0!==n?"tag$"+n:(t(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,r){const i=e._path.toString();this.log_("Listen called for "+i+" "+e._queryIdentifier);const s=aw.getListenId_(e,n),o={};this.listens_[s]=o;const a=sw(e._queryParams);this.restRequest_(i+".json",a,(e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(i,a,!1,n),S(this.listens_,s)===o){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",r(t,null)}})}unlisten(e,t){const n=aw.getListenId_(e,t);delete this.listens_[n]}get(e){const t=sw(e._queryParams),n=e._path.toString(),r=new p;return this.restRequest_(n+".json",t,(e,t)=>{let i=t;404===e&&(i=null,e=null),null===e?(this.onDataUpdate_(n,i,!1,null),r.resolve(i)):r.reject(new Error(i))}),r.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([r,i])=>{r&&r.accessToken&&(t.auth=r.accessToken),i&&i.token&&(t.ac=i.token);const s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+function(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("&"):""}(t);this.log_("Sending REST request for "+s);const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+s+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=I(o.responseText)}catch(e){d_("Failed to parse JSON response for "+s+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&d_("Got unsuccessful REST response for "+s+" Status: "+o.status),n(o.status);n=null}},o.open("GET",s,!0),o.send()})}}class cw{constructor(){this.rootNode_=zv.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function uw(){return{value:null,children:new Map}}function lw(e,t,n){if(av(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const r=ev(t);e.children.has(r)||e.children.set(r,uw()),lw(e.children.get(r),t=nv(t),n)}}function hw(e,t){if(av(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(Mv,(t,n)=>{lw(e,new J_(t),n)}),hw(e,t)}}if(e.children.size>0){const n=ev(t);return t=nv(t),e.children.has(n)&&hw(e.children.get(n),t)&&e.children.delete(n),0===e.children.size}return!0}function dw(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach((e,n)=>{t(n,e)})}(e,(e,r)=>{dw(r,new J_(t.toString()+"/"+e),n)})}class fw{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&b_(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}class pw{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new fw(e);const n=1e4+2e4*Math.random();S_(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;b_(e,(e,r)=>{r>0&&T(this.statsToReport_,e)&&(t[e]=r,n=!0)}),n&&this.server_.reportStats(t),S_(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var gw;function mw(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(gw||(gw={}));class yw{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=gw.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(av(this.path)){if(null!=this.affectedTree.value)return t(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new J_(e));return new yw(Z_(),t,this.revert)}}return t(ev(this.path)===e,"operationForChild called for unrelated child."),new yw(nv(this.path),this.affectedTree,this.revert)}}class _w{constructor(e,t){this.source=e,this.path=t,this.type=gw.LISTEN_COMPLETE}operationForChild(e){return av(this.path)?new _w(this.source,Z_()):new _w(this.source,nv(this.path))}}class vw{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=gw.OVERWRITE}operationForChild(e){return av(this.path)?new vw(this.source,Z_(),this.snap.getImmediateChild(e)):new vw(this.source,nv(this.path),this.snap)}}class ww{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=gw.MERGE}operationForChild(e){if(av(this.path)){const t=this.children.subtree(new J_(e));return t.isEmpty()?null:t.value?new vw(this.source,Z_(),t.value):new ww(this.source,Z_(),t)}return t(ev(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new ww(this.source,nv(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class bw{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(av(e))return this.isFullyInitialized()&&!this.filtered_;const t=ev(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Iw{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Ew(e,t,n,i,s,o){const a=i.filter(e=>e.type===n);a.sort((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw r("Should only compare child_ events.");const i=new _v(t.childName,t.snapshotNode),s=new _v(n.childName,n.snapshotNode);return e.index_.compare(i,s)}(e,t,n)),a.forEach(n=>{const r=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);s.forEach(i=>{i.respondsTo(n.type)&&t.push(i.createEvent(r,e.query_))})})}function Cw(e,t){return{eventCache:e,serverCache:t}}function Tw(e,t,n,r){return Cw(new bw(t,n,r),e.serverCache)}function Sw(e,t,n,r){return Cw(e.eventCache,new bw(t,n,r))}function xw(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function kw(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Nw;class Dw{constructor(e,t=(()=>(Nw||(Nw=new Tv(y_)),Nw))()){this.value=e,this.children=t}static fromObject(e){let t=new Dw(null);return b_(e,(e,n)=>{t=t.set(new J_(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:Z_(),value:this.value};if(av(e))return null;{const n=ev(e),r=this.children.get(n);if(null!==r){const i=r.findRootMostMatchingPathAndValue(nv(e),t);return null!=i?{path:ov(new J_(n),i.path),value:i.value}:null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(av(e))return this;{const t=ev(e),n=this.children.get(t);return null!==n?n.subtree(nv(e)):new Dw(null)}}set(e,t){if(av(e))return new Dw(t,this.children);{const n=ev(e),r=(this.children.get(n)||new Dw(null)).set(nv(e),t),i=this.children.insert(n,r);return new Dw(this.value,i)}}remove(e){if(av(e))return this.children.isEmpty()?new Dw(null):new Dw(null,this.children);{const t=ev(e),n=this.children.get(t);if(n){const r=n.remove(nv(e));let i;return i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty()?new Dw(null):new Dw(this.value,i)}return this}}get(e){if(av(e))return this.value;{const t=ev(e),n=this.children.get(t);return n?n.get(nv(e)):null}}setTree(e,t){if(av(e))return t;{const n=ev(e),r=(this.children.get(n)||new Dw(null)).setTree(nv(e),t);let i;return i=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),new Dw(this.value,i)}}fold(e){return this.fold_(Z_(),e)}fold_(e,t){const n={};return this.children.inorderTraversal((r,i)=>{n[r]=i.fold_(ov(e,r),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,Z_(),t)}findOnPath_(e,t,n){const r=!!this.value&&n(t,this.value);if(r)return r;if(av(e))return null;{const r=ev(e),i=this.children.get(r);return i?i.findOnPath_(nv(e),ov(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,Z_(),t)}foreachOnPath_(e,t,n){if(av(e))return this;{this.value&&n(t,this.value);const r=ev(e),i=this.children.get(r);return i?i.foreachOnPath_(nv(e),ov(t,r),n):new Dw(null)}}foreach(e){this.foreach_(Z_(),e)}foreach_(e,t){this.children.inorderTraversal((n,r)=>{r.foreach_(ov(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}class Aw{constructor(e){this.writeTree_=e}static empty(){return new Aw(new Dw(null))}}function Pw(e,t,n){if(av(t))return new Aw(new Dw(n));{const r=e.writeTree_.findRootMostValueAndPath(t);if(null!=r){const i=r.path;let s=r.value;const o=cv(i,t);return s=s.updateChild(o,n),new Aw(e.writeTree_.set(i,s))}{const r=new Dw(n),i=e.writeTree_.setTree(t,r);return new Aw(i)}}}function Rw(e,t,n){let r=e;return b_(n,(e,n)=>{r=Pw(r,ov(t,e),n)}),r}function Ow(e,t){if(av(t))return Aw.empty();{const n=e.writeTree_.setTree(t,new Dw(null));return new Aw(n)}}function Mw(e,t){return null!=Fw(e,t)}function Fw(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(cv(n.path,t)):null}function Lw(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(Mv,(e,n)=>{t.push(new _v(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new _v(e,n.value))}),t}function qw(e,t){if(av(t))return e;{const n=Fw(e,t);return new Aw(null!=n?new Dw(n):e.writeTree_.subtree(t))}}function Vw(e){return e.writeTree_.isEmpty()}function jw(e,t){return Bw(Z_(),e.writeTree_,t)}function Bw(e,n,r){if(null!=n.value)return r.updateChild(e,n.value);{let i=null;return n.children.inorderTraversal((n,s)=>{".priority"===n?(t(null!==s.value,"Priority writes must always be leaf nodes"),i=s.value):r=Bw(ov(e,n),s,r)}),r.getChild(e).isEmpty()||null===i||(r=r.updateChild(ov(e,".priority"),i)),r}}function Uw(e,t){return Zw(t,e)}function zw(e,t){if(e.snap)return hv(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&hv(ov(e.path,n),t))return!0;return!1}function $w(e){return e.visible}function Gw(e,t,n){let i=Aw.empty();for(let s=0;s<e.length;++s){const o=e[s];if(t(o)){const e=o.path;let t;if(o.snap)hv(n,e)?(t=cv(n,e),i=Pw(i,t,o.snap)):hv(e,n)&&(t=cv(e,n),i=Pw(i,Z_(),o.snap.getChild(t)));else{if(!o.children)throw r("WriteRecord should have .snap or .children");if(hv(n,e))t=cv(n,e),i=Rw(i,t,o.children);else if(hv(e,n))if(t=cv(e,n),av(t))i=Rw(i,Z_(),o.children);else{const e=S(o.children,ev(t));if(e){const n=e.getChild(nv(t));i=Pw(i,Z_(),n)}}}}}return i}function Kw(e,t,n,r,i){if(r||i){const s=qw(e.visibleWrites,t);if(!i&&Vw(s))return n;if(i||null!=n||Mw(s,Z_())){const s=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(hv(e.path,t)||hv(t,e.path))};return jw(Gw(e.allWrites,s,t),n||zv.EMPTY_NODE)}return null}{const r=Fw(e.visibleWrites,t);if(null!=r)return r;{const r=qw(e.visibleWrites,t);return Vw(r)?n:null!=n||Mw(r,Z_())?jw(r,n||zv.EMPTY_NODE):null}}}function Ww(e,t,n,r){return Kw(e.writeTree,e.treePath,t,n,r)}function Qw(e,t){return function(e,t,n){let r=zv.EMPTY_NODE;const i=Fw(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(Mv,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const i=qw(e.visibleWrites,t);return n.forEachChild(Mv,(e,t)=>{const n=jw(qw(i,new J_(e)),t);r=r.updateImmediateChild(e,n)}),Lw(i).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return Lw(qw(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function Hw(e,n,r,i){return function(e,n,r,i,s){t(i||s,"Either existingEventSnap or existingServerSnap must exist");const o=ov(n,r);if(Mw(e.visibleWrites,o))return null;{const t=qw(e.visibleWrites,o);return Vw(t)?s.getChild(r):jw(t,s.getChild(r))}}(e.writeTree,e.treePath,n,r,i)}function Yw(e,t){return function(e,t){return Fw(e.visibleWrites,t)}(e.writeTree,ov(e.treePath,t))}function Xw(e,t,n){return function(e,t,n,r){const i=ov(t,n),s=Fw(e.visibleWrites,i);return null!=s?s:r.isCompleteForChild(n)?jw(qw(e.visibleWrites,i),r.getNode().getImmediateChild(n)):null}(e.writeTree,e.treePath,t,n)}function Jw(e,t){return Zw(ov(e.treePath,t),e.writeTree)}function Zw(e,t){return{treePath:e,writeTree:t}}class eb{constructor(){this.changeMap=new Map}trackChildChange(e){const n=e.type,i=e.childName;t("child_added"===n||"child_changed"===n||"child_removed"===n,"Only child changes supported for tracking"),t(".priority"!==i,"Only non-priority child changes can be tracked.");const s=this.changeMap.get(i);if(s){const t=s.type;if("child_added"===n&&"child_removed"===t)this.changeMap.set(i,Xv(i,e.snapshotNode,s.snapshotNode));else if("child_removed"===n&&"child_added"===t)this.changeMap.delete(i);else if("child_removed"===n&&"child_changed"===t)this.changeMap.set(i,Yv(i,s.oldSnap));else if("child_changed"===n&&"child_added"===t)this.changeMap.set(i,Hv(i,e.snapshotNode));else{if("child_changed"!==n||"child_changed"!==t)throw r("Illegal combination of changes: "+e+" occurred after "+s);this.changeMap.set(i,Xv(i,e.snapshotNode,s.oldSnap))}}else this.changeMap.set(i,e)}getChanges(){return Array.from(this.changeMap.values())}}const tb=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class nb{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);{const t=null!=this.optCompleteServerCache_?new bw(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Xw(this.writes_,e,t)}}getChildAfterChild(e,t,n){const r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:kw(this.viewCache_),i=function(e,t,n,r,i,s){return function(e,t,n,r,i,s,o){let a;const c=qw(e.visibleWrites,t),u=Fw(c,Z_());if(null!=u)a=u;else{if(null==n)return[];a=jw(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=s?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o);let c=n.getNext();for(;c&&e.length<i;)0!==t(c,r)&&e.push(c),c=n.getNext();return e}}(e.writeTree,e.treePath,t,n,r,i,s)}(this.writes_,r,t,1,n,e);return 0===i.length?null:i[0]}}function rb(e,n,r,i,s,o){const a=n.eventCache;if(null!=Yw(i,r))return n;{let c,u;if(av(r))if(t(n.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),n.serverCache.isFiltered()){const t=kw(n),r=Qw(i,t instanceof zv?t:zv.EMPTY_NODE);c=e.filter.updateFullNode(n.eventCache.getNode(),r,o)}else{const t=Ww(i,kw(n));c=e.filter.updateFullNode(n.eventCache.getNode(),t,o)}else{const l=ev(r);if(".priority"===l){t(1===tv(r),"Can't have a priority with additional path components");const s=a.getNode();u=n.serverCache.getNode();const o=Hw(i,r,s,u);c=null!=o?e.filter.updatePriority(s,o):a.getNode()}else{const t=nv(r);let h;if(a.isCompleteForChild(l)){u=n.serverCache.getNode();const e=Hw(i,r,a.getNode(),u);h=null!=e?a.getNode().getImmediateChild(l).updateChild(t,e):a.getNode().getImmediateChild(l)}else h=Xw(i,l,n.serverCache);c=null!=h?e.filter.updateChild(a.getNode(),l,h,t,s,o):a.getNode()}}return Tw(n,c,a.isFullyInitialized()||av(r),e.filter.filtersNodes())}}function ib(e,t,n,r,i,s,o,a){const c=t.serverCache;let u;const l=o?e.filter:e.filter.getIndexedFilter();if(av(n))u=l.updateFullNode(c.getNode(),r,null);else if(l.filtersNodes()&&!c.isFiltered()){const e=c.getNode().updateChild(n,r);u=l.updateFullNode(c.getNode(),e,null)}else{const e=ev(n);if(!c.isCompleteForPath(n)&&tv(n)>1)return t;const i=nv(n),s=c.getNode().getImmediateChild(e).updateChild(i,r);u=".priority"===e?l.updatePriority(c.getNode(),s):l.updateChild(c.getNode(),e,s,i,tb,null)}const h=Sw(t,u,c.isFullyInitialized()||av(n),l.filtersNodes());return rb(e,h,n,i,new nb(i,h,s),a)}function sb(e,t,n,r,i,s,o){const a=t.eventCache;let c,u;const l=new nb(i,t,s);if(av(n))u=e.filter.updateFullNode(t.eventCache.getNode(),r,o),c=Tw(t,u,!0,e.filter.filtersNodes());else{const i=ev(n);if(".priority"===i)u=e.filter.updatePriority(t.eventCache.getNode(),r),c=Tw(t,u,a.isFullyInitialized(),a.isFiltered());else{const s=nv(n),u=a.getNode().getImmediateChild(i);let h;if(av(s))h=r;else{const e=l.getCompleteChild(i);h=null!=e?".priority"===rv(s)&&e.getChild(sv(s)).isEmpty()?e:e.updateChild(s,r):zv.EMPTY_NODE}c=u.equals(h)?t:Tw(t,e.filter.updateChild(a.getNode(),i,h,s,l,o),a.isFullyInitialized(),e.filter.filtersNodes())}}return c}function ob(e,t){return e.eventCache.isCompleteForChild(t)}function ab(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function cb(e,t,n,r,i,s,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c,u=t;c=av(n)?r:new Dw(null).setTree(n,r);const l=t.serverCache.getNode();return c.children.inorderTraversal((n,r)=>{if(l.hasChild(n)){const c=ab(0,t.serverCache.getNode().getImmediateChild(n),r);u=ib(e,u,new J_(n),c,i,s,o,a)}}),c.children.inorderTraversal((n,r)=>{const c=!t.serverCache.isCompleteForChild(n)&&null===r.value;if(!l.hasChild(n)&&!c){const c=ab(0,t.serverCache.getNode().getImmediateChild(n),r);u=ib(e,u,new J_(n),c,i,s,o,a)}}),u}class ub{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new Jv(n.getIndex()),i=(s=n).loadsAllData()?new Jv(s.getIndex()):s.hasLimit()?new ew(s):new Zv(s);var s;this.processor_=function(e){return{filter:e}}(i);const o=t.serverCache,a=t.eventCache,c=r.updateFullNode(zv.EMPTY_NODE,o.getNode(),null),u=i.updateFullNode(zv.EMPTY_NODE,a.getNode(),null),l=new bw(c,o.isFullyInitialized(),r.filtersNodes()),h=new bw(u,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=Cw(h,l),this.eventGenerator_=new Iw(this.query_)}get query(){return this.query_}}function lb(e,t){const n=kw(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!av(t)&&!n.getImmediateChild(ev(t)).isEmpty())?n.getChild(t):null}function hb(e){return 0===e.eventRegistrations_.length}function db(e,n,r){const i=[];if(r){t(null==n,"A cancel should cancel all event registrations.");const s=e.query._path;e.eventRegistrations_.forEach(e=>{const t=e.createCancelEvent(r,s);t&&i.push(t)})}if(n){let t=[];for(let r=0;r<e.eventRegistrations_.length;++r){const i=e.eventRegistrations_[r];if(i.matches(n)){if(n.hasAnyCallback()){t=t.concat(e.eventRegistrations_.slice(r+1));break}}else t.push(i)}e.eventRegistrations_=t}else e.eventRegistrations_=[];return i}function fb(e,n,i,s){n.type===gw.MERGE&&null!==n.source.queryId&&(t(kw(e.viewCache_),"We should always have a full cache before handling merges"),t(xw(e.viewCache_),"Missing event cache, even though we have a server cache"));const o=e.viewCache_,a=function(e,n,i,s,o){const a=new eb;let c,u;if(i.type===gw.OVERWRITE){const r=i;r.source.fromUser?c=sb(e,n,r.path,r.snap,s,o,a):(t(r.source.fromServer,"Unknown source."),u=r.source.tagged||n.serverCache.isFiltered()&&!av(r.path),c=ib(e,n,r.path,r.snap,s,o,u,a))}else if(i.type===gw.MERGE){const r=i;r.source.fromUser?c=function(e,t,n,r,i,s,o){let a=t;return r.foreach((r,c)=>{const u=ov(n,r);ob(t,ev(u))&&(a=sb(e,a,u,c,i,s,o))}),r.foreach((r,c)=>{const u=ov(n,r);ob(t,ev(u))||(a=sb(e,a,u,c,i,s,o))}),a}(e,n,r.path,r.children,s,o,a):(t(r.source.fromServer,"Unknown source."),u=r.source.tagged||n.serverCache.isFiltered(),c=cb(e,n,r.path,r.children,s,o,u,a))}else if(i.type===gw.ACK_USER_WRITE){const r=i;c=r.revert?function(e,n,r,i,s,o){let a;if(null!=Yw(i,r))return n;{const c=new nb(i,n,s),u=n.eventCache.getNode();let l;if(av(r)||".priority"===ev(r)){let r;if(n.serverCache.isFullyInitialized())r=Ww(i,kw(n));else{const e=n.serverCache.getNode();t(e instanceof zv,"serverChildren would be complete if leaf node"),r=Qw(i,e)}l=e.filter.updateFullNode(u,r,o)}else{const t=ev(r);let s=Xw(i,t,n.serverCache);null==s&&n.serverCache.isCompleteForChild(t)&&(s=u.getImmediateChild(t)),l=null!=s?e.filter.updateChild(u,t,s,nv(r),c,o):n.eventCache.getNode().hasChild(t)?e.filter.updateChild(u,t,zv.EMPTY_NODE,nv(r),c,o):u,l.isEmpty()&&n.serverCache.isFullyInitialized()&&(a=Ww(i,kw(n)),a.isLeafNode()&&(l=e.filter.updateFullNode(l,a,o)))}return a=n.serverCache.isFullyInitialized()||null!=Yw(i,Z_()),Tw(n,l,a,e.filter.filtersNodes())}}(e,n,r.path,s,o,a):function(e,t,n,r,i,s,o){if(null!=Yw(i,n))return t;const a=t.serverCache.isFiltered(),c=t.serverCache;if(null!=r.value){if(av(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return ib(e,t,n,c.getNode().getChild(n),i,s,a,o);if(av(n)){let r=new Dw(null);return c.getNode().forEachChild(Iv,(e,t)=>{r=r.set(new J_(e),t)}),cb(e,t,n,r,i,s,a,o)}return t}{let u=new Dw(null);return r.foreach((e,t)=>{const r=ov(n,e);c.isCompleteForPath(r)&&(u=u.set(e,c.getNode().getChild(r)))}),cb(e,t,n,u,i,s,a,o)}}(e,n,r.path,r.affectedTree,s,o,a)}else{if(i.type!==gw.LISTEN_COMPLETE)throw r("Unknown operation type: "+i.type);c=function(e,t,n,r,i){const s=t.serverCache;return rb(e,Sw(t,s.getNode(),s.isFullyInitialized()||av(n),s.isFiltered()),n,r,tb,i)}(e,n,i.path,s,a)}const l=a.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){const i=r.getNode().isLeafNode()||r.getNode().isEmpty(),s=xw(e);(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(Qv(xw(t)))}}(n,c,l),{viewCache:c,changes:l}}(e.processor_,o,n,i,s);var c,u;return c=e.processor_,u=a.viewCache,t(u.eventCache.getNode().isIndexed(c.filter.getIndex()),"Event snap not indexed"),t(u.serverCache.getNode().isIndexed(c.filter.getIndex()),"Server snap not indexed"),t(a.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=a.viewCache,pb(e,a.changes,a.viewCache.eventCache.getNode(),null)}function pb(e,t,n,r){const i=r?[r]:e.eventRegistrations_;return function(e,t,n,r){const i=[],s=[];return t.forEach(t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&s.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))}),Ew(e,i,"child_removed",t,r,n),Ew(e,i,"child_added",t,r,n),Ew(e,i,"child_moved",s,r,n),Ew(e,i,"child_changed",t,r,n),Ew(e,i,"value",t,r,n),i}(e.eventGenerator_,t,n,i)}let gb,mb;class yb{constructor(){this.views=new Map}}function _b(e,n,r,i){const s=n.source.queryId;if(null!==s){const o=e.views.get(s);return t(null!=o,"SyncTree gave us an op for an invalid query."),fb(o,n,r,i)}{let t=[];for(const s of e.views.values())t=t.concat(fb(s,n,r,i));return t}}function vb(e,t,n,r,i){const s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=Ww(n,i?r:null),s=!1;e?s=!0:r instanceof zv?(e=Qw(n,r),s=!1):(e=zv.EMPTY_NODE,s=!1);const o=Cw(new bw(e,s,!1),new bw(r,i,!1));return new ub(t,o)}return o}function wb(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function bb(e,t){let n=null;for(const r of e.views.values())n=n||lb(r,t);return n}function Ib(e,t){if(t._queryParams.loadsAllData())return Tb(e);{const n=t._queryIdentifier;return e.views.get(n)}}function Eb(e,t){return null!=Ib(e,t)}function Cb(e){return null!=Tb(e)}function Tb(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Sb=1;class xb{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Dw(null),this.pendingWriteTree_={visibleWrites:Aw.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function kb(e,n,r,i,s){return function(e,n,r,i,s){t(i>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===s&&(s=!0),e.allWrites.push({path:n,snap:r,writeId:i,visible:s}),s&&(e.visibleWrites=Pw(e.visibleWrites,n,r)),e.lastWriteId=i}(e.pendingWriteTree_,n,r,i,s),s?Mb(e,new vw({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},n,r)):[]}function Nb(e,n,r=!1){const i=function(e,t){for(let n=0;n<e.allWrites.length;n++){const r=e.allWrites[n];if(r.writeId===t)return r}return null}(e.pendingWriteTree_,n);if(function(e,n){const r=e.allWrites.findIndex(e=>e.writeId===n);t(r>=0,"removeWrite called with nonexistent writeId.");const i=e.allWrites[r];e.allWrites.splice(r,1);let s=i.visible,o=!1,a=e.allWrites.length-1;for(;s&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=r&&zw(t,i.path)?s=!1:hv(i.path,t.path)&&(o=!0)),a--}return!!s&&(o?(function(e){e.visibleWrites=Gw(e.allWrites,$w,Z_()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0):(i.snap?e.visibleWrites=Ow(e.visibleWrites,i.path):b_(i.children,t=>{e.visibleWrites=Ow(e.visibleWrites,ov(i.path,t))}),!0))}(e.pendingWriteTree_,n)){let t=new Dw(null);return null!=i.snap?t=t.set(Z_(),!0):b_(i.children,e=>{t=t.set(new J_(e),!0)}),Mb(e,new yw(i.path,t,r))}return[]}function Db(e,t,n){return Mb(e,new vw({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function Ab(e,n,r,i,s=!1){const o=n._path,a=e.syncPointTree_.get(o);let c=[];if(a&&("default"===n._queryIdentifier||Eb(a,n))){const u=function(e,n,r,i){const s=n._queryIdentifier,o=[];let a=[];const c=Cb(e);if("default"===s)for(const[t,n]of e.views.entries())a=a.concat(db(n,r,i)),hb(n)&&(e.views.delete(t),n.query._queryParams.loadsAllData()||o.push(n.query));else{const t=e.views.get(s);t&&(a=a.concat(db(t,r,i)),hb(t)&&(e.views.delete(s),t.query._queryParams.loadsAllData()||o.push(t.query)))}return c&&!Cb(e)&&o.push(new(t(gb,"Reference.ts has not been loaded"),gb)(n._repo,n._path)),{removed:o,events:a}}(a,n,r,i);0===a.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(o));const l=u.removed;if(c=u.events,!s){const t=-1!==l.findIndex(e=>e._queryParams.loadsAllData()),r=e.syncPointTree_.findOnPath(o,(e,t)=>Cb(t));if(t&&!r){const t=e.syncPointTree_.subtree(o);if(!t.isEmpty()){const n=function(e){return e.fold((e,t,n)=>{if(t&&Cb(t))return[Tb(t)];{let e=[];return t&&(e=wb(t)),b_(n,(t,n)=>{e=e.concat(n)}),e}})}(t);for(let t=0;t<n.length;++t){const r=n[t],i=r.query,s=qb(e,r);e.listenProvider_.startListening($b(i),Vb(e,i),s.hashFn,s.onComplete)}}}if(!r&&l.length>0&&!i)if(t){const t=null;e.listenProvider_.stopListening($b(n),t)}else l.forEach(t=>{const n=e.queryToTagMap.get(jb(t));e.listenProvider_.stopListening($b(t),n)})}!function(e,t){for(let n=0;n<t.length;++n){const r=t[n];if(!r._queryParams.loadsAllData()){const t=jb(r),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,l)}return c}function Pb(e,t,n,r){const i=Bb(e,r);if(null!=i){const r=Ub(i),s=r.path,o=r.queryId,a=cv(s,t);return zb(e,s,new vw(mw(o),a,n))}return[]}function Rb(e,n,r,i=!1){const s=n._path;let o=null,a=!1;e.syncPointTree_.foreachOnPath(s,(e,t)=>{const n=cv(e,s);o=o||bb(t,n),a=a||Cb(t)});let c,u=e.syncPointTree_.get(s);u?(a=a||Cb(u),o=o||bb(u,Z_())):(u=new yb,e.syncPointTree_=e.syncPointTree_.set(s,u)),null!=o?c=!0:(c=!1,o=zv.EMPTY_NODE,e.syncPointTree_.subtree(s).foreachChild((e,t)=>{const n=bb(t,Z_());n&&(o=o.updateImmediateChild(e,n))}));const l=Eb(u,n);if(!l&&!n._queryParams.loadsAllData()){const r=jb(n);t(!e.queryToTagMap.has(r),"View does not exist, but we have a tag");const i=Sb++;e.queryToTagMap.set(r,i),e.tagToQueryMap.set(i,r)}let h=function(e,t,n,r,i,s){const o=vb(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),function(e,t){e.eventRegistrations_.push(t)}(o,n),function(e,t){const n=e.viewCache_.eventCache,r=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(Mv,(e,t)=>{r.push(Hv(e,t))}),n.isFullyInitialized()&&r.push(Qv(n.getNode())),pb(e,r,n.getNode(),t)}(o,n)}(u,n,r,Uw(e.pendingWriteTree_,s),o,c);if(!l&&!a&&!i){const r=Ib(u,n);h=h.concat(function(e,n,r){const i=n._path,s=Vb(e,n),o=qb(e,r),a=e.listenProvider_.startListening($b(n),s,o.hashFn,o.onComplete),c=e.syncPointTree_.subtree(i);if(s)t(!Cb(c.value),"If we're adding a query, it shouldn't be shadowed");else{const t=c.fold((e,t,n)=>{if(!av(e)&&t&&Cb(t))return[Tb(t).query];{let e=[];return t&&(e=e.concat(wb(t).map(e=>e.query))),b_(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){const r=t[n];e.listenProvider_.stopListening($b(r),Vb(e,r))}}return a}(e,n,r))}return h}function Ob(e,t,n){const r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(t,(e,n)=>{const r=bb(n,cv(e,t));if(r)return r});return Kw(r,t,i,n,!0)}function Mb(e,t){return Fb(t,e.syncPointTree_,null,Uw(e.pendingWriteTree_,Z_()))}function Fb(e,t,n,r){if(av(e.path))return Lb(e,t,n,r);{const i=t.get(Z_());null==n&&null!=i&&(n=bb(i,Z_()));let s=[];const o=ev(e.path),a=e.operationForChild(o),c=t.children.get(o);if(c&&a){const e=n?n.getImmediateChild(o):null,t=Jw(r,o);s=s.concat(Fb(a,c,e,t))}return i&&(s=s.concat(_b(i,e,r,n))),s}}function Lb(e,t,n,r){const i=t.get(Z_());null==n&&null!=i&&(n=bb(i,Z_()));let s=[];return t.children.inorderTraversal((t,i)=>{const o=n?n.getImmediateChild(t):null,a=Jw(r,t),c=e.operationForChild(t);c&&(s=s.concat(Lb(c,i,o,a)))}),i&&(s=s.concat(_b(i,e,r,n))),s}function qb(e,t){const n=t.query,r=Vb(e,n);return{hashFn:()=>{const e=function(e){return e.viewCache_.serverCache.getNode()}(t)||zv.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return r?function(e,t,n){const r=Bb(e,n);if(r){const n=Ub(r),i=n.path,s=n.queryId,o=cv(i,t);return zb(e,i,new _w(mw(s),o))}return[]}(e,n._path,r):function(e,t){return Mb(e,new _w({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const 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}(t,n);return Ab(e,n,null,r)}}}}function Vb(e,t){const n=jb(t);return e.queryToTagMap.get(n)}function jb(e){return e._path.toString()+"$"+e._queryIdentifier}function Bb(e,t){return e.tagToQueryMap.get(t)}function Ub(e){const n=e.indexOf("$");return t(-1!==n&&n<e.length-1,"Bad queryKey."),{queryId:e.substr(n+1),path:new J_(e.substr(0,n))}}function zb(e,n,r){const i=e.syncPointTree_.get(n);return t(i,"Missing sync point for query tag that we're tracking"),_b(i,r,Uw(e.pendingWriteTree_,n),null)}function $b(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(t(mb,"Reference.ts has not been loaded"),mb)(e._repo,e._path):e}class Gb{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new Gb(t)}node(){return this.node_}}class Kb{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=ov(this.path_,e);return new Kb(this.syncTree_,t)}node(){return Ob(this.syncTree_,this.path_)}}const Wb=function(e,n,r){return e&&"object"==typeof e?(t(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Qb(e[".sv"],n,r):"object"==typeof e[".sv"]?Hb(e[".sv"],n):void t(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Qb=function(e,n,r){if("timestamp"===e)return r.timestamp;t(!1,"Unexpected server value: "+e)},Hb=function(e,n,r){e.hasOwnProperty("increment")||t(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const i=e.increment;"number"!=typeof i&&t(!1,"Unexpected increment value: "+i);const s=n.node();if(t(null!=s,"Expected ChildrenNode.EMPTY_NODE for nulls"),!s.isLeafNode())return i;const o=s.getValue();return"number"!=typeof o?i:o+i},Yb=function(e,t,n,r){return Jb(t,new Kb(n,e),r)},Xb=function(e,t,n){return Jb(e,new Gb(t),n)};function Jb(e,t,n){const r=e.getPriority().val(),i=Wb(r,t.getImmediateChild(".priority"),n);let s;if(e.isLeafNode()){const r=e,s=Wb(r.getValue(),t,n);return s!==r.getValue()||i!==r.getPriority().val()?new Ov(s,Gv(i)):e}{const r=e;return s=r,i!==r.getPriority().val()&&(s=s.updatePriority(new Ov(i))),r.forEachChild(Mv,(e,r)=>{const i=Jb(r,t.getImmediateChild(e),n);i!==r&&(s=s.updateImmediateChild(e,i))}),s}}class Zb{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function eI(e,t){let n=t instanceof J_?t:new J_(t),r=e,i=ev(n);for(;null!==i;){const e=S(r.node.children,i)||{children:{},childCount:0};r=new Zb(i,r,e),n=nv(n),i=ev(n)}return r}function tI(e){return e.node.value}function nI(e,t){e.node.value=t,aI(e)}function rI(e){return e.node.childCount>0}function iI(e,t){b_(e.node.children,(n,r)=>{t(new Zb(n,e,r))})}function sI(e,t,n,r){n&&!r&&t(e),iI(e,e=>{sI(e,t,!0,r)}),n&&r&&t(e)}function oI(e){return new J_(null===e.parent?e.name:oI(e.parent)+"/"+e.name)}function aI(e){null!==e.parent&&function(e,t,n){const r=function(e){return void 0===tI(e)&&!rI(e)}(n),i=T(e.node.children,t);r&&i?(delete e.node.children[t],e.node.childCount--,aI(e)):r||i||(e.node.children[t]=n.node,e.node.childCount++,aI(e))}(e.parent,e.name,e)}const cI=/[\[\].#$\/\u0000-\u001F\u007F]/,uI=/[\[\].#$\u0000-\u001F\u007F]/,lI=10485760,hI=function(e){return"string"==typeof e&&0!==e.length&&!cI.test(e)},dI=function(e){return"string"==typeof e&&0!==e.length&&!uI.test(e)},fI=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!f_(e)||e&&"object"==typeof e&&T(e,".sv")},pI=function(e,t,n,r){r&&void 0===t||gI(F(e,"value"),t,n)},gI=function(e,t,n){const r=n instanceof J_?new dv(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+pv(r));if("function"==typeof t)throw new Error(e+"contains a function "+pv(r)+" with contents = "+t.toString());if(f_(t))throw new Error(e+"contains "+t.toString()+" "+pv(r));if("string"==typeof t&&t.length>lI/3&&V(t)>lI)throw new Error(e+"contains a string greater than "+lI+" utf8 bytes "+pv(r)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,i=!1;if(b_(t,(t,s)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(i=!0,!hI(t)))throw new Error(e+" contains an invalid key ("+t+") "+pv(r)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=V(t),fv(e)}(r,t),gI(e,s,r),function(e){const t=e.parts_.pop();e.byteLength_-=V(t),e.parts_.length>0&&(e.byteLength_-=1)}(r)}),n&&i)throw new Error(e+' contains ".value" child '+pv(r)+" in addition to actual children.")}},mI=function(e,t,n,r){if(r&&void 0===t)return;const i=F(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=[];b_(t,(e,t)=>{const r=new J_(e);if(gI(i,t,ov(n,r)),".priority"===rv(r)&&!fI(t))throw new Error(i+"contains an invalid value for '"+r.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(r)}),function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];const i=iv(r);for(let t=0;t<i.length;t++)if(".priority"===i[t]&&t===i.length-1);else if(!hI(i[t]))throw new Error(e+"contains an invalid key ("+i[t]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(uv);let i=null;for(n=0;n<t.length;n++){if(r=t[n],null!==i&&hv(i,r))throw new Error(e+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString());i=r}}(i,s)},yI=function(e,t,n){if(!n||void 0!==t){if(f_(t))throw new Error(F(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!fI(t))throw new Error(F(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},_I=function(e,t,n,r){if(!(r&&void 0===n||hI(n)))throw new Error(F(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},vI=function(e,t,n,r){if(!(r&&void 0===n||dI(n)))throw new Error(F(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},wI=function(e,t){if(".info"===ev(t))throw new Error(e+" failed = Can't modify data under /.info/")},bI=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!hI(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),dI(e)}(n))throw new Error(F(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class II{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function EI(e,t){let n=null;for(let r=0;r<t.length;r++){const i=t[r],s=i.getPath();null===n||lv(s,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:s}),n.events.push(i)}n&&e.eventLists_.push(n)}function CI(e,t,n){EI(e,n),SI(e,e=>lv(e,t))}function TI(e,t,n){EI(e,n),SI(e,e=>hv(e,t)||hv(t,e))}function SI(e,t){e.recursionDepth_++;let n=!0;for(let r=0;r<e.eventLists_.length;r++){const i=e.eventLists_[r];i&&(t(i.path)?(xI(e.eventLists_[r]),e.eventLists_[r]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}function xI(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const r=n.getEventRunner();s_&&c_("event: "+n.toString()),T_(r)}}}const kI="repo_interrupt";class NI{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 II,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=uw(),this.transactionQueueTree_=new Zb,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function DI(e,t,n){if(e.stats_=j_(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new aw(e.repoInfo_,(t,n,r,i)=>{RI(e,t,n,r,i)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>OI(e,!0),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{E(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new yv(e.repoInfo_,t,(t,n,r,i)=>{RI(e,t,n,r,i)},t=>{OI(e,t)},t=>{!function(e,t){b_(t,(t,n)=>{MI(e,t,n)})}(e,t)},e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener(t=>{e.server_.refreshAuthToken(t)}),e.appCheckProvider_.addTokenChangeListener(t=>{e.server_.refreshAppCheckToken(t.token)}),e.statsReporter_=function(t){const n=t.toString();return V_[n]||(V_[n]=new pw(e.stats_,e.server_)),V_[n]}(e.repoInfo_),e.infoData_=new cw,e.infoSyncTree_=new xb({startListening:(t,n,r,i)=>{let s=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=Db(e.infoSyncTree_,t._path,o),setTimeout(()=>{i("ok")},0)),s},stopListening:()=>{}}),MI(e,"connected",!1),e.serverSyncTree_=new xb({startListening:(t,n,r,i)=>(e.server_.listen(t,r,n,(n,r)=>{const s=i(n,r);TI(e.eventQueue_,t._path,s)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function AI(e){const t=e.infoData_.getNode(new J_(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function PI(e){return(t=(t={timestamp:AI(e)})||{}).timestamp=t.timestamp||(new Date).getTime(),t;var t}function RI(e,t,n,r,i){e.dataUpdateCount++;const s=new J_(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(i)if(r){const t=k(n,e=>Gv(e));o=function(e,t,n,r){const i=Bb(e,r);if(i){const r=Ub(i),s=r.path,o=r.queryId,a=cv(s,t),c=Dw.fromObject(n);return zb(e,s,new ww(mw(o),a,c))}return[]}(e.serverSyncTree_,s,t,i)}else{const t=Gv(n);o=Pb(e.serverSyncTree_,s,t,i)}else if(r){const t=k(n,e=>Gv(e));o=function(e,t,n){const r=Dw.fromObject(n);return Mb(e,new ww({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,r))}(e.serverSyncTree_,s,t)}else{const t=Gv(n);o=Db(e.serverSyncTree_,s,t)}let a=s;o.length>0&&(a=KI(e,s)),TI(e.eventQueue_,a,o)}function OI(e,t){MI(e,"connected",t),!1===t&&function(e){UI(e,"onDisconnectEvents");const t=PI(e),n=uw();dw(e.onDisconnect_,Z_(),(r,i)=>{const s=Yb(r,i,e.serverSyncTree_,t);lw(n,r,s)});let r=[];dw(n,Z_(),(t,n)=>{r=r.concat(Db(e.serverSyncTree_,t,n));const i=XI(e,t);KI(e,i)}),e.onDisconnect_=uw(),TI(e.eventQueue_,Z_(),r)}(e)}function MI(e,t,n){const r=new J_("/.info/"+t),i=Gv(n);e.infoData_.updateSnapshot(r,i);const s=Db(e.infoSyncTree_,r,i);TI(e.eventQueue_,r,s)}function FI(e){return e.nextWriteId_++}function LI(e,t,n,r,i){UI(e,"set",{path:t.toString(),value:n,priority:r});const s=PI(e),o=Gv(n,r),a=Ob(e.serverSyncTree_,t),c=Xb(o,a,s),u=FI(e),l=kb(e.serverSyncTree_,t,c,u,!0);EI(e.eventQueue_,l),e.server_.put(t.toString(),o.val(!0),(n,r)=>{const s="ok"===n;s||d_("set at "+t+" failed: "+n);const o=Nb(e.serverSyncTree_,u,!s);TI(e.eventQueue_,t,o),zI(0,i,n,r)});const h=XI(e,t);KI(e,h),TI(e.eventQueue_,h,[])}function qI(e,t,n){e.server_.onDisconnectCancel(t.toString(),(r,i)=>{"ok"===r&&hw(e.onDisconnect_,t),zI(0,n,r,i)})}function VI(e,t,n,r){const i=Gv(n);e.server_.onDisconnectPut(t.toString(),i.val(!0),(n,s)=>{"ok"===n&&lw(e.onDisconnect_,t,i),zI(0,r,n,s)})}function jI(e,t,n){let r;r=".info"===ev(t._path)?Ab(e.infoSyncTree_,t,n):Ab(e.serverSyncTree_,t,n),CI(e.eventQueue_,t._path,r)}function BI(e){e.persistentConnection_&&e.persistentConnection_.interrupt(kI)}function UI(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),c_(n,...t)}function zI(e,t,n,r){t&&T_(()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let i=e;r&&(i+=": "+r);const s=new Error(i);s.code=e,t(s)}})}function $I(e,t,n){return Ob(e.serverSyncTree_,t,n)||zv.EMPTY_NODE}function GI(e,n=e.transactionQueueTree_){if(n||YI(e,n),tI(n)){const r=QI(e,n);t(r.length>0,"Sending zero length transaction queue"),r.every(e=>0===e.status)&&function(e,n,r){const i=r.map(e=>e.currentWriteId),s=$I(e,n,i);let o=s;const a=s.hash();for(let e=0;e<r.length;e++){const i=r[e];t(0===i.status,"tryToSendTransactionQueue_: items in queue should all be run."),i.status=1,i.retryCount++;const s=cv(n,i.path);o=o.updateChild(s,i.currentOutputSnapshotRaw)}const c=o.val(!0),u=n;e.server_.put(u.toString(),c,t=>{UI(e,"transaction put response",{path:u.toString(),status:t});let i=[];if("ok"===t){const t=[];for(let n=0;n<r.length;n++)r[n].status=2,i=i.concat(Nb(e.serverSyncTree_,r[n].currentWriteId)),r[n].onComplete&&t.push(()=>r[n].onComplete(null,!0,r[n].currentOutputSnapshotResolved)),r[n].unwatcher();YI(e,eI(e.transactionQueueTree_,n)),GI(e,e.transactionQueueTree_),TI(e.eventQueue_,n,i);for(let e=0;e<t.length;e++)T_(t[e])}else{if("datastale"===t)for(let e=0;e<r.length;e++)3===r[e].status?r[e].status=4:r[e].status=0;else{d_("transaction at "+u.toString()+" failed: "+t);for(let e=0;e<r.length;e++)r[e].status=4,r[e].abortReason=t}KI(e,n)}},a)}(e,oI(n),r)}else rI(n)&&iI(n,t=>{GI(e,t)})}function KI(e,n){const r=WI(e,n),i=oI(r);return function(e,n,r){if(0===n.length)return;const i=[];let s=[];const o=n.filter(e=>0===e.status),a=o.map(e=>e.currentWriteId);for(let o=0;o<n.length;o++){const c=n[o],u=cv(r,c.path);let l,h=!1;if(t(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),4===c.status)h=!0,l=c.abortReason,s=s.concat(Nb(e.serverSyncTree_,c.currentWriteId,!0));else if(0===c.status)if(c.retryCount>=25)h=!0,l="maxretry",s=s.concat(Nb(e.serverSyncTree_,c.currentWriteId,!0));else{const t=$I(e,c.path,a);c.currentInputSnapshot=t;const r=n[o].update(t.val());if(void 0!==r){gI("transaction failed: Data returned ",r,c.path);let n=Gv(r);"object"==typeof r&&null!=r&&T(r,".priority")||(n=n.updatePriority(t.getPriority()));const i=c.currentWriteId,o=PI(e),u=Xb(n,t,o);c.currentOutputSnapshotRaw=n,c.currentOutputSnapshotResolved=u,c.currentWriteId=FI(e),a.splice(a.indexOf(i),1),s=s.concat(kb(e.serverSyncTree_,c.path,u,c.currentWriteId,c.applyLocally)),s=s.concat(Nb(e.serverSyncTree_,i,!0))}else h=!0,l="nodata",s=s.concat(Nb(e.serverSyncTree_,c.currentWriteId,!0))}TI(e.eventQueue_,r,s),s=[],h&&(n[o].status=2,function(e){setTimeout(e,Math.floor(0))}(n[o].unwatcher),n[o].onComplete&&("nodata"===l?i.push(()=>n[o].onComplete(null,!1,n[o].currentInputSnapshot)):i.push(()=>n[o].onComplete(new Error(l),!1,null))))}YI(e,e.transactionQueueTree_);for(let e=0;e<i.length;e++)T_(i[e]);GI(e,e.transactionQueueTree_)}(e,QI(e,r),i),i}function WI(e,t){let n,r=e.transactionQueueTree_;for(n=ev(t);null!==n&&void 0===tI(r);)r=eI(r,n),n=ev(t=nv(t));return r}function QI(e,t){const n=[];return HI(e,t,n),n.sort((e,t)=>e.order-t.order),n}function HI(e,t,n){const r=tI(t);if(r)for(let e=0;e<r.length;e++)n.push(r[e]);iI(t,t=>{HI(e,t,n)})}function YI(e,t){const n=tI(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,nI(t,n.length>0?n:void 0)}iI(t,t=>{YI(e,t)})}function XI(e,t){const n=oI(WI(e,t)),r=eI(e.transactionQueueTree_,t);return function(e,t){let n=e.parent;for(;null!==n;){if(t(n))return!0;n=n.parent}}(r,t=>{JI(e,t)}),JI(e,r),sI(r,t=>{JI(e,t)}),n}function JI(e,n){const r=tI(n);if(r){const i=[];let s=[],o=-1;for(let n=0;n<r.length;n++)3===r[n].status||(1===r[n].status?(t(o===n-1,"All SENT items should be at beginning of queue."),o=n,r[n].status=3,r[n].abortReason="set"):(t(0===r[n].status,"Unexpected transaction status in abort"),r[n].unwatcher(),s=s.concat(Nb(e.serverSyncTree_,r[n].currentWriteId,!0)),r[n].onComplete&&i.push(r[n].onComplete.bind(null,new Error("set"),!1,null))));-1===o?nI(n,void 0):r.length=o+1,TI(e.eventQueue_,oI(n),s);for(let e=0;e<i.length;e++)T_(i[e])}}const ZI=function(e,t){const n=eE(e),r=n.namespace;"firebase.com"===n.domain&&h_(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||h_("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&d_("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new M_(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new J_(n.pathString)}},eE=function(e){let t="",n="",r="",i="",s="",o=!0,a="https",c=443;if("string"==typeof e){let u=e.indexOf("//");u>=0&&(a=e.substring(0,u-1),e=e.substring(u+2));let l=e.indexOf("/");-1===l&&(l=e.length);let h=e.indexOf("?");-1===h&&(h=e.length),t=e.substring(0,Math.min(l,h)),l<h&&(i=function(e){let t="";const n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g," "))}catch(e){}t+="/"+r}return t}(e.substring(l,h)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const r=n.split("=");2===r.length?t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):d_(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,h)));u=t.indexOf(":"),u>=0?(o="https"===a||"wss"===a,c=parseInt(t.substring(u+1),10)):u=t.length;const f=t.slice(0,u);if("localhost"===f.toLowerCase())n="localhost";else if(f.split(".").length<=2)n=f;else{const e=t.indexOf(".");r=t.substring(0,e).toLowerCase(),n=t.substring(e+1),s=r}"ns"in d&&(s=d.ns)}return{host:t,port:c,domain:n,subdomain:r,secure:o,scheme:a,pathString:i,namespace:s}},tE="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",nE=function(){let e=0;const n=[];return function(r){const i=r===e;let s;e=r;const o=new Array(8);for(s=7;s>=0;s--)o[s]=tE.charAt(r%64),r=Math.floor(r/64);t(0===r,"Cannot push at time == 0");let a=o.join("");if(i){for(s=11;s>=0&&63===n[s];s--)n[s]=0;n[s]++}else for(s=0;s<12;s++)n[s]=Math.floor(64*Math.random());for(s=0;s<12;s++)a+=tE.charAt(n[s]);return t(20===a.length,"nextPushId: Length should be 20."),a}}();class rE{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+E(this.snapshot.exportVal())}}class iE{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 sE{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return t(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 oE{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new p;return qI(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){wI("OnDisconnect.remove",this._path);const e=new p;return VI(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){wI("OnDisconnect.set",this._path),pI("OnDisconnect.set",e,this._path,!1);const t=new p;return VI(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){wI("OnDisconnect.setWithPriority",this._path),pI("OnDisconnect.setWithPriority",e,this._path,!1),yI("OnDisconnect.setWithPriority",t,!1);const n=new p;return function(e,t,n,r,i){const s=Gv(n,r);e.server_.onDisconnectPut(t.toString(),s.val(!0),(n,r)=>{"ok"===n&&lw(e.onDisconnect_,t,s),zI(0,i,n,r)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){wI("OnDisconnect.update",this._path),mI("OnDisconnect.update",e,this._path,!1);const t=new p;return function(e,t,n,r){if(x(n))return c_("onDisconnect().update() called with empty data. Don't do anything."),void zI(0,r,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,(i,s)=>{"ok"===i&&b_(n,(n,r)=>{const i=Gv(r);lw(e.onDisconnect_,ov(t,n),i)}),zI(0,r,i,s)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class aE{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return av(this._path)?null:rv(this._path)}get ref(){return new hE(this._repo,this._path)}get _queryIdentifier(){const e=ow(this._queryParams),t=v_(e);return"{}"===t?"default":t}get _queryObject(){return ow(this._queryParams)}isEqual(e){if(!((e=j(e))instanceof aE))return!1;const t=this._repo===e._repo,n=lv(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 cE(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function uE(e){let n=null,r=null;if(e.hasStart()&&(n=e.getIndexStartValue()),e.hasEnd()&&(r=e.getIndexEndValue()),e.getIndex()===Iv){const t="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()!==p_)throw new Error(t);if("string"!=typeof n)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==g_)throw new Error(t);if("string"!=typeof r)throw new Error(i)}}else if(e.getIndex()===Mv){if(null!=n&&!fI(n)||null!=r&&!fI(r))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(t(e.getIndex()instanceof Kv||e.getIndex()===Wv,"unknown index type."),null!=n&&"object"==typeof n||null!=r&&"object"==typeof r)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function lE(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 hE extends aE{constructor(e,t){super(e,t,new tw,!1)}get parent(){const e=sv(this._path);return null===e?null:new hE(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class dE{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){const t=new J_(e),n=gE(this.ref,e);return new dE(this._node.getChild(t),n,Mv)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(t,n)=>e(new dE(n,gE(this.ref,t),Mv)))}hasChild(e){const t=new J_(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 fE(e,t){return(e=j(e))._checkNotDeleted("ref"),void 0!==t?gE(e._root,t):e._root}function pE(e,t){(e=j(e))._checkNotDeleted("refFromURL");const n=ZI(t,e._repo.repoInfo_.nodeAdmin);bI("refFromURL",n);const r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||h_("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),fE(e,n.path.toString())}function gE(e,t){var n;return null===ev((e=j(e))._path)?((n=t)&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),vI("child","path",n,false)):vI("child","path",t,!1),new hE(e._repo,ov(e._path,t))}function mE(e,t){e=j(e),wI("set",e._path),pI("set",t,e._path,!1);const n=new p;return LI(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function yE(e,n){mI("update",n,e._path,!1);const r=new p;return function(e,n,r,i){UI(e,"update",{path:n.toString(),value:r});let s=!0;const o=PI(e),a={};if(b_(r,(t,r)=>{s=!1,a[t]=Yb(ov(n,t),Gv(r),e.serverSyncTree_,o)}),s)c_("update() called with empty data. Don't do anything."),zI(0,i,"ok",void 0);else{const s=FI(e),o=function(e,n,r,i){!function(e,n,r,i){t(i>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:n,children:r,writeId:i,visible:!0}),e.visibleWrites=Rw(e.visibleWrites,n,r),e.lastWriteId=i}(e.pendingWriteTree_,n,r,i);const s=Dw.fromObject(r);return Mb(e,new ww({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},n,s))}(e.serverSyncTree_,n,a,s);EI(e.eventQueue_,o),e.server_.merge(n.toString(),r,(t,r)=>{const o="ok"===t;o||d_("update at "+n+" failed: "+t);const a=Nb(e.serverSyncTree_,s,!o),c=a.length>0?KI(e,n):n;TI(e.eventQueue_,c,a),zI(0,i,t,r)}),b_(r,t=>{const r=XI(e,ov(n,t));KI(e,r)}),TI(e.eventQueue_,n,[])}}(e._repo,e._path,n,r.wrapCallback(()=>{})),r.promise}function _E(e){e=j(e);const t=new sE(()=>{}),n=new vE(t);return function(e,t,n){const r=function(e,t){const n=t._path;let r=null;e.syncPointTree_.foreachOnPath(n,(e,t)=>{const i=cv(e,n);r=r||bb(t,i)});let i=e.syncPointTree_.get(n);i?r=r||bb(i,Z_()):(i=new yb,e.syncPointTree_=e.syncPointTree_.set(n,i));const s=null!=r,o=s?new bw(r,!0,!1):null;return xw(vb(i,t,Uw(e.pendingWriteTree_,t._path),s?o.getNode():zv.EMPTY_NODE,s).viewCache_)}(e.serverSyncTree_,t);return null!=r?Promise.resolve(r):e.server_.get(t).then(r=>{const i=Gv(r).withIndex(t._queryParams.getIndex());let s;if(Rb(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())s=Db(e.serverSyncTree_,t._path,i);else{const n=Vb(e.serverSyncTree_,t);s=Pb(e.serverSyncTree_,t._path,i,n)}return TI(e.eventQueue_,t._path,s),Ab(e.serverSyncTree_,t,n,null,!0),i},n=>(UI(e,"get for query "+E(t)+" failed: "+n),Promise.reject(new Error(n))))}(e._repo,e,n).then(t=>new dE(t,new hE(e._repo,e._path),e._queryParams.getIndex()))}class vE{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new rE("value",this,new dE(e.snapshotNode,new hE(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 iE(this,e,t):null}matches(e){return e instanceof vE&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class wE{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 iE(this,e,t):null}createEvent(e,n){t(null!=e.childName,"Child events should have a childName.");const r=gE(new hE(n._repo,n._path),e.childName),i=n._queryParams.getIndex();return new rE(e.type,this,new dE(e.snapshotNode,r,i),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 wE&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function bE(e,t,n,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const t=n,r=(n,r)=>{jI(e._repo,e,a),t(n,r)};r.userCallback=n.userCallback,r.context=n.context,n=r}const o=new sE(n,s||void 0),a="value"===t?new vE(o):new wE(t,o);return function(e,t,n){let r;r=".info"===ev(t._path)?Rb(e.infoSyncTree_,t,n):Rb(e.serverSyncTree_,t,n),CI(e.eventQueue_,t._path,r)}(e._repo,e,a),()=>jI(e._repo,e,a)}function IE(e,t,n,r){return bE(e,"value",t,n,r)}function EE(e,t,n,r){return bE(e,"child_added",t,n,r)}function CE(e,t,n,r){return bE(e,"child_changed",t,n,r)}function TE(e,t,n,r){return bE(e,"child_moved",t,n,r)}function SE(e,t,n,r){return bE(e,"child_removed",t,n,r)}function xE(e,t,n){let r=null;const i=n?new sE(n):null;"value"===t?r=new vE(i):t&&(r=new wE(t,i)),jI(e._repo,e,r)}class kE{}class NE extends kE{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){pI("endAt",this._value,e._path,!0);const t=rw(e._queryParams,this._value,this._key);if(lE(t),uE(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new aE(e._repo,e._path,t,e._orderByCalled)}}class DE extends kE{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){pI("endBefore",this._value,e._path,!1);const t=function(e,t,n){let r;return r=e.index_===Iv||n?rw(e,t,n):rw(e,t,p_),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(lE(t),uE(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new aE(e._repo,e._path,t,e._orderByCalled)}}class AE extends kE{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){pI("startAt",this._value,e._path,!0);const t=nw(e._queryParams,this._value,this._key);if(lE(t),uE(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new aE(e._repo,e._path,t,e._orderByCalled)}}class PE extends kE{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){pI("startAfter",this._value,e._path,!1);const t=function(e,t,n){let r;return r=e.index_===Iv||n?nw(e,t,n):nw(e,t,g_),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(lE(t),uE(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new aE(e._repo,e._path,t,e._orderByCalled)}}class RE extends kE{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 aE(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 OE extends kE{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 aE(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 ME extends kE{constructor(e){super(),this._path=e}_apply(e){cE(e,"orderByChild");const t=new J_(this._path);if(av(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new Kv(t),r=iw(e._queryParams,n);return uE(r),new aE(e._repo,e._path,r,!0)}}class FE extends kE{_apply(e){cE(e,"orderByKey");const t=iw(e._queryParams,Iv);return uE(t),new aE(e._repo,e._path,t,!0)}}class LE extends kE{_apply(e){cE(e,"orderByPriority");const t=iw(e._queryParams,Mv);return uE(t),new aE(e._repo,e._path,t,!0)}}class qE extends kE{_apply(e){cE(e,"orderByValue");const t=iw(e._queryParams,Wv);return uE(t),new aE(e._repo,e._path,t,!0)}}class VE extends kE{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(pI("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 NE(this._value,this._key)._apply(new AE(this._value,this._key)._apply(e))}}function jE(e,...t){let n=j(e);for(const e of t)n=e._apply(n);return n}!function(e){t(!gb,"__referenceConstructor has already been defined"),gb=e}(hE),function(e){t(!mb,"__referenceConstructor has already been defined"),mb=e}(hE);const BE={};function UE(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||h_("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),c_("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o,a,c=ZI(s,i),u=c.repoInfo;"undefined"!=typeof process&&process.env&&(a=process.env.FIREBASE_DATABASE_EMULATOR_HOST),a?(o=!0,s=`http://${a}?ns=${u.namespace}`,c=ZI(s,i),u=c.repoInfo):o=!c.repoInfo.secure;const l=i&&o?new N_(N_.OWNER):new k_(e.name,e.options,t);bI("Invalid Firebase Database URL",c),av(c.path)||h_("Database URL must point to the root of a Firebase Database (not including a child path).");const h=function(e,t,n,r){let i=BE[t.name];i||(i={},BE[t.name]=i);let s=i[e.toURLString()];return s&&h_("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new NI(e,false,n,r),i[e.toURLString()]=s,s}(u,e,l,new x_(e.name,n));return new zE(h,e)}class zE{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(DI(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new hE(this._repo,Z_())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=BE[t];n&&n[e.key]===e||h_(`Database ${t}(${e.repoInfo_}) has already been deleted.`),BI(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&h_("Cannot call "+e+" on a deleted database.")}}function $E(){W_.IS_TRANSPORT_INITIALIZED&&d_("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function GE(){$E(),z_.forceDisallow()}function KE(){$E(),K_.forceDisallow(),z_.forceAllow()}function WE(e,t){a_(e,t)}class QE{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function HE(e,n,r){var i;if(e=j(e),wI("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const s=null===(i=null==r?void 0:r.applyLocally)||void 0===i||i,o=new p,a=IE(e,()=>{});return function(n,r,i,s,a,c){UI(n,"transaction on "+r);const u={path:r,update:i,onComplete:(t,n,r)=>{let i=null;t?o.reject(t):(i=new dE(r,new hE(e._repo,e._path),Mv),o.resolve(new QE(n,i)))},status:null,order:n_(),applyLocally:c,retryCount:0,unwatcher:a,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},l=$I(n,r,void 0);u.currentInputSnapshot=l;const h=u.update(l.val());if(void 0===h)u.unwatcher(),u.currentOutputSnapshotRaw=null,u.currentOutputSnapshotResolved=null,u.onComplete&&u.onComplete(null,!1,u.currentInputSnapshot);else{gI("transaction failed: Data returned ",h,u.path),u.status=0;const e=eI(n.transactionQueueTree_,r),i=tI(e)||[];let s;i.push(u),nI(e,i),"object"==typeof h&&null!==h&&T(h,".priority")?(s=S(h,".priority"),t(fI(s),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):s=(Ob(n.serverSyncTree_,r)||zv.EMPTY_NODE).getPriority().val();const o=PI(n),a=Gv(h,s),c=Xb(a,l,o);u.currentOutputSnapshotRaw=a,u.currentOutputSnapshotResolved=c,u.currentWriteId=FI(n);const d=kb(n.serverSyncTree_,r,c,u.currentWriteId,u.applyLocally);TI(n.eventQueue_,r,d),GI(n,n.transactionQueueTree_)}}(e._repo,e._path,n,0,a,s),o.promise}yv.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},yv.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Hy(et),Qe(new B("database",(e,{instanceIdentifier:t})=>UE(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),st(Ky,Wy,void 0),st(Ky,Wy,"esm2017");const YE=new X("@firebase/database-compat"),XE=function(e){const t="FIREBASE WARNING: "+e;YE.warn(t)};class JE{constructor(e){this._delegate=e}cancel(e){M("OnDisconnect.cancel",0,1,arguments.length),L("OnDisconnect.cancel","onComplete",e,!0);const t=this._delegate.cancel();return e&&t.then(()=>e(null),t=>e(t)),t}remove(e){M("OnDisconnect.remove",0,1,arguments.length),L("OnDisconnect.remove","onComplete",e,!0);const t=this._delegate.remove();return e&&t.then(()=>e(null),t=>e(t)),t}set(e,t){M("OnDisconnect.set",1,2,arguments.length),L("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){M("OnDisconnect.setWithPriority",2,3,arguments.length),L("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(e,t){if(M("OnDisconnect.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let n=0;n<e.length;++n)t[""+n]=e[n];e=t,XE("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.")}L("OnDisconnect.update","onComplete",t,!0);const n=this._delegate.update(e);return t&&n.then(()=>t(null),e=>t(e)),n}}class ZE{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return M("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class eC{constructor(e,t){this._database=e,this._delegate=t}val(){return M("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return M("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return M("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return M("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return M("DataSnapshot.child",0,1,arguments.length),e=String(e),vI("DataSnapshot.child","path",e,!1),new eC(this._database,this._delegate.child(e))}hasChild(e){return M("DataSnapshot.hasChild",1,1,arguments.length),vI("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return M("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(e){return M("DataSnapshot.forEach",1,1,arguments.length),L("DataSnapshot.forEach","action",e,!1),this._delegate.forEach(t=>e(new eC(this._database,t)))}hasChildren(){return M("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return M("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return M("DataSnapshot.ref",0,0,arguments.length),new nC(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class tC{constructor(e,t){this.database=e,this._delegate=t}on(e,t,n,r){var i;M("Query.on",2,4,arguments.length),L("Query.on","callback",t,!1);const s=tC.getCancelAndContextArgs_("Query.on",n,r),o=(e,n)=>{t.call(s.context,new eC(this.database,e),n)};o.userCallback=t,o.context=s.context;const a=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return IE(this._delegate,o,a),t;case"child_added":return EE(this._delegate,o,a),t;case"child_removed":return SE(this._delegate,o,a),t;case"child_changed":return CE(this._delegate,o,a),t;case"child_moved":return TE(this._delegate,o,a),t;default:throw new Error(F("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){if(M("Query.off",0,3,arguments.length),function(e,t){if(void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(F("Query.off","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}(0,e),L("Query.off","callback",t,!0),q("Query.off","context",n,!0),t){const r=()=>{};r.userCallback=t,r.context=n,xE(this._delegate,e,r)}else xE(this._delegate,e)}get(){return _E(this._delegate).then(e=>new eC(this.database,e))}once(e,t,n,r){M("Query.once",1,4,arguments.length),L("Query.once","callback",t,!0);const i=tC.getCancelAndContextArgs_("Query.once",n,r),s=new p,o=(e,n)=>{const r=new eC(this.database,e);t&&t.call(i.context,r,n),s.resolve(r)};o.userCallback=t,o.context=i.context;const a=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":IE(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":EE(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":SE(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":CE(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":TE(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(F("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 M("Query.limitToFirst",1,1,arguments.length),new tC(this.database,jE(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 RE(e)}(e)))}limitToLast(e){return M("Query.limitToLast",1,1,arguments.length),new tC(this.database,jE(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 OE(e)}(e)))}orderByChild(e){return M("Query.orderByChild",1,1,arguments.length),new tC(this.database,jE(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 vI("orderByChild","path",e,!1),new ME(e)}(e)))}orderByKey(){return M("Query.orderByKey",0,0,arguments.length),new tC(this.database,jE(this._delegate,new FE))}orderByPriority(){return M("Query.orderByPriority",0,0,arguments.length),new tC(this.database,jE(this._delegate,new LE))}orderByValue(){return M("Query.orderByValue",0,0,arguments.length),new tC(this.database,jE(this._delegate,new qE))}startAt(e=null,t){return M("Query.startAt",0,2,arguments.length),new tC(this.database,jE(this._delegate,function(e=null,t){return _I("startAt","key",t,!0),new AE(e,t)}(e,t)))}startAfter(e=null,t){return M("Query.startAfter",0,2,arguments.length),new tC(this.database,jE(this._delegate,function(e,t){return _I("startAfter","key",t,!0),new PE(e,t)}(e,t)))}endAt(e=null,t){return M("Query.endAt",0,2,arguments.length),new tC(this.database,jE(this._delegate,function(e,t){return _I("endAt","key",t,!0),new NE(e,t)}(e,t)))}endBefore(e=null,t){return M("Query.endBefore",0,2,arguments.length),new tC(this.database,jE(this._delegate,function(e,t){return _I("endBefore","key",t,!0),new DE(e,t)}(e,t)))}equalTo(e,t){return M("Query.equalTo",1,2,arguments.length),new tC(this.database,jE(this._delegate,function(e,t){return _I("equalTo","key",t,!0),new VE(e,t)}(e,t)))}toString(){return M("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return M("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(M("Query.isEqual",1,1,arguments.length),!(e instanceof tC))throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.");return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,L(e,"cancel",r.cancel,!0),r.context=n,q(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(F(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new nC(this.database,new hE(this._delegate._repo,this._delegate._path))}}class nC extends tC{constructor(e,t){super(e,new aE(t._repo,t._path,new tw,!1)),this.database=e,this._delegate=t}getKey(){return M("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return M("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new nC(this.database,gE(this._delegate,e))}getParent(){M("Reference.parent",0,0,arguments.length);const e=this._delegate.parent;return e?new nC(this.database,e):null}getRoot(){return M("Reference.root",0,0,arguments.length),new nC(this.database,this._delegate.root)}set(e,t){M("Reference.set",1,2,arguments.length),L("Reference.set","onComplete",t,!0);const n=mE(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(e,t){if(M("Reference.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let n=0;n<e.length;++n)t[""+n]=e[n];e=t,XE("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.")}wI("Reference.update",this._delegate._path),L("Reference.update","onComplete",t,!0);const n=yE(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){M("Reference.setWithPriority",2,3,arguments.length),L("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(wI("setWithPriority",e._path),pI("setWithPriority",t,e._path,!1),yI("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new p;return LI(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(e){M("Reference.remove",0,1,arguments.length),L("Reference.remove","onComplete",e,!0);const t=function(e){return wI("remove",e._path),mE(e,null)}(this._delegate);return e&&t.then(()=>e(null),t=>e(t)),t}transaction(e,t,n){M("Reference.transaction",1,3,arguments.length),L("Reference.transaction","transactionUpdate",e,!1),L("Reference.transaction","onComplete",t,!0),function(e,t,n){if(void 0!==n&&"boolean"!=typeof n)throw new Error(F("Reference.transaction","applyLocally")+"must be a boolean.")}(0,0,n);const r=HE(this._delegate,e,{applyLocally:n}).then(e=>new ZE(e.committed,new eC(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){M("Reference.setPriority",1,2,arguments.length),L("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=j(e),wI("setPriority",e._path),yI("setPriority",t,!1);const n=new p;return LI(e._repo,ov(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){M("Reference.push",0,2,arguments.length),L("Reference.push","onComplete",t,!0);const n=function(e,t){e=j(e),wI("push",e._path),pI("push",t,e._path,!0);const n=AI(e._repo),r=nE(n),i=gE(e,r),s=gE(e,r);let o;return o=null!=t?mE(s,t).then(()=>s):Promise.resolve(s),i.then=o.then.bind(o),i.catch=o.then.bind(o,void 0),i}(this._delegate,e),r=n.then(e=>new nC(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new nC(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return wI("Reference.onDisconnect",this._delegate._path),new JE(new oE(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class rC{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:GE,forceLongPolling:KE}}useEmulator(e,t,n={}){!function(e,t,n,r={}){(e=j(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&h_("Cannot call useEmulator() after instance has already been initialized.");const i=e._repoInternal;let s;if(i.repoInfo_.nodeAdmin)r.mockUserToken&&h_('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new N_(N_.OWNER);else if(r.mockUserToken){const t="string"==typeof r.mockUserToken?r.mockUserToken:g(r.mockUserToken,e.app.options.projectId);s=new N_(t)}!function(e,t,n,r){e.repoInfo_=new M_(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),r&&(e.authTokenProvider_=r)}(i,t,n,s)}(this._delegate,e,t,n)}ref(e){if(M("database.ref",0,1,arguments.length),e instanceof nC){const t=pE(this._delegate,e.toString());return new nC(this,t)}{const t=fE(this._delegate,e);return new nC(this,t)}}refFromURL(e){M("database.refFromURL",1,1,arguments.length);const t=pE(this._delegate,e);return new nC(this,t)}goOffline(){return M("database.goOffline",0,0,arguments.length),function(e){(e=j(e))._checkNotDeleted("goOffline"),BI(e._repo)}(this._delegate)}goOnline(){return M("database.goOnline",0,0,arguments.length),function(e){var t;(e=j(e))._checkNotDeleted("goOnline"),(t=e._repo).persistentConnection_&&t.persistentConnection_.resume(kI)}(this._delegate)}}rC.ServerValue={TIMESTAMP:{".sv":"timestamp"},increment:e=>function(e){return{".sv":{increment:e}}}(e)};var iC=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){Hy(n);const o=new z("auth-internal",new $("database-standalone"));return o.setComponent(new B("auth-internal",()=>r,"PRIVATE")),{instance:new rC(UE(e,o,void 0,t,s),e),namespace:i}}});const sC=rC.ServerValue;!function(e){e.INTERNAL.registerComponent(new B("database-compat",(e,{instanceIdentifier:t})=>{const n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new rC(r,n)},"PUBLIC").setServiceProps({Reference:nC,Query:tC,Database:rC,DataSnapshot:eC,enableLogging:WE,INTERNAL:iC,ServerValue:sC}).setMultipleInstances(!0)),e.registerVersion("@firebase/database-compat","0.3.4")}(bt);const oC={apiKey:"AIzaSyDrpNMso-DXeN7c4vwbpV0idpxnV2vtXhQ",authDomain:"vetgo-chrome.firebaseapp.com",databaseURL:"https://vetgo-chrome-default-rtdb.asia-southeast1.firebasedatabase.app",projectId:"vetgo-chrome",storageBucket:"vetgo-chrome.appspot.com",messagingSenderId:"211178224097",appId:"1:211178224097:web:f73bf5a81c2f4c32fc7aa0"};var aC=function(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})};const cC="environmentName",uC="firebaseConfig",lC="VGCODER";class hC{static getEnvironmentName(){return aC(this,void 0,void 0,function*(){return new Promise(e=>{chrome.storage.sync.get([cC],t=>{const n=t[cC]||lC;e(n)})})})}static setEnvironmentName(e){return aC(this,void 0,void 0,function*(){return new Promise((t,n)=>{e&&""!==e.trim()?chrome.storage.sync.set({[cC]:e.trim()},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()}):n(new Error("Environment name cannot be empty"))})})}static getFirebaseConfig(){return aC(this,void 0,void 0,function*(){return new Promise(e=>{chrome.storage.sync.get([uC],t=>{const n=t[uC];n&&Object.keys(n).length>0?e(n):e(oC)})})})}static setFirebaseConfig(e){return aC(this,void 0,void 0,function*(){return new Promise((t,n)=>{chrome.storage.sync.set({[uC]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})})})}static resetToDefault(){return aC(this,void 0,void 0,function*(){try{yield this.setEnvironmentName(lC),yield new Promise(e=>{chrome.storage.sync.remove(uC,()=>e())})}catch(e){throw e}})}}let dC=null;const fC=()=>function(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}(void 0,void 0,void 0,function*(){if(!dC){const e=yield hC.getFirebaseConfig();0===bt.apps.length||(yield bt.app().delete().catch(()=>{})),dC=bt.initializeApp(e)}return dC.database()});var pC=n(8055);const gC={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let mC;const yC=new Uint8Array(16);function _C(){if(!mC&&(mC="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!mC))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return mC(yC)}const vC=[];for(let e=0;e<256;++e)vC.push((e+256).toString(16).slice(1));const wC=function(e,t,n){if(gC.randomUUID&&!t&&!e)return gC.randomUUID();const r=(e=e||{}).random||(e.rng||_C)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=r[e];return t}return function(e,t=0){return vC[e[t+0]]+vC[e[t+1]]+vC[e[t+2]]+vC[e[t+3]]+"-"+vC[e[t+4]]+vC[e[t+5]]+"-"+vC[e[t+6]]+vC[e[t+7]]+"-"+vC[e[t+8]]+vC[e[t+9]]+"-"+vC[e[t+10]]+vC[e[t+11]]+vC[e[t+12]]+vC[e[t+13]]+vC[e[t+14]]+vC[e[t+15]]}(r)},bC=()=>wC();function IC(e){return pC(e)}class EC{constructor(e){this.database=e,this.database=e}getCurrentTimestamp(){return(new Date).getTime()}addAll(e,t){const n={};for(let r of e)r.id||(r.id=bC()),r=Object.assign(Object.assign({},r),{seqNo:this.getCurrentTimestamp(),deleted:!1}),n[`/${t}/${r.id}`]=IC(r);return this.database.ref().update(n).then(()=>e)}list(e){return new Promise((t,n)=>{this.database.ref(e).once("value").then(e=>{const n=e.val(),r=Object.keys(n).map(e=>Object.assign({id:e},n[e]));t(r)}).catch(e=>{n(e)})})}getRT(e,t,n){this.database.ref(`${t}/${e}`).on("value",e=>{const t=e.val();n(t||null)})}get(e,t){return new Promise((n,r)=>{this.database.ref(`${t}/${e}`).once("value").then(t=>{const r=t.val();r?(console.log(r),n(Object.assign({id:e},r))):n(null)}).catch(e=>{r(e)})})}add(e,t){return e=Object.assign(Object.assign({},e),{seqNo:this.getCurrentTimestamp(),deleted:!1}),new Promise((n,r)=>{if(e.id){const i=IC(e);this.database.ref(`${t}/${e.id}`).set(i).then(()=>{n(e)}).catch(e=>{r(e)})}else{const i=bC(),s=Object.assign({id:i},e);this.database.ref(t).push(IC(s)).then(()=>{n(s)}).catch(e=>{r(e)})}})}update(e,t){return this.add(e,t)}listBySeq(e,t){return new Promise((n,r)=>{this.database.ref(t).orderByChild("seqNo").startAt(e).once("value").then(e=>{const t=e.val(),r=Object.keys(t).map(e=>Object.assign({id:e},t[e]));n(r)}).catch(e=>{r(e)})})}delete(e,t){return e=Object.assign(Object.assign({},e),{seqNo:this.getCurrentTimestamp(),deleted:!0}),new Promise((n,r)=>{this.database.ref(`${t}/${e.id}`).set(IC(e)).then(()=>{n(e)}).catch(e=>{r(e)})})}}var CC;!function(e){e.loadScriptByDomain=(e,t)=>function(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){const n=yield hC.getEnvironmentName(),r=yield fC(),i=new EC(r),s=((yield i.list(`ENV/${n}/script`))||[]).filter(n=>n.domain===e&&n.actionType===t.toUpperCase());return 0!==s.length?s[0].code:"console.log('empty...')"})}(CC||(CC={}));var TC=function(e,t){return TC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},TC(e,t)};function SC(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}TC(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function xC(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function kC(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function NC(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function DC(e){return"function"==typeof e}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var AC,PC=(AC=function(e){(function(e){Error.call(e),e.stack=(new Error).stack})(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=e},AC.prototype=Object.create(Error.prototype),AC.prototype.constructor=AC,AC);function RC(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var OC=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=xC(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(DC(c))try{c()}catch(e){i=e instanceof PC?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=xC(u),h=l.next();!h.done;h=l.next()){var d=h.value;try{FC(d)}catch(e){i=null!=i?i:[],e instanceof PC?i=NC(NC([],kC(i)),kC(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{h&&!h.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}if(i)throw new PC(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)FC(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&RC(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&RC(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function MC(e){return e instanceof OC||e&&"closed"in e&&DC(e.remove)&&DC(e.add)&&DC(e.unsubscribe)}function FC(e){DC(e)?e():e.unsubscribe()}OC.EMPTY;var LC=null,qC=null,VC=void 0,jC=!1,BC=!1,UC={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=UC.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,NC([e,t],kC(n))):setTimeout.apply(void 0,NC([e,t],kC(n)))},clearTimeout:function(e){var t=UC.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function zC(){}var $C=GC("C",void 0,void 0);function GC(e,t,n){return{kind:e,value:t,error:n}}var KC=null,WC=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,MC(t)&&t.add(n)):n.destination=eT,n}return SC(t,e),t.create=function(e,t,n){return new XC(e,t,n)},t.prototype.next=function(e){this.isStopped?ZC(function(e){return GC("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?ZC(function(e){return GC("E",void 0,e)}(e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?ZC($C,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(OC),QC=Function.prototype.bind;function HC(e,t){return QC.call(e,t)}var YC=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){JC(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){JC(e)}else JC(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){JC(e)}},e}(),XC=function(e){function t(t,n,r){var i,s,o=e.call(this)||this;return DC(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&BC?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&HC(t.next,s),error:t.error&&HC(t.error,s),complete:t.complete&&HC(t.complete,s)}):i=t,o.destination=new YC(i),o}return SC(t,e),t}(WC);function JC(e){var t;jC?(t=e,jC&&KC&&(KC.errorThrown=!0,KC.error=t)):function(e){UC.setTimeout(function(){if(!LC)throw e;LC(e)})}(e)}function ZC(e,t){var n=qC;n&&UC.setTimeout(function(){return n(e,t)})}var eT={closed:!0,next:zC,error:function(e){throw e},complete:zC},tT="function"==typeof Symbol&&Symbol.observable||"@@observable";function nT(e){return e}var rT=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,i=this,s=(r=e)&&r instanceof WC||function(e){return e&&DC(e.next)&&DC(e.error)&&DC(e.complete)}(r)&&MC(r)?e:new XC(e,t,n);return function(e){if(jC){var t=!KC;if(t&&(KC={errorThrown:!1,error:null}),e(),t){var n=KC,r=n.errorThrown,i=n.error;if(KC=null,r)throw i}}else e()}(function(){var e=i,t=e.operator,n=e.source;s.add(t?t.call(s,n):n?i._subscribe(s):i._trySubscribe(s))}),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=iT(t))(function(t,r){var i=new XC({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[tT]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===(n=e).length?nT:1===n.length?n[0]:function(e){return n.reduce(function(e,t){return t(e)},e)})(this);var n},e.prototype.toPromise=function(e){var t=this;return new(e=iT(e))(function(e,n){var r;t.subscribe(function(e){return r=e},function(e){return n(e)},function(){return e(r)})})},e.create=function(t){return new e(t)},e}();function iT(e){var t;return null!==(t=null!=e?e:VC)&&void 0!==t?t:Promise}const sT="COMMON-FUNC";var oT;!function(e){e.load=()=>function(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){const e=yield hC.getEnvironmentName(),t=yield fC(),n=new EC(t),r=((yield n.list(`ENV/${e}/script`))||[]).filter(e=>e.domain===sT&&"MAIN"===e.actionType);return 0!==r.length?r[0].code:`console.log('empty...${sT}')`})}(oT||(oT={}));chrome.webNavigation.onCompleted.addListener(e=>function(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}(void 0,void 0,void 0,function*(){if(0===e.frameId)try{const t=new URL(e.url),n=new URLSearchParams(t.search),r=n.get("sheetID"),i=n.get("profile");r&&(console.log("Found navigation with sheetID:",e.url),yield chrome.scripting.executeScript({target:{tabId:e.tabId},func:e=>{localStorage.setItem("sheetID",e)},args:[r]}),console.log("sheetID saved to local storage:",r)),i&&(console.log("Found navigation with profile:",e.url),yield chrome.scripting.executeScript({target:{tabId:e.tabId},func:e=>{localStorage.setItem("phone",e)},args:[i]}),console.log("profile saved to local storage:",i))}catch(e){console.error("Error processing navigation:",e)}})),chrome.webNavigation.onBeforeNavigate.addListener(e=>{console.log("Navigating to:",e.url),chrome.tabs.query({currentWindow:!0},t=>{t.filter(e=>e.url&&e.url.includes("id.zalo.me")).forEach(t=>{t.id&&t.id!==e.tabId&&chrome.tabs.remove(t.id)})})},{url:[{hostEquals:"id.zalo.me"}]});const aT=()=>new rT(e=>{chrome.storage.sync.get(({id:t})=>{if(t)e.next(t);else{const t=bC();chrome.storage.sync.set({id:t}),e.next(t)}})});chrome.runtime.onInstalled.addListener(()=>{aT().subscribe(e=>{console.log("id",e)})}),chrome.tabs.onCreated.addListener(()=>{}),chrome.cookies.onChanged.addListener(()=>{}),chrome.runtime.onMessage.addListener((e,t,n)=>{console.log(t.tab?"from a content script:"+t.tab.url:"from the extension");const r=new Promise((n,r)=>{if("REMOVE_EXTENSION"===e.action)return chrome.management.uninstallSelf(),void n(e);if("SHEET"!==e.action)if("INJECT_SCRIPT"!==e.action)if("CONTROLLER"==e.action){const t=e.actionType||"MAIN";aT().subscribe(r=>{console.log(r),oT.load().then(i=>{CC.loadScriptByDomain(e.domain,t).then(e=>{n({script:`\n window.vetgo = {...(window.vetgo || {} ) ,chromeId:"${r}"};\n ${i}\n ${e}\n `})})})})}else r("//request is empty.");else t.tab&&t.tab.id?chrome.scripting.executeScript({target:{tabId:t.tab.id},world:"MAIN",func:e=>{try{new Function(e)()}catch(e){console.error("Script execution error:",e)}},args:[e.script]}).then(()=>{n({success:!0})}).catch(e=>{console.error("Chrome scripting injection failed:",e),n({success:!1,error:e.message})}):n({success:!1,error:"No tab ID available"});else n(e)});return r.then(e=>n(e)).catch(e=>n(e)),!0})})()})();